Ajout gestion Look & Sync firmwares, et routes BST

This commit is contained in:
Arnaud Nelissen
2025-09-17 17:45:46 +02:00
parent e715c265ad
commit 73add80cab
27 changed files with 2209 additions and 386 deletions

32
app.js
View File

@@ -10,6 +10,8 @@ const https = require('https');
const certificate = fs.readFileSync(process.env.CLIENT_CRT || 'cert/client.crt', 'utf8');
const privateKey = fs.readFileSync(process.env.CLIENT_KEY || 'cert/client.key', 'utf8');
const firmwares = './resources/firmwares/'
const credentials = {
key: privateKey,
cert: certificate,
@@ -18,6 +20,7 @@ const credentials = {
};
const dbcontroller = require('./db');
const {firmware} = require('./services');
const routes = require('./routes')
const app = express();
@@ -39,6 +42,12 @@ console.log(' T E C H N O L O G I E S');
console.log('');
console.log('');
firmware.init(firmwares)
.then((err) => {
if (err) { console.log('Unable to initialize firmware service')}
else { console.log ('Firmware service initialized') }
})
///// Startup MongoDB Client
dbcontroller.init()
.then((err) => {
@@ -66,6 +75,10 @@ dbcontroller.init()
console.log('HTTPS Port: ' + https_port);
console.log('-------------------------------------------------------');
});
///// Set keep-alive timeout
httpServer.keepAliveTimeout = 120*1000;
httpsServer.keepAliveTimeout = 120*1000;
}
})
@@ -81,7 +94,7 @@ app.use(function (req, res, next) {
});
app.use(function (req, res, next) {
if (!req.body.length) {
if (!req.body) {
// No body
//////////
console.log('Got empty frame');
@@ -100,6 +113,9 @@ app.use(function (req, res, next) {
cbor_length = req.body.length;
///// Decode CBOR body
cbor.decodeFirst(req.body, (err, decoded) => {
///// Check for error
if (err) { res.sendStatus(418); return; }
///// Assign decoded data
req.body = decoded;
json_length = JSON.stringify(decoded).length
@@ -129,7 +145,19 @@ app.use(function (req, res, next) {
/////////////////////////
// Redefine send function
res.send = function (body) {
if (req.is('application/cbor') || req.acceptsEncodings("application/cbor") || req.acceptsEncodings("cbor")) {
if (Buffer.isBuffer(body)) {
// Octet/Stream frame
/////////////////////
///// Set header
res.set('Content-Type', 'application/octet-stream');
// Log statistics
console.log('Stream:');
console.log(body.toString('hex'))
console.log(body.length + ' Bytes');
} else if (req.is('application/cbor') || req.acceptsEncodings("application/cbor") || req.acceptsEncodings("cbor")) {
// CBOR Frame
/////////////
console.log('Send CBOR frame');

View File

@@ -0,0 +1,278 @@
const services = require('../services')
const { device } = services
const getPrograms = async (req, res, next) => {
///// Emit event to server
try {
const programs = await device.getPrograms(req.params.msn);
res.send(programs);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const postPrograms = async (req, res, next) => {
///// Emit event to server
try {
const programs = await device.postPrograms(req.params.msn, req.body.programs, req.body.timestamp);
res.send(programs);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const putPrograms = async (req, res, next) => {
try {
var programs = await device.postPrograms(req.params.msn, req.body.programs, req.body.timestamp);
res.send(programs);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const deletePrograms = async (req, res, next) => {
///// Emit event to server
try {
const programs = await device.postPrograms(req.params.msn, [], req.body.timestamp);
res.send(programs);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const getConfiguration = async (req, res, next) => {
///// Emit event to server
try {
const configuration = await device.getConfiguration(req.params.msn);
res.send(configuration);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const postConfiguration = async (req, res, next) => {
///// Emit event to server
try {
const configuration = await device.postConfiguration(req.params.msn, req.body.configuration, req.body.timestamp);
res.send(configuration);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const putConfiguration = async (req, res, next) => {
try {
var configuration = await device.postConfiguration(req.params.msn, req.body.configuration, req.body.timestamp);
res.send(configuration);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const deleteConfiguration = async (req, res, next) => {
///// Emit event to server
try {
const configuration = await device.postConfiguration(req.params.msn, [], req.body.timestamp);
res.send(configuration);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const getSlots = async (req, res, next) => {
///// Emit event to server
try {
const slots = await device.getSlots(req.params.msn);
res.send(slots);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const postSlots = async (req, res, next) => {
///// Emit event to server
try {
const slots = await device.postSlots(req.params.msn, req.body.slots, req.body.timestamp);
res.send(slots);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const putSlots = async (req, res, next) => {
try {
var slots = await device.postSlots(req.params.msn, req.body.slots, req.body.timestamp);
res.send(slots);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const deleteSlots = async (req, res, next) => {
///// Emit event to server
try {
const slots = await device.postSlots(req.params.msn, [], req.body.timestamp);
res.send(slots);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const getManualCommand = async (req, res, next) => {
///// Emit event to server
try {
const manualCommand = await device.getManualCommand(req.params.msn);
res.send(manualCommand);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const postManualCommand = async (req, res, next) => {
///// Emit event to server
try {
const manualCommand = await device.postManualCommand(req.params.msn, req.body.manualCommand);
res.send(manualCommand);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const putManualCommand = async (req, res, next) => {
try {
var manualCommand = await device.postManualCommand(req.params.msn, req.body.manualCommand);
res.send(manualCommand);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const deleteManualCommand = async (req, res, next) => {
///// Emit event to server
try {
const manualCommand = await device.postManualCommand(req.params.msn, null);
res.send(manualCommand);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const getStatusCommand = async (req, res, next) => {
///// Emit event to server
try {
const statusCommand = await device.getStatusCommand(req.params.msn);
res.send(statusCommand);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const postStatusCommand = async (req, res, next) => {
///// Emit event to server
try {
const statusCommand = await device.postStatusCommand(req.params.msn, req.body.statusCommand);
res.send(statusCommand);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const putStatusCommand = async (req, res, next) => {
try {
var statusCommand = await device.postStatusCommand(req.params.msn, req.body.statusCommand);
res.send(statusCommand);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const deleteStatusCommand = async (req, res, next) => {
///// Emit event to server
try {
const statusCommand = await device.postStatusCommand(req.params.msn, null);
res.send(statusCommand);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const getAcknowledgedAlerts = async (req, res, next) => {
///// Emit event to server
try {
const acknowledgedAlerts = await device.getAcknowledgedAlerts(req.params.msn);
res.send(acknowledgedAlerts);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const postAcknowledgedAlerts = async (req, res, next) => {
///// Emit event to server
try {
const acknowledgedAlerts = await device.postAcknowledgedAlerts(req.params.msn, req.body.acknowledgedAlerts);
res.send(acknowledgedAlerts);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const putAcknowledgedAlerts = async (req, res, next) => {
try {
var acknowledgedAlerts = await device.postAcknowledgedAlerts(req.params.msn, req.body.acknowledgedAlerts);
res.send(acknowledgedAlerts);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const deleteAcknowledgedAlerts = async (req, res, next) => {
///// Emit event to server
try {
const acknowledgedAlerts = await device.postAcknowledgedAlerts(req.params.msn, null);
res.send(acknowledged);
} catch (error) {
res.status(500).send({message: error.message || "unknown_error"});
}
}
const ping = async (req, res, next) => {
///// Emit event to server
res.sendStatus(200);
}
module.exports = {
getPrograms,
postPrograms,
putPrograms,
deletePrograms,
getConfiguration,
postConfiguration,
putConfiguration,
deleteConfiguration,
getSlots,
postSlots,
putSlots,
deleteSlots,
getManualCommand,
postManualCommand,
putManualCommand,
deleteManualCommand,
getStatusCommand,
postStatusCommand,
putStatusCommand,
deleteStatusCommand,
getAcknowledgedAlerts,
postAcknowledgedAlerts,
putAcknowledgedAlerts,
deleteAcknowledgedAlerts,
ping,
}

View File

@@ -3,10 +3,15 @@ const services = require('../services')
const { firmware } = services
const postLookFirmware = async (req, res, next) => {
const { serialNumber, hash, version, type, hardwareIndex, hardwareVersion } = req.body
const { serialNumber, firmwareHash, firmwareVersion, moduleType, hardwareIndex, hardwareVersion } = req.body
try {
const obj = await firmware.lookFirmware(serialNumber, hash, version, type, hardwareIndex, hardwareVersion)
res.send(obj)
const obj = await firmware.lookFirmware(serialNumber, firmwareHash, firmwareVersion, moduleType, hardwareIndex, hardwareVersion)
if (!obj) { res.sendStatus(200); }
else { res.send({
firmwareHash: obj.firmwareHash,
firmwareSize: obj.firmwareSize,
})}
} catch (e) {
console.log(e.message)
res.sendStatus(500)
@@ -14,10 +19,12 @@ const postLookFirmware = async (req, res, next) => {
}
const postSyncFirmware = async (req, res, next) => {
const { serialNumber, hash, version, type, hardwareIndex, hardwareVersion } = req.body
const { serialNumber, firmwareHash, moduleType, position, length } = req.body
try {
const obj = await firmware.syncFirmware(serialNumber, hash, version, type, hardwareIndex, hardwareVersion)
res.send(obj)
const buffer = await firmware.syncFirmware(serialNumber, firmwareHash, moduleType, position, length)
if (!buffer) { res.sendStatus(400); }
else { res.send(buffer) }
} catch (e) {
console.log(e.message)
res.sendStatus(500)

View File

@@ -1,67 +1,240 @@
const services = require('../services')
const util = require('../util')
const { device } = services
const getModuleMsn = (req) => {
return req.query.msn || req.query.id || req.body.module
}
const getRelayMsn = (req) => {
return req.body.relayMsn
}
const postGetRequestToDo = async (req, res, next) => {
///// Emit event to server
try {
await device.postRequestToDo(req.body.relayMsn, req.body);
await device.getRequestToDo(req.body.relayMsn);
var response = { todo: [{ serialNumber: req.body.relayMsn, configuration: 1 }] };
await device.postRequestToDo(getRelayMsn(req), req.body);
const todo = await device.getRequestToDo(getRelayMsn(req));
var response = { todo };
console.log(req.body);
res.send(response);
} catch (error) {
res.send(500);
res.sendStatus(500);
}
}
const getModuleConfiguration = async (req, res, next) => {
///// Emit event to server
var response = {
"name": "LRBST-R-TARACE",
"inventory": [
"7400040670330001"
],
"wakeUpTimes": [
60,
480,
540,
600,
660,
720,
780,
840,
900,
960,
1020,
1080
]
};
try {
///// Emit event to server
var response = await device.getConfiguration(getModuleMsn(req))
res.send(response);
res.send(response.configuration);
} catch (error) {
res.sendStatus(500);
}
}
const setModuleConfiguration = async (req, res, next) => {
try {
///// Emit event to server
await device.postConfiguration(getModuleMsn(req), req.body, util.dateToTimestamp(req.body.flashTimeStamp))
}
const getModulePrograms = async (req, res, next) => {
}
const setModulePrograms = async (req, res, next) => {
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
}
}
const reportModuleDataSent = async (req, res, next) => {
res.send(200);
try {
///// Emit event to server
await device.postConfiguration(getModuleMsn(req), null, util.dateToTimestamp(req.body.sentAt))
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
}
}
const getModulePrograms = async (req, res, next) => {
try {
///// Emit event to server
var response = await device.getPrograms(getModuleMsn(req))
res.send(response.programs);
} catch (error) {
res.sendStatus(500);
}
}
const setModulePrograms = async (req, res, next) => {
try {
///// Emit event to server
await device.postPrograms(getModuleMsn(req), req.body, util.dateToTimestamp(req.body.flashTimeStamp))
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
}
}
const reportProgramsDataSent = async (req, res, next) => {
try {
///// Emit event to server
await device.postPrograms(getModuleMsn(req), null, util.dateToTimestamp(req.body.programmingTimestamp))
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
}
}
const reportAllModuleProgramsDataSent = async (req, res, next) => {
try {
///// Emit event to server
await device.postPrograms(getModuleMsn(req), null, util.dateToTimestamp(req.body.sentAt))
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
}
}
const getModuleSlots = async (req, res, next) => {
try {
///// Emit event to server
var response = await device.getSlots(getModuleMsn(req))
res.send(response.slots);
} catch (error) {
res.sendStatus(500);
}
}
const setModuleSlots = async (req, res, next) => {
try {
///// Emit event to server
await device.postSlots(getModuleMsn(req), req.body, util.dateToTimestamp(req.body.flashTimeStamp))
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
}
}
const reportSlotsDataSent = async (req, res, next) => {
try {
///// Emit event to server
await device.postSlots(getModuleMsn(req), null, util.dateToTimestamp(req.body.programmingTimestamp))
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
}
}
const reportAllModuleSlotsDataSent = async (req, res, next) => {
try {
///// Emit event to server
await device.postSlots(getModuleMsn(req), null, util.dateToTimestamp(req.body.sentAt))
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
}
}
const getManualCommand = async (req, res, next) => {
try {
///// Emit event to server
var response = await device.getManualCommand(getModuleMsn(req))
res.send(response.manualCommand);
} catch (error) {
res.sendStatus(500);
}
}
const reportManualCommandSent = async (req, res, next) => {
try {
///// Emit event to server
await device.postManualCommand(getModuleMsn(req), null)
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
}
}
const getStatusCommand = async (req, res, next) => {
try {
///// Emit event to server
var response = await device.getStatusCommand(getModuleMsn(req))
res.send(response.statusCommand);
} catch (error) {
res.sendStatus(500);
}
}
const reportStatusCommandSent = async (req, res, next) => {
try {
///// Emit event to server
await device.postStatusCommand(getModuleMsn(req), null)
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
}
}
const getAcknowledgeAlerts = async (req, res, next) => {
try {
///// Emit event to server
var response = await device.getAcknowledgedAlerts(getModuleMsn(req))
res.send(response.acknowledgedAlerts);
} catch (error) {
res.sendStatus(500);
}
}
const reportAcknowledgeAlerts = async (req, res, next) => {
try {
///// Emit event to server
await device.postAcknowledgedAlerts(getModuleMsn(req), null)
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
}
}
module.exports = {
postGetRequestToDo,
getModuleConfiguration,
setModuleConfiguration,
reportModuleDataSent,
getModulePrograms,
setModulePrograms,
reportModuleDataSent,
reportProgramsDataSent,
reportAllModuleProgramsDataSent,
getModuleSlots,
setModuleSlots,
reportSlotsDataSent,
reportAllModuleSlotsDataSent,
getManualCommand,
reportManualCommandSent,
getStatusCommand,
reportStatusCommandSent,
getAcknowledgeAlerts,
reportAcknowledgeAlerts,
}

View File

@@ -1,17 +1,21 @@
const status = require('./status.controller')
const data = require('./data.controller')
const senbus_value = require('./senbus_value.controller')
const firmware = require('./firmware.controller')
const ipx = require('./ipx.controller')
const journal = require('./journal.controller')
const longpolling = require('./longpolling.controller')
const grtd = require('./grtd.controller')
const api = require('./api.controller')
module.exports = {
status,
data,
senbus_value,
firmware,
ipx,
journal,
longpolling,
grtd,
api,
}

View File

@@ -84,10 +84,6 @@ const getModuleRequest = async (req, res, next) => {
if (error) { res.send(error); }
else { res.send(body); }
});
req.on("close", function () {
console.log("Request cancelled by client");
});
}
const postModuleRequest = async (req, res, next) => {
@@ -96,10 +92,6 @@ const postModuleRequest = async (req, res, next) => {
if (error) { res.send(error); }
else { res.send(body); }
});
req.on("close", function () {
console.log("Request cancelled by client");
});
}
module.exports = {

View File

@@ -0,0 +1,16 @@
const services = require('../services')
const { senbus_value } = services
const postSenbusValue = async (req, res, next) => {
try {
res.sendStatus(200)
} catch (e) {
console.log(e.message)
res.sendStatus(500)
}
}
module.exports = {
postSenbusValue,
}

View File

@@ -1,6 +1,6 @@
const services = require('../services')
const { status } = services
const { status, device } = services
const postSetStatus = async (req, res, next) => {
try {
@@ -9,11 +9,13 @@ const postSetStatus = async (req, res, next) => {
if (req.body.status) {
const values = { inputsAlerts: req.body.status.inputsAlerts || [], msn: req.body.msn, id: req.params.id }
code = await status.createAlerts(values)
code = await device.updateStatus(req.body.msn, req.body, req.body.dialogTimestamp)
} else if (req.body.radioProducts) {
for (const product of req.body.radioProducts) {
const values = { inputsAlerts: product.inputsAlerts || [], msn: product.msn, id: req.params.id }
code = await status.createAlerts(values)
code = await device.updateStatus(product.msn, product, product.dialogTimestamp)
}
}
res.send(code)

View File

@@ -1,17 +1,16 @@
const MongoClient = require('mongodb').MongoClient;
const models = require('../models')
const mongodb_hostname = process.env.MONGODB_HOST || 'localhost';
const mongodb_hostname = process.env.MONGODB_HOST || '0.0.0.0';
const mongodb_port = process.env.MONGODB_PORT || 27017;
const mongodb_database = process.env.MONGODB_DATABASE || 'lsp';
const mongodb_url = 'mongodb://' + mongodb_hostname + ':' + mongodb_port;
const client = new MongoClient(mongodb_url, { useNewUrlParser: true, useUnifiedTopology: true });
const client = new MongoClient(mongodb_url, { useUnifiedTopology: true });
const bucketMaxSize = 4096;
var _db;
var _devices = MongoClient();
var _data;
var _ipx_data;
var _events;
@@ -22,8 +21,10 @@ var days = function(date) {
}
var init = async function () {
client.connect(function (err) {
await client.connect(function (err) {
if (err) {
console.log('MongoDB Client error');
console.log(err);
return { error: "Error connecting to DB: " + err }
} else {
@@ -34,13 +35,14 @@ var init = async function () {
_events = _db.collection('events');
_alerts = _db.collection('alerts');
console.log('MongoDB Client connected');
////////////////////////////
// FLUSH DB BY UNCOMMENTING
// _devices.remove(function(err, objects){});
// _data.remove(function(err, objects){});
// _ipx_data.remove(function(err, objects){});
// _events.remove(function(err, objects){});
// _alerts.remove(function(err, objects){});
// _devices.deleteMany(function(err, objects){});
// _data.deleteMany(function(err, objects){});
// _ipx_data.deleteMany(function(err, objects){});
// _events.deleteMany(function(err, objects){});
// _alerts.deleteMany(function(err, objects){});
return null;
}
@@ -165,9 +167,104 @@ var addIPXData = async function (relay, device, child, element) {
}
}
var addDevice = async function (element) {
try {
const model = await models.device.validateAsync(element);
await _devices.updateOne(
{
msn: model.msn
},
{
$set: model
},
{
upsert: true
})
.then(err => {
return err;
})
} catch (err) {
return err;
}
}
var updateDevice = async function (model) {
try {
await _devices.updateOne(
{
msn: model.msn
},
{
$set: model
},
{
upsert: true
})
.then(err => {
return err;
})
} catch (err) {
return err;
}
}
var getDevice = async function (msn) {
try {
if (!msn) { throw ("msn_not_provided")}
return await _devices.findOne(
{
$or : [{relayMsn: msn}, {msn: msn}]
})
.then(element => {
return element;
})
} catch (err) {
throw err
}
}
var getDeviceChildren = async function (msn) {
try {
if (!msn) { throw ("msn_not_provided")}
return await _devices.findOne(
{
relayMsn: msn
})
.then(element => {
return element.inventory;
})
} catch (err) {
throw err
}
}
var getDeviceParents = async function (msn) {
try {
if (!msn) { throw ("msn_not_provided")}
return await _devices.find(
{
inventory: { $in: {msn: msn} }
})
.then(elements => {
return elements;
})
} catch (err) {
throw err
}
}
exports.init = init
exports.addData = addData
exports.addEvent = addEvent
exports.addAlert = addAlert
exports.addIPXData = addIPXData
exports.addIPXData = addIPXData
exports.addDevice = addDevice
exports.updateDevice = updateDevice
exports.getDevice = getDevice
exports.getDeviceChildren = getDeviceChildren
exports.getDeviceParents = getDeviceParents

44
models/device.model.js Normal file
View File

@@ -0,0 +1,44 @@
const joi = require("joi")
const DeviceModel = joi.object({
relayMsn: joi.string().optional(),
msn: joi.string().optional(),
relayName: joi.string().optional(),
relayBattery: joi.number().optional(),
relayBatteryStatus: joi.number().optional(),
relayCSQ: joi.number().optional(),
relayNetwork: joi.number().optional(),
connectionType: joi.string().optional(),
phoneNumber: joi.string().optional(),
iccid: joi.string().optional(),
relayTemperature: joi.number().optional(),
relayConfigurationTimestamp: joi.number().optional(),
vsoft: joi.string().optional(),
inventory: joi.array().items( joi.object({
msn: joi.string().required(),
configurationTimestamp: joi.number().optional(),
programmingTimestamp: joi.number().optional(),
}).optional()
).optional(),
configurationTimestamp: joi.number().optional(),
programmationTimestamp: joi.number().optional(),
todo: joi.array().items(joi.object({
msn: joi.string().required(),
}).unknown()).optional(),
status: joi.object().unknown(),
programs: joi.object().unknown(),
configuration: joi.object().unknown(),
slots: joi.object().unknown(),
manualCommand: joi.object().unknown(),
statusCommand: joi.object().unknown(),
acknowledgedAlerts: joi.object().unknown(),
})
module.exports = DeviceModel

View File

@@ -2,10 +2,12 @@ const data = require('./data.model.js');
const event = require('./event.model.js');
const alert = require('./alert.model.js');
const ipxdata = require('./ipxdata.model.js');
const device = require('./device.model.js');
module.exports = {
data,
event,
alert,
ipxdata
ipxdata,
device
}

1222
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -15,12 +15,16 @@
"body-parser": "^1.19.0",
"cbor": "^5.1.0",
"cbor-body-parser": "^1.0.3",
"chokidar": "^3.6.0",
"crc": "^4.3.2",
"events": "^3.2.0",
"express": "^4.17.1",
"express-session": "^1.17.2",
"joi": "^17.4.0",
"moment": "^2.29.1",
"mongodb": "^3.6.2",
"random-bytes": "^1.0.0"
"random-bytes": "^1.0.0",
"underscore": "^1.13.6",
"oauth2-server": "^3.1.1"
}
}

Binary file not shown.

View File

@@ -16,20 +16,64 @@ router.get('/api/module/:id/:route/:module?', controller.longpolling.getModuleRe
router.post('/api/module/:id/:route/:module?', controller.longpolling.postModuleRequest);
router.post('/v2/setData/:id', controller.data.postSetData);
router.post('/v2/setSenbusValue/:id', controller.senbus_value.postSenbusValue);
router.post('/v2/setJournal/:id', controller.journal.postSetJournal);
router.post('/v2/ipx-data/:id', controller.ipx.postIpxData);
router.post('/v2/setStatus/:id', controller.status.postSetStatus);
router.post("/v2/get/requests/to/do", controller.grtd.postGetRequestToDo);
router.post("/v2/reportModuleDataSent", controller.grtd.reportModuleDataSent);
router.get("/v2/getAcknowledgeAlerts/:id", controller.grtd.getAcknowledgeAlerts);
router.get("/v2/getManualCommand", controller.grtd.getManualCommand);
router.get("/v2/getModuleConfiguration", controller.grtd.getModuleConfiguration);
router.post("/v2/setModuleConfiguration", controller.grtd.setModuleConfiguration);
router.get("/v2/getModulePrograms", controller.grtd.getModulePrograms);
router.get("/v2/getModuleSlots", controller.grtd.getModuleSlots);
router.get("/v2/getStatusCommand", controller.grtd.getStatusCommand);
router.post("/v2/get/requests/to/do", controller.grtd.postGetRequestToDo);
router.post("/v2/reportAcknowledgeAlerts", controller.grtd.reportAcknowledgeAlerts);
router.post("/v2/reportAllModuleProgramsDataSent", controller.grtd.reportAllModuleProgramsDataSent);
router.post("/v2/reportAllModuleSlotsDataSent", controller.grtd.reportAllModuleSlotsDataSent);
router.post("/v2/reportManualCommandSent", controller.grtd.reportManualCommandSent);
router.post("/v2/reportModuleDataSent", controller.grtd.reportModuleDataSent);
router.post("/v2/reportSlotsDataSent", controller.grtd.reportSlotsDataSent);
router.post("/v2/reportStatusCommandSent", controller.grtd.reportStatusCommandSent);
router.post("/v2/setModuleConfiguration", controller.grtd.setModuleConfiguration);
router.post("/v2/setModulePrograms", controller.grtd.setModulePrograms);
router.post("/v2/setModuleSlots", controller.grtd.setModuleSlots);
router.all('/api/*', (req, res) => { res.send(503); });
router.get("/api/lsp/programs/:msn", controller.api.getPrograms);
router.post("/api/lsp/programs/:msn", controller.api.postPrograms);
router.put("/api/lsp/programs/:msn", controller.api.putPrograms);
router.delete("/api/lsp/programs/:msn", controller.api.deletePrograms);
router.all('*', (req, res) => { res.send(404); });
router.get("/api/lsp/configuration/:msn", controller.api.getConfiguration);
router.post("/api/lsp/configuration/:msn", controller.api.postConfiguration);
router.put("/api/lsp/configuration/:msn", controller.api.putConfiguration);
router.delete("/api/lsp/configuration/:msn", controller.api.deleteConfiguration);
router.get("/api/lsp/slots/:msn", controller.api.getSlots);
router.post("/api/lsp/slots/:msn", controller.api.postSlots);
router.put("/api/lsp/slots/:msn", controller.api.putSlots);
router.delete("/api/lsp/slots/:msn", controller.api.deleteSlots);
router.get("/api/lsp/manual-command/:msn", controller.api.getManualCommand);
router.post("/api/lsp/manual-command/:msn", controller.api.postManualCommand);
router.put("/api/lsp/manual-command/:msn", controller.api.putManualCommand);
router.delete("/api/lsp/manual-command/:msn", controller.api.deleteManualCommand);
router.get("/api/lsp/status-command/:msn", controller.api.getStatusCommand);
router.post("/api/lsp/status-command/:msn", controller.api.postStatusCommand);
router.put("/api/lsp/status-command/:msn", controller.api.putStatusCommand);
router.delete("/api/lsp/status-command/:msn", controller.api.deleteStatusCommand);
router.get("/api/lsp/acknowledged-alerts/:msn", controller.api.getAcknowledgedAlerts);
router.post("/api/lsp/acknowledged-alerts/:msn", controller.api.postAcknowledgedAlerts);
router.put("/api/lsp/acknowledged-alerts/:msn", controller.api.putAcknowledgedAlerts);
router.delete("/api/lsp/acknowledged-alerts/:msn", controller.api.deleteAcknowledgedAlerts);
router.get("/api/ping", controller.api.ping);
router.all('/api/*', (req, res) => { res.sendStatus(503); });
router.all('*', (req, res) => { res.sendStatus(404); });
module.exports = router;

View File

@@ -1,7 +1,14 @@
const dbcontroller = require('../db');
const util = require('../util');
const postRequestToDo = async function (data, msn) {
const postRequestToDo = async function (msn, body) {
try {
await dbcontroller.addDevice(body, null)
body.inventory.forEach(async device => {
await dbcontroller.addDevice(device, body.relayMsn)
});
return { success: true }
} catch (e) {
throw new Error(e.message)
@@ -10,13 +17,315 @@ const postRequestToDo = async function (data, msn) {
const getRequestToDo = async function (msn) {
try {
return { success: true }
var todos = []
const children = await dbcontroller.getDeviceChildren(msn)
for (const child of children) {
///// Retrieve child
const device = await dbcontroller.getDevice(child.msn)
var todo = { msn : child.msn }
///// Programs
if (device.programs != undefined) {
if (child.programmingTimestamp < device.programs.timestamp) { todo.programs = 1 }
else if (child.programmingTimestamp > device.programs.timestamp) { todo.programs = 2 }
}
///// Configuration
if (device.configuration != undefined) {
if (child.configurationTimestamp < device.configuration.timestamp) { todo.configuration = 1 }
else if (child.configurationTimestamp > device.configuration.timestamp) { todo.configuration = 2 }
}
///// Slots
if (device.slots != undefined) {
if (child.programmingTimestamp < device.slots.timestamp) { todo.slots = 1 }
else if (child.programmingTimestamp > device.slots.timestamp) { todo.slots = 2 }
}
///// Status
if (device.statusCommand != undefined) { todo.status = 1 }
///// Manual
if (device.manualCommand != undefined) { todo.manual = 1 }
///// Acknowledged
if (device.acknowledgedAlerts != undefined) { todo.acknowledged = 1 }
///// Firmware
if (device.firmware != undefined) { device.firmware = 1 }
///// Add objet to todos only if something to do
if (Object.keys(todo).length > 1) { todos.push(todo) }
}
return todos
} catch (e) {
throw new Error(e.message)
}
}
const getStatus = async function (msn) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
return device.status || {}
} catch (e) {
throw new Error(e.message)
}
}
const updateStatus = async function (msn, status, timestamp) {
try {
///// Retrieve device
var device = await dbcontroller.getDevice(msn)
if (!device) { await dbcontroller.addDevice({"msn": msn}); }
device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
///// Set variables
if (status) {
device.status = { timestamp: timestamp || util.unixTimestamp(), status: status }
} else {
device.status = undefined
}
///// Update device
await dbcontroller.updateDevice(device);
return 200;
} catch (e) {
throw new Error(e.message)
}
}
const getPrograms = async function (msn) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
return device.programs || {}
} catch (e) {
throw new Error(e.message)
}
}
const postPrograms = async function (msn, programs, timestamp) {
try {
///// Retrieve device
var device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
///// Set variables
if (programs) {
device.programs = { timestamp: timestamp || util.unixTimestamp(), programs: programs }
} else {
device.programmingTimestamp = device.programs.timestamp;
// device.programs = undefined
}
///// Update device
await dbcontroller.updateDevice(device)
return device.programs
} catch (e) {
throw new Error(e.message)
}
}
const getConfiguration = async function (msn) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
return device.configuration || {}
} catch (e) {
throw new Error(e.message)
}
}
const postConfiguration = async function (msn, configuration, timestamp) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
///// Set variables
if (configuration) {
device.configuration = { timestamp: timestamp || util.unixTimestamp(), configuration: configuration }
} else {
device.configurationTimestamp = device.configuration.timestamp;
// device.configuration = undefined
}
///// Update device
await dbcontroller.updateDevice(device)
return device.configuration
} catch (e) {
throw new Error(e.message)
}
}
const getSlots = async function (msn) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
return device.slots || {}
} catch (e) {
throw new Error(e.message)
}
}
const postSlots = async function (msn, slots, timestamp) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
///// Set variables
if (slots) {
device.slots = { timestamp: timestamp || util.unixTimestamp(), slots: slots }
} else {
device.programmingTimestamp = device.slots.timestamp;
// device.slots = undefined
}
///// Update device
await dbcontroller.updateDevice(device, msn)
return device.slots
} catch (e) {
throw new Error(e.message)
}
}
const getManualCommand = async function (msn) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
return device.manualCommand || {}
} catch (e) {
throw new Error(e.message)
}
}
const postManualCommand = async function (msn, manualCommand) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
///// Set variable
if (manualCommand) {
device.manualCommand = { timestamp: util.unixTimestamp(), manualCommand: manualCommand }
} else {
device.manualCommand = undefined
}
///// Update device
await dbcontroller.updateDevice(device, msn)
return device.manualCommand
} catch (e) {
throw new Error(e.message)
}
}
const getStatusCommand = async function (msn) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
return device.statusCommand || {}
} catch (e) {
throw new Error(e.message)
}
}
const postStatusCommand = async function (msn, statusCommand) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
///// Set variable
if (statusCommand) {
device.statusCommand = { timestamp: util.unixTimestamp(), statusCommand: statusCommand }
} else {
device.statusCommand = undefined
}
///// Update device
await dbcontroller.updateDevice(device, msn)
return device.statusCommand
} catch (e) {
throw new Error(e.message)
}
}
const getAcknowledgedAlerts = async function (msn) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
return device.acknowledgedAlerts || {}
} catch (e) {
throw new Error(e.message)
}
}
const postAcknowledgedAlerts = async function (msn, acknowledgedAlerts) {
try {
///// Retrieve device
const device = await dbcontroller.getDevice(msn)
if (!device) { throw({message: "module_not_found_for_this_identifier"}) }
///// Set variable
if (acknowledgedAlerts) {
device.acknowledgedAlerts = { timestamp: util.unixTimestamp(), acknowledgedAlerts: acknowledgedAlerts }
} else {
device.acknowledgedAlerts = undefined
}
///// Update device
await dbcontroller.updateDevice(device, msn)
return device.acknowledgedAlerts
} catch (e) {
throw new Error(e.message)
}
}
module.exports = {
getStatus,
updateStatus,
postRequestToDo,
getRequestToDo,
getPrograms,
postPrograms,
getConfiguration,
postConfiguration,
getSlots,
postSlots,
getManualCommand,
postManualCommand,
getStatusCommand,
postStatusCommand,
getAcknowledgedAlerts,
postAcknowledgedAlerts,
}

View File

@@ -1,20 +1,191 @@
const lookFirmware = (serialNumber, hash, version, type, hardwareIndex, hardwareVersion) => {
var fs = require('fs').promises;
var path = require('path');
var crc = require('crc');
var chokidar = require('chokidar');
var firmwares = []
const parseVersion = (version) => {
try {
return {}
const array = version.split('.')
if (!array || array.length != 3) { throw ({ message: 'invalid_version' }) }
return {
major: array[0],
minor: array[1],
build: array[2],
}
} catch (e) { return null; }
}
const compareVersions = (v1, v2) => {
var normalized1 = (v1.major << 16) | (v1.minor << 8) | (v1.build);
var normalized2 = (v2.major << 16) | (v2.minor << 8) | (v2.build);
return (normalized1 > normalized2) ? -1 : (normalized1 < normalized2) ? 1 : 0;
}
const validateHardwareVersion = (list, version) => {
for (element of list) {
if (element.minor == version.minor && element.build == version.build) { return true }
}
return false
}
const getBinFiles = async (dir) => {
const dirents = await fs.opendir(dir)
var files = []
for await (const dirent of dirents) {
const filePath = path.join(dir, dirent.name)
if (dirent.isDirectory()) {
files = files.concat(await getBinFiles(filePath))
} else if (path.extname(dirent.name) === '.bin') {
files.push(filePath)
}
}
return files
}
const validateFirmware = async (filePath) => {
const fileBuffer = await fs.readFile(filePath);
const stats = await fs.stat(filePath);
const startPattern = Buffer.from('5C2A5C', 'hex');
const endPattern = Buffer.from('5C2B5C', 'hex');
var firmware = {}
var offset = 0;
///// Check file is bin file
if (path.extname(filePath) != '.bin') { throw ({ message: 'not_a_bin_file' }) }
///// Check firmware size
if (stats.size < 18) { throw ({ message: 'invalid_firmware' }) }
///// Find patterns first
var startMatch = fileBuffer.indexOf(startPattern, 0)
var endMatch = fileBuffer.indexOf(endPattern, 0)
if (startMatch < 0 || endMatch < 0) { throw ({ message: 'invalid_firmware' }) }
///// Version
offset = 0x0000;
firmware.version = {
major: fileBuffer.readUInt8(offset++),
minor: fileBuffer.readUInt8(offset++),
build: fileBuffer.readUInt8(offset++)
}
///// Hardware Type
offset = 0x0003;
firmware.hardware_type = fileBuffer.readUInt8(offset++)
///// Module Type
offset = 0x0008;
firmware.moduleType = fileBuffer.toString('ascii', offset, Math.min(fileBuffer.indexOf(0x00, offset), offset + 10)).trim();
///// Hardware compatibility
offset = startMatch + 3
let compatibility = []
while (offset < endMatch) {
compatibility.push({
major: fileBuffer.readUInt8(offset++),
minor: fileBuffer.readUInt8(offset++),
build: fileBuffer.readUInt8(offset++)
})
}
firmware.compatibility = compatibility
///// Hash
firmware.firmwareHash = crc.crc32(fileBuffer).toString(16)
///// Size
firmware.firmwareSize = stats.size
///// Path
firmware.path = filePath;
return firmware
}
const init = async (path) => {
try {
this.path = path;
var watcher = chokidar.watch(this.path + '/**/*.bin', { ignored: /^\./, persistent: true });
watcher
.on('add', async function (path) {
///// Try validating firmware
try {
firmwares.push(await validateFirmware(path))
} catch (e) { }
})
.on('unlink', async function (path) {
///// Remove firmware from list
firmwares = firmwares.filter((element) => { return element.path != path })
})
.on('change', async function (path) {
///// Remove firmware from list
firmwares = firmwares.filter((element) => { return element.path != path })
///// Try validating firmware
try {
firmwares.push(await validateFirmware(path))
} catch (e) { }
})
.on('error', async function (error) { console.error('Error happened', error); })
return null
} catch (exception) {
return exception.message
}
}
const lookFirmware = (serialNumber, firmwareHash, version, moduleType, hardwareIndex, hardwareVersion) => {
try {
///// Retrieve best firmware
const firmware = firmwares.filter((element) => {
const parsedHardwareVersion = parseVersion(hardwareVersion);
if (!hardwareVersion) { return false; }
if (!validateHardwareVersion(element.compatibility, parsedHardwareVersion)) { return false; }
if (moduleType && element.moduleType != moduleType) { return false; }
if (firmwareHash && (firmwareHash != 'init' && element.firmwareHash == firmwareHash)) { return false; }
return true;
}).sort((f1, f2) => {
return compareVersions(f1.version, f2.version);
})[0]
return firmware
} catch (e) {
throw new Error(e.message)
}
}
const syncFirmware = (serialNumber, hash, version, type, hardwareIndex, hardwareVersion) => {
const syncFirmware = async (serialNumber, firmwareHash, moduleType, position, length) => {
try {
return {}
///// Retrieve firmware
const firmware = firmwares.find((element) => { return element.firmwareHash == firmwareHash; })
///// Check module type
if (moduleType && firmware.moduleType != moduleType) { return false; }
///// Read file
const fileBuffer = await fs.readFile(firmware.path);
return fileBuffer.subarray(parseInt(position), parseInt(position) + parseInt(length));
} catch (e) {
throw new Error(e.message)
throw new Error(e.message);
}
}
module.exports = {
init,
lookFirmware,
syncFirmware,
}

View File

@@ -1,5 +1,6 @@
const status = require('./status.service')
const data = require('./data.service')
const senbus_value = require('./senbus_value.service')
const firmware = require('./firmware.service')
const ipx = require('./ipx.service')
const journal = require('./journal.service')
@@ -9,6 +10,7 @@ const device = require('./device.service')
module.exports = {
status,
data,
senbus_value,
firmware,
ipx,
journal,

View File

@@ -0,0 +1,9 @@
const dbcontroller = require('../db');
const createSenbusValue = async function (data) {
return { success: true }
}
module.exports = {
createSenbusValue,
}

3
util/index.js Normal file
View File

@@ -0,0 +1,3 @@
const util = require('./util.js')
module.exports = util

34
util/util.js Normal file
View File

@@ -0,0 +1,34 @@
const dateToTimestamp = function (date) {
var iteration = 0
while (1) {
try {
switch (iteration++) {
///// ISO String
case 0: return Math.floor(Date.parse(date) / 1000);
///// Timestamp string
case 2:
if (typeof(date) != 'string') continue;
date = parseInt(date); break;
///// Timestamp integer
case 1:
if (typeof(date) != 'integer') continue;
// if (date > 0xFFFFFFFF) return Math.floor(date / 1000)
else return date;
default: return undefined
}
} catch (e) { continue }
}
}
const unixTimestamp = function () { return Math.floor(Date.now() / 1000) }
module.exports = {
dateToTimestamp,
unixTimestamp,
}