Wait and Repeat

When you want to pause a device like for waiting a response from a sensor use wait(). It pause both device and program.

led.on();
await obniz.wait(1000); // led ON for 1sec.
led.off();

Remove await to keep working program side.

var time = new Date();
led.on();
obniz.wait(1000); // led ON 1sec.
led.off();
console.log((new Date()).getTime() - time.getTime()) // 0 or very few ms. not 1000ms.

Repeat

You need to care when you do repeatable task.

  • When disconnected from a device, break a loop.
  • avoid freeze.

Most safety loop is below.

while(obniz.connectionState === 'connected') {
  try {
    // something code
    await obniz.pingWait(); // check communication
  } catch(e) {
    // break or throw a error
  }
}

connectionState represents connection status for a device.
pingWait() send a data and wait for a response.
Above code will break a loop if offline and avoiding a freeze and also clean up communication line by using ping.

But pingWait() take a time because it wait until response received. If distance is too far like oversea, it take over 10 msec. For improving loop performance, instead of pingWait(), use setTimeout() or obniz.wait(). But It never mind data transfer, you need to care that when you need to send or receive mass data.

while(obniz.connectionState === 'connected') {
  try {
    // something code
    await obniz.wait(1);
  } catch(e) {
    // break or throw a error
  }
}