Skip to content

Instantly share code, notes, and snippets.

@mmontes11
Last active March 20, 2020 18:37
Show Gist options
  • Save mmontes11/2cd220dc0b7aa935ff8c871b6b36ba2e to your computer and use it in GitHub Desktop.
Save mmontes11/2cd220dc0b7aa935ff8c871b6b36ba2e to your computer and use it in GitHub Desktop.
Thing socket handler
import os from "os";
import { Log } from "../util/log";
import { SensorHandler } from "./sensorHandler";
import { LEDHandler } from "./ledHandler";
import config from "../config";
export class SocketHandler {
constructor(io) {
this.io = io;
this.numConnections = 0;
this.interval = config.socketInterval;
}
static _getData(measurementList) {
...
}
static _emit(socket, dataObject) {
...
socket.emit("data", dataToEmit);
Log.logInfo(`Emiting data: ${JSON.stringify(dataToEmit)}`);
}
static _clearInterval({ intervalId }) {
...
}
listen() {
this.io.on("connection", socket => {
Log.logInfo("Socket connection");
this.numConnections += 1;
Log.logInfo(`Number of connections: ${this.numConnections}`);
socket.intervalId = setInterval(async () => {
try {
const measurementList = await SensorHandler.read();
const data = SocketHandler._getData(measurementList);
LEDHandler.blinkAck();
SocketHandler._emit(socket, data);
} catch (err) {
Log.logError(err);
}
}, this.interval);
socket.on("disconnect", () => {
Log.logInfo("Socket disconnection");
this.numConnections -= 1;
Log.logInfo(`Number of connections: ${this.numConnections}`);
SocketHandler._clearInterval(socket);
if (this.numConnections === 0) {
this.close();
}
});
socket.on("error", error => {
Log.logError(error);
socket.emit("thing_error", error);
SocketHandler._clearInterval(socket);
});
});
}
close() {
Log.logInfo("Closing all socket connections...");
Object.keys(this.io.sockets.sockets).forEach(s => {
const socket = this.io.sockets.sockets[s];
SocketHandler._clearInterval(socket);
socket.disconnect(true);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment