feat: implement sensor connection endpoint and add pending tokens route

This commit is contained in:
Giuseppe Raffa
2026-04-14 17:45:40 +02:00
parent a79ab2af38
commit b6b1ed7a2b
4 changed files with 152 additions and 13 deletions

View File

@@ -1,6 +1,10 @@
const redis = require('ioredis');
const redisClient = new redis({
const connectionsToken = "snsr_pending_token";
const connectedSensorsKey = "sensors";
const client = new redis({
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT),
password: process.env.REDIS_PASSWORD,
@@ -12,22 +16,22 @@ const redisClient = new redis({
}
});
redisClient.on('error', (error) => {
client.on('error', (error) => {
console.error('Redis error', error);
});
redisClient.on('connect', () => {
client.on('connect', () => {
console.log('Connected to Redis');
});
redisClient.on('reconnecting', () => {
client.on('reconnecting', () => {
console.log('Reconnecting to Redis');
});
async function configure() {
try {
await redisClient.connect();
await redisClient.ping();
await client.connect();
await client.ping();
console.log('Redis connection established');
} catch (err) {
console.error('Failed to connect to Redis', err);
@@ -35,21 +39,87 @@ async function configure() {
}
function connected() {
return redisClient.status === 'ready';
return client.status === 'ready';
}
async function checkRedis() {
try {
if (redisClient.status !== 'ready') {
await redisClient.connect().catch(() => {});
if (client.status !== 'ready') {
await client.connect().catch(() => {});
}
await redisClient.ping();
await client.ping();
return true;
} catch (err) {
return false;
}
}
/**
*
* @param {*} sensor
* @param {*} status
* @param {*} timestamp
*/
async function appendAsConnection(sensor, status, timestamp) {
try {
await client.hset(`sensor:${sensor}`, 'status', status, 'timestamp', timestamp);
} catch (err) {
console.error('Redis append error', err);
}
}
/**
* Recupera i valori di un campo specifico per una chiave data.
* @param {String} name - la chiave da cui leggere, es. "sensor:123"
* @param {String} from - il nome del campo da leggere, es. "status" o "timestamp"
* @returns {Object} un oggetto contenente i valori del campo richiesto
*/
async function query(name, from) {
const key = `${from}:${name}`;
return await client.hgetall(key);
}
/**
* Crea un token temporaneo per una nuova connessione WebSocket, scade dopo 5 secondi.
* @returns {string} il token
*/
async function createConnectionToken(sensor) {
const crypto = require('crypto');
const token = crypto.randomBytes(32).toString('hex');
const key = `${connectionsToken}:${token}`;
await client.set(key, sensor, 'EX', 5);
return token;
}
/**
* Verifica e consuma un token di connessione.
* @returns {string|null} il nome del sensore se valido, null altrimenti
*/
async function consumeConnectionToken(token) {
const key = `${connectionsToken}:${token}`;
const sensor = await client.get(key);
if (sensor) {
await client.del(key);
}
return sensor;
}
/**
* Restituisce tutte le chiavi che corrispondono a un prefisso.
* @param {String} from - il prefisso da cercare, es. "sensor", "ws_token"
* @returns {string[]} lista di chiavi trovate
*/
async function queryAll(from) {
const keys = [];
let cursor = '0';
do {
const [next, found] = await client.scan(cursor, 'MATCH', `${from}:*`, 'COUNT', 100);
cursor = next;
keys.push(...found);
} while (cursor !== '0');
return keys;
}
configure();
module.exports = { redisClient, connected, checkRedis };
module.exports = { checkRedis, appendAsConnection, createConnectionToken, consumeConnectionToken, query, queryAll };