Now that we have our model, we need to monitor its state. for this we are going to simulate a temperature sensor that modify its attribute “temperature”. Later we will be able to connect with a real IoT sensor. Make a new folder called virtualTempSensorOrgan where we are going to define our process.
Code Block |
---|
| ~/fine-wine-system$ mkdir virtualTempSensorOrgan |
An organ has to be linked with the Spinalhub via a connector. For this tutorial, we use the Node.js connector, which has already been installed at the first step. Inside the organ folder, create the file called index.js with the code below. myOrganvirtualTempSensorOrgan/index.js
Code Block |
---|
language | js |
---|
theme | DJango |
---|
linenumbers | true |
---|
| // 1
var spinalCore = require('spinal-core-connectorjs');
require('../spinal-model-wine-cellar/model.js');
// 2
console.log("Configuration Environment not found, using default config");
process.env.SPINALHUB_PORT = 7777;
process.env.SPINALHUB_IP = "127.0.0.1";
process.env.SPINAL_USER_ID = 168;
process.env.SPINAL_PASSWORD = "JHGgcz45JKilmzknzelf65ddDadggftIO98P";
var conn = spinalCore.connect("http`http://${process.env.SPINAL_USER_ID}:${process.env.SPINAL_PASSWORD}@${process.env.SPINALHUB_IP}:${process.env.SPINALHUB_PORT}/"`);
// 3: Create and store the wineCave model or load it if it exists
spinalCore.load(conn, "myCellar",
function(myCellar) { //success callback
console.log('load & sync existing model if it exists');
setSensorData(myCellar.temperature);
},
function(myCellar) { //error callback
myCellar= new WineCellarModel();
spinalCore.store(conn, myCellar, "myCellar", function () {
console.log('store & sync new model, first connection');
setSensorData(myCellar.temperature);
});
}
);
i = 0;
sampleRate = 2;
function setSensorData(currentTemperature) {
var simTemp;
console.log("Sending sensored temperature");
simTemp = 15 + 5 * Math.sin(i);
i += 0.5;
currentTemperature.set(simTemp );
setTimeout(function() {
setSensorData(currentTemperature); }, sampleRate * 1000);
}; |
These are the steps that the code is following: - Requires connector and model.
- Establishes a connection with the hub, with write/read rights, using a user, password and environment variables. To understand more about configuration, please head to the configuration docs.
- Creates and synchronize an instance of our button model and stores it in the hub. We first try to load and sync an existing instance from the hub, if no instance exist, than we create a new one
- Changes the data periodically through the setSensorData() function.
The current system folder organization so far is:
|