onmessage when ws is rebuild

This commit is contained in:
Daniel Kluge 2022-05-12 18:42:46 +02:00
parent a6ade2806a
commit b493b1ec85

View File

@ -6,13 +6,16 @@ let ws;
const wsConnect = () => { const wsConnect = () => {
ws = new WebSocket(secrets.wsUrl); ws = new WebSocket(secrets.wsUrl);
ws.on("close", () => { ws.on("close", () => {
console.log(`${new Date().toString()}: Websocket closed unexpectedly`);
ws = undefined; ws = undefined;
setTimeout(wsConnect, 10000); // Retry after 10 seconds setTimeout(wsConnect, 10000); // Retry after 10 seconds
}); });
ws.on("error", () => { ws.on("error", () => {
console.log(`${new Date().toString()}: Error on websocket`);
ws = undefined; ws = undefined;
setTimeout(wsConnect, 10000); // Retry after 10 seconds setTimeout(wsConnect, 10000); // Retry after 10 seconds
}); });
ws.on("message", wsOnMsg);
} }
do { do {
wsConnect(); wsConnect();
@ -39,7 +42,7 @@ function metaFromMetadata(metadata) {
return meta; return meta;
} }
ws.on("message", (data) => { function wsOnMsg(data) {
if (!client.connected) return; if (!client.connected) return;
const parsed = JSON.parse(data); const parsed = JSON.parse(data);
@ -65,4 +68,4 @@ ws.on("message", (data) => {
} }
client.publish(secrets.mqttTopic, JSON.stringify(message)); client.publish(secrets.mqttTopic, JSON.stringify(message));
}); };