// Requirements and connection
const spinalCore = require('spinal-core-connectorjs');
const models = require('../spinal-models/models.js');
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";
const conn = spinalCore.connect(`http://${process.env.SPINAL_USER_ID}:${process.env.SPINAL_PASSWORD}@${process.env.SPINALHUB_IP}:${process.env.SPINALHUB_PORT}/`);
// Gives random values to the hygrometry and temperature of a sensor
function simulate(sensor) {
const hydro = Math.floor(Math.random() * 100);
const degrees = Math.floor(Math.random() * 30);
sensor.hygrometry.set(hydro);
sensor.temperature.set(degrees);
// Repeats every second
setTimeout(() => {
console.log(sensor.name.get() + ": data has changed");
simulate(sensor);
}, 1000);
};
// Finds a Sensor in the SensorList, if it doesn't exist, creates it
function getSensorById(list, id) {
let item;
for (let i = 0; i < list.sensors.length; i++) {
if (list.sensors[i].id.get() === id) {
item = list.sensors[i];
break;
}
}
if (typeof item === "undefined") {
item = new models.SensorModel();
item.id.set(id);
item.name.set("sensor" + id);
list.sensors.push(item);
}
return item;
}
// This function will be called if the list is successfully loaded
function onSuccess(list) {
simulate(getSensorById(list, 0));
};
// This function will be called if the list cannot be loaded
function onFailure() {
const list = new models.SensorListModel();
const item = getSensorById(list, 0);
spinalCore.store(conn, list, "List", () => {
simulate(item);
});
};
spinalCore.load(conn, "List", onSuccess, onFailure);
|