AWS Lambda: Manage multiple obniz with one function

Serverless is convenient for regular runs, but there is some network response wait time, such as connecting to obniz, which is a waste of money.

To solve that, let's manage multiple obniz with a single lambda function.

The prerequisites are the same as for one car.

  • Make sure there is no confusion in the startup.
  • Consider the time limit.
  • Consider if you can't connect.

For more information, see AWS Lambda: Managing one obniz with 1 function

The way the program is written changes a bit.

Create an instruction function for one obniz as oneTask and complete the process in that function to do. Run it for a few minutes of obniz and wait until it's all done in Promise.all I will.

const Obniz = require("obniz");

const obnizIdList = [
  {obnizId: "obniz_id_1", accessToken: "access_token_1"},
  {obnizId: "obniz_id_2", accessToken: "access_token_2"},
  {obnizId: "obniz_id_3", accessToken: "access_token_3"},
  ...
  {obnizId: "obniz_id_99", accessToken: "access_token_99"},
];

// For one obniz
async function oneTask(targetObniz) {
  const obniz = new Obniz(targetObniz.obnizId, {auto_connect: false, access_token: targetObniz.accessToken});

  try {
    const connected = await obniz.connectWait({timeout: 3});
    if (!connected) {
      return new Error("obniz " + targetObniz.obnizId + " is not online");
    }

    const tempSensor = obniz.wired("LM35DZ", {gnd: 0, output: 1, vcc: 2});
    const temp = await tempSensor.getWait();
    obniz.close();
  } catch (e) {
    return e;
  }
  return null;

}

exports.handler = async (event) => {

  let tasks = [];
  for (const targetObniz of obnizIdList) {
    tasks.push(oneTask(targetObniz));
  }

  let results = await Promise.all(tasks);

  for (const result of results) {
    if (result) {
      const response = {
        statusCode: 500,
        body: JSON.stringify({status: "error", error: result}),
      };
    }

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

  return response;
};