AWS Lambda: Manage one obniz with one function

It can be useful to use serverless for periodic runs, such as once an hour.

There are a few things to keep in mind when combining obniz and serverless.

Make sure there is no confusion in the startup.

One of the features of serverless systems is the ease of multiplexing. It is possible to control one obniz from a program, but there is a limit to the number (1 (up to 5 programs per obniz at the same time), and you need to consider how to write the program. So, we recommend not to use lambda in that way until you have a deeper understanding of it. In other words, you need to control the lambda processes so that they don’t start at the same time.

In the lambda settings, there is a number of simultaneous executions, so set this to 1. If you do so, an error will occur if you try to start the second one, and it will not start.

Consider the time limit.

After the lambda function is launched, the connection and authentication to obniz is performed, so the time required to connect and authenticate to obniz will be reduced by It may take about 1 second to connect to obniz, so you may have to wait for a few more seconds to get the data. I recommend that you allow about 5 seconds for the time of

Consider if you can’t connect.

obniz is not always online, and depending on the signal conditions, it may be offline It is also possible that you have You need to program for the possibility of being offline.

Specific implementation

For example, let’s say you are using AWS lambda to retrieve data from a temperature sensor.

The devices are automatically connected from lambda, so there is no need to put in place an API gateway or anything like that There is no such case. Please put it on the case that you want to access it by URL separately.

const Obniz = require("obniz");

exports.handler = async (event) => {

    // Disable auto_connect to connect manually
    const obniz = new Obniz("obniz_id_hiere", {auto_connect: false, access_token: targetObniz.accessToken});

    // Connect to obniz. If it doesn't connect within 3 seconds, it will time out.
    const connected =  await obniz.connectWait({ timeout: 3 });
    if (!connected) {
        // How to handle obniz when it is off-line
        const response = {
            statusCode: 404,
            body: JSON.stringify({error: "obniz is not online"}),
        };
        return response;
    }

    //initialization
    const tempSensor = obniz.wired("LM35DZ", { gnd:0 , output:1, vcc:2});
    const temp = await tempSensor.getWait();

    //Disconnect from obniz on exit (if you don't do this, you'll still have a connected session)
    obniz.close();

    const response = {
        statusCode: 200,
        body: JSON.stringify({temp}),
    };

    return response;
};