AWS EC2: Managing multiple devices (2 to 100) on a single machine

Obniz can manage about 100 obniz with a single program by creating a good system.

For example, consider an app that records sensor values in a database on AWS. All devices are equivalent, and the sensors are connected to any device for the same purpose, and any device can be used to Suppose you want the same behavior.

The system configuration in this case is the same as when dealing with a single obniz.

In this case, since the connection between obniz↔EC2 is accessed from EC2 to obniz, there is no need to open the port or otherwise allow access to EC2 from the outside.

You can integrate with obniz from a closed EC2 while keeping it secure.

There are some things to keep in mind in the way you write and execute the program.

  • Publish an access token.
  • Clarify the behavior when disconnecting and reconnecting
  • If the process dies, make sure to restart it.

For more information, see our page on how to write secure and trouble-free programs.

In this program, each sensor value is moved independently, so it's simple to use a single unit with When you use it, you should have multiple programs running. There is another way to launch the process, but that would take up excessive resources, so you can use Manage all obniz in one process, up to 100 units in one process It is simple and easy to manage.

Here's a sample program based on the above.

const Obniz = require("obniz");
initDb();

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(const targetObniz of obnizIdList){
  const obnizId = targetObniz.obnizId;
  const accessToken = targetObniz.accessToken;

    // Set the access_token.
    const obniz = new Obniz(obnizId, { access_token: accessToken })

    obniz.onconnect = async ()=>{
      // Processing at connection (initial settings, etc.)
      await saveObnizStatusToDb(obnizId, "connected");

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

        obniz.repeat(async ()=>{
         //repetitive processing

             const temp = await tempSensor.getWait();
             console.log(obnizId, temp);
         await saveTempToDb(obnizId, temp);
      });
    }


    obniz.onclose = async ()=>{
      // Disconnection processing (e.g., resetting callbacks)
      await saveObnizStatusToDb(obnizId, "disconnected");
    }

}

function initDb(){
  ...
}

async function saveTempToDb(obnizId, temp){
  ...
}

async function saveObnizStatusToDb(obnizId, status){
  ...
}

At run time, use pm2 and run as follows

npm install pm2 -g
pm2 start ./app.js --name app

Since it is persistent, the stop also stops through pm2.

pm2 stop app