feat: implement WebSocket server for real-time sensor data handling and add sensor status update routes
This commit is contained in:
65
realtime/src/store/influx.js
Normal file
65
realtime/src/store/influx.js
Normal file
@@ -0,0 +1,65 @@
|
||||
const { InfluxDB, Point } = require('@influxdata/influxdb-client');
|
||||
|
||||
const client = new InfluxDB({
|
||||
url: process.env.INFLX_URL,
|
||||
token: process.env.INFLX_TOKEN,
|
||||
});
|
||||
|
||||
const bucket = process.env.INFLX_BUCKET || 'sensors';
|
||||
const org = process.env.INFLX_ORG;
|
||||
|
||||
const writeApi = client.getWriteApi(org, bucket, 'ms', {
|
||||
flushInterval: 100,
|
||||
batchSize: 50,
|
||||
});
|
||||
|
||||
const fieldMap = {
|
||||
t: 'temperature',
|
||||
h: 'humidity',
|
||||
spd: 'speed',
|
||||
cog: 'cog',
|
||||
sog: 'sog',
|
||||
hdg: 'headingTrue',
|
||||
lat: 'latitude',
|
||||
lon: 'longitude',
|
||||
};
|
||||
|
||||
function writeSensorData(fields, sensor, session, timestamp) {
|
||||
const point = new Point('sensor_data')
|
||||
.tag('sensor', sensor)
|
||||
.tag('session', session)
|
||||
.timestamp(timestamp);
|
||||
|
||||
for (const [short, long] of Object.entries(fieldMap)) {
|
||||
if (fields[short] !== undefined) {
|
||||
point.floatField(long, fields[short]);
|
||||
}
|
||||
}
|
||||
|
||||
writeApi.writePoint(point);
|
||||
}
|
||||
|
||||
async function queryHistory(sensor, session, since) {
|
||||
const queryApi = client.getQueryApi(org);
|
||||
const query = `
|
||||
from(bucket: "${bucket}")
|
||||
|> range(start: ${since})
|
||||
|> filter(fn: (r) => r._measurement == "sensor_data")
|
||||
|> filter(fn: (r) => r.sensor == "${sensor}")
|
||||
|> filter(fn: (r) => r.session == "${session}")
|
||||
|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")
|
||||
`;
|
||||
|
||||
const rows = [];
|
||||
return new Promise((resolve, reject) => {
|
||||
queryApi.queryRows(query, {
|
||||
next(row, tableMeta) {
|
||||
rows.push(tableMeta.toObject(row));
|
||||
},
|
||||
error: reject,
|
||||
complete() { resolve(rows); },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { writeSensorData, queryHistory };
|
||||
@@ -1,6 +1,6 @@
|
||||
const redis = require('ioredis');
|
||||
|
||||
const connectionsToken = "snsr_pending_token";
|
||||
const connectionsToken = "sensors_pending";
|
||||
const connectedSensorsKey = "sensors";
|
||||
|
||||
|
||||
@@ -122,4 +122,12 @@ async function queryAll(from) {
|
||||
|
||||
configure();
|
||||
|
||||
module.exports = { checkRedis, appendAsConnection, createConnectionToken, consumeConnectionToken, query, queryAll };
|
||||
async function hset(key, ...args) {
|
||||
return client.hset(key, ...args);
|
||||
}
|
||||
|
||||
async function del(key) {
|
||||
return client.del(key);
|
||||
}
|
||||
|
||||
module.exports = { checkRedis, appendAsConnection, createConnectionToken, consumeConnectionToken, query, queryAll, hset, del };
|
||||
Reference in New Issue
Block a user