Sending real time temperature messages to Azure IoT hub with NodeJS

And to conclude one series of post where I played for 3 days with the PI, grooveboard and some sensors, with this last step I wanted to send the messages that actually we need in the IoT Hub to be processed later.

For this we need to install this package

npm install azure-iot-device  

After that its installed we need to define connection strings (to the device), I assume here you know how to create a device:

var connectionString = 'HostName=iothubdemo1.azure-devices.net;DeviceId=helloworlddevice2;SharedAccessKey=urkey';  
// use factory function from AMQP-specific package 
var clientFromConnectionString = require('azure-iot-device-amqp').clientFromConnectionString;  
// AMQP-specific factory function returns Client object from core package 
var client = clientFromConnectionString(connectionString);  
// use Message object from core package 
var Message = require('azure-iot-device').Message;  

We did some refactoring, we need to connect the client first, and then init the board

 var connectCallback = function (err) {
    if (err) {
        console.error('Could not connect: ' + err);
    } else {
        console.log('Client connected');
        board.init();
    };
};

client.open(connectCallback);  

And then on the board initiation, we can actually get the temperature and send the message to the cloud:

Full code below:

var i2c = require('i2c-bus')  
var sleep = require('sleep')  
var GrovePi = require('node-grovepi').GrovePi  
var DHTDigitalSensor = GrovePi.sensors.DHTDigital  
var connectionString = 'HostName=iothubdemo1.azure-devices.net;DeviceId=helloworlddevice2;SharedAccessKey=urkey';  
// use factory function from AMQP-specific package 
var clientFromConnectionString = require('azure-iot-device-amqp').clientFromConnectionString;  
// AMQP-specific factory function returns Client object from core package 
var client = clientFromConnectionString(connectionString);  
// use Message object from core package 
var Message = require('azure-iot-device').Message;

var Board = GrovePi.board  
var DISPLAY_RGB_ADDR = 0x62;  
var DISPLAY_TEXT_ADDR = 0x3e;

function setRGB(i2c1, r, g, b) {  
  i2c1.writeByteSync(DISPLAY_RGB_ADDR,0,0)
  i2c1.writeByteSync(DISPLAY_RGB_ADDR,1,0)
  i2c1.writeByteSync(DISPLAY_RGB_ADDR,0x08,0xaa)
  i2c1.writeByteSync(DISPLAY_RGB_ADDR,4,r)
  i2c1.writeByteSync(DISPLAY_RGB_ADDR,3,g)
  i2c1.writeByteSync(DISPLAY_RGB_ADDR,2,b)
}

function textCommand(i2c1, cmd) {  
  i2c1.writeByteSync(DISPLAY_TEXT_ADDR, 0x80, cmd);
}

function setText(i2c1, text) {  
  textCommand(i2c1, 0x01) // clear display
  sleep.usleep(50000);
  textCommand(i2c1, 0x08 | 0x04) // display on, no cursor
  textCommand(i2c1, 0x28) // 2 lines
  sleep.usleep(50000);
  var count = 0;
  var row = 0;
  for(var i = 0, len = text.length; i < len; i++) {
    if(text[i] === '\n' || count === 16) {
      count = 0;
      row ++;
        if(row === 2)
          break;
      textCommand(i2c1, 0xc0)
      if(text[i] === '\n')
        continue;
    }
    count++;
    i2c1.writeByteSync(DISPLAY_TEXT_ADDR, 0x40, text[i].charCodeAt(0));
  }
}

var board = new Board({  
    debug: true,
    onError: function(err) {
      console.log('Something wrong just happened')
      console.log(err)
    },
    onInit: function(res) {
      if (res) {
        console.log('GrovePi Version :: ' + board.version())
        var dhtSensor = new DHTDigitalSensor(7, DHTDigitalSensor.VERSION.DHT11, DHTDigitalSensor.CELSIUS)


        // DHT Sensor
        console.log('DHT Digital Sensor (start watch)')
        dhtSensor.on('change', function(res) {
            var temp= res[2];
            //var humidity = res[1];
            console.log(res);
            var i2c1 = i2c.openSync(1);
            if(temp>28){
                setText(i2c1, 'Temp:' + temp);
                setRGB(i2c1, 255,0, 0);
            }
            else if (temp>27 && temp <28){
                setText(i2c1, 'Temp:' + temp);
                setRGB(i2c1, 255,255, 0);
            }
            else{
                setText(i2c1, 'Temp:' + temp);
                setRGB(i2c1, 0, 0, 255);
            }

            var msg = new Message(temp);
            client.sendEvent(msg, function (err) {
            if (err) {
                console.log(err.toString());
            } else {
                console.log('Message sent');
            };
            });

            i2c1.closeSync();
        })
        dhtSensor.watch(500) // milliseconds


      }
    }
  })


 var connectCallback = function (err) {
    if (err) {
        console.error('Could not connect: ' + err);
    } else {
        console.log('Client connected');
        board.init();
    };
};


client.open(connectCallback);