89 lines
1.9 KiB
JavaScript
89 lines
1.9 KiB
JavaScript
const Redis = require('ioredis');
|
|
|
|
const redis = new Redis({
|
|
host: process.env.REDIS_HOST,
|
|
port: process.env.REDIS_PORT
|
|
});
|
|
|
|
// Client dedicato per subscribe (ioredis richiede client separato)
|
|
const redisSub = new Redis({
|
|
host: process.env.REDIS_HOST,
|
|
port: process.env.REDIS_PORT
|
|
});
|
|
|
|
redis.on('error', (error) => {
|
|
console.error('Redis error:', error);
|
|
});
|
|
|
|
redis.on('connect', () => {
|
|
console.log('Server connected to Redis DB');
|
|
});
|
|
|
|
redisSub.on('error', (error) => {
|
|
console.error('Redis sub error:', error);
|
|
});
|
|
|
|
const sensors_hash_map = 'sensors:sessions';
|
|
|
|
async function setSession(sensorID, metadata) {
|
|
await redis.hset(sensors_hash_map, sensorID, JSON.stringify(metadata));
|
|
}
|
|
|
|
async function getSession(sensorID) {
|
|
return await redis.hget(sensors_hash_map, sensorID);
|
|
}
|
|
|
|
async function deleteSession(sensorID) {
|
|
await redis.hdel(sensors_hash_map, sensorID);
|
|
}
|
|
|
|
async function getSessions() {
|
|
return await redis.hgetall(sensors_hash_map);
|
|
}
|
|
|
|
// --- Pub/Sub per live watchers ---
|
|
|
|
async function publishSensorData(sensorId, data) {
|
|
await redis.publish(`sensor:data:${sensorId}`, JSON.stringify(data));
|
|
}
|
|
|
|
async function addWatcher(sensorId) {
|
|
return await redis.incr(`sensor:watchers:${sensorId}`);
|
|
}
|
|
|
|
async function removeWatcher(sensorId) {
|
|
const count = await redis.decr(`sensor:watchers:${sensorId}`);
|
|
if (count <= 0) {
|
|
await redis.del(`sensor:watchers:${sensorId}`);
|
|
return 0;
|
|
}
|
|
return count;
|
|
}
|
|
|
|
async function getWatcherCount(sensorId) {
|
|
const count = await redis.get(`sensor:watchers:${sensorId}`);
|
|
return parseInt(count) || 0;
|
|
}
|
|
|
|
async function checkRedis() {
|
|
try {
|
|
await redis.ping();
|
|
return true;
|
|
} catch (error) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
setSession,
|
|
getSession,
|
|
deleteSession,
|
|
getSessions,
|
|
publishSensorData,
|
|
addWatcher,
|
|
removeWatcher,
|
|
getWatcherCount,
|
|
checkRedis,
|
|
redis,
|
|
redisSub
|
|
}; |