AWS EC2: Managing one device on one machine

When building a robust system that uses obniz, there are a few things to keep in mind.

For example, consider an app that records sensor values in a database on AWS.

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.

Here's a sample program based on the above.

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

// Set the access_token.
const obniz = new Obniz("obniz_id_here", { access_token:"xxxxxxxxxxx" })

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

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

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

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

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

function initDb(temp){
  ...
}

async function saveTempToDb(temp){
  ...
}

async function saveObnizStatusToDb(status){
  ...
}

At run time, use pm2 and run as follows

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

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

pm2 stop app