Publishing events

At this point in the chapter, we have explored Node.js scripts that are capable of reading both soil moisture and temperatures, and we have also looked at the code that can turn on and turn off the relay that lets the water flow to the plant.

The goal is now to publish both of these values to the IBM Watson IoT Platform.

As shown in the previous chapter, it's necessary to create a device and note the credentials, so that we can use them to connect the device to the platform. The following code performs the regular publishing of the events:

var iotf = require("ibmiotf");
var mraa = require('mraa');
var config = require("./device.json");
var deviceClient = new iotf.IotfDevice(config);
var temperatureSensor = new mraa.Aio(3);
var moistureSensor = new mraa.Aio(0);
var RESISTOR = 100000;
var THERMISTOR = 4250;
var getTemperature = function() {
var sensorReading = temperatureSensor.read();
var R = 1023 / sensorReading - 1;
R = RESISTOR * R;
var temperature = 1 / (Math.log(R/RESISTOR)/THERMISTOR+1/298.15)-273.15;
return temperature;
};
var getSoilMoisture = function() {
var sensorReading = moistureSensor.read();
return sensorReading;
};
deviceClient.connect();
deviceClient.on('connect', function(){
console.log("connected");
setInterval(function function_name () {
deviceClient.publish('status', 'json', '{ "temperature": ' + getTemperature() +', "soilMoisture": ' + getSoilMoisture() + '}', 2);
},300000);
});

When the scripts start, they will load the configuration from the device.json file, connect to the IBM Watson IoT Platform, and then publish an event with the current soil moisture and temperature every five minutes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.79.33