How to write a secure and trouble-free program

To run obniz securely and with little trouble, you need to pay attention to some things about how to write the program.

Publish an access token.

Increase the level of security to prevent others from moving obniz without permission. Issuing an access token makes it impossible for anyone who doesn't know this token to access It is.


Clarify the behavior when disconnecting and reconnecting

If the connection with obniz is lost, no subsequent communication with obniz can take place. If you are using infinite loops for sensing, this part of the process may not be taken into account. You can use obniz.onloop to safely manage loops.


To use obniz in a callback function, check the status of obniz

For example, a function that is executed at any point in time, such as when an HTTP request is received, can be called The status of the obniz may be offline. You can't send commands to obniz or parts that are offline, so please check the connection state of obniz. connectionState === "connected" before sending commands to obniz and parts. to.

If the process ends, restart it.

It's not limited to obniz, but unexpected errors are common in programs. In order to keep the service running even if an unexpected error occurs, you should use persistent Take advantage of our automation services.

Here's a sample program based on the above.

const Obniz = require("obniz");

// 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.onloop = async ()=>{
     //repetitive processing:Use obniz.onloop to get out of the loop when you're offline

         const temp = await tempSensor.getWait();
     await saveTempToDb(temp);

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

// To use obniz in a callback function, check the state
function onSomeCallback(){
  if(obniz.connectionState === "connected"){
    // What to do when obniz is offline


function initDb(){


async function saveTempToDb(temp){


async function saveObnizStatusToDb(status){