-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
263 lines (214 loc) · 6.44 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
var config = require("./config");
var botgram = require("botgram");
var mqtt = require("mqtt");
var Timer = require("./lib/timer");
var EditedMessage = require("./lib/edited-message");
var UPS = require("./lib/ups");
var bot = botgram(config.bot_token);
var reply = bot.reply(config.group_id);
var secReply = bot.reply(config.backoffice_id);
bot.on("ready", () => {
console.log("Bot ready.");
secReply.text("Bot ready.");
});
var ignore = true;
var client = mqtt.connect(config.mqtt_url, config.mqtt_options);
client.on("connect", function () {
client.subscribe("vocore-timbre/ring-time");
client.subscribe("vocore-timbre/online");
client.subscribe("manel-router/dash-1/press-time");
client.subscribe("manel-router/online");
setTimeout(() => { ignore = false; }, 1000);
});
client.on("error", function () {
console.error("At %s -> %s", new Date().toISOString(), err.stack);
});
var mainUps = new UPS({
hostname: config.ups.hostname,
name: config.ups.name,
interval: 2 * 1000,
});
/* Error handling */
var errorMessageSending = false;
var lastError;
bot.on("error", (err) => {
console.error("At %s -> %s", new Date().toISOString(), err.stack);
lastError = err;
if (errorMessageSending) return;
errorMessageSending = true;
function sendMsg() {
secReply.text("Internal error! Last:\n\n" + lastError.toString());
secReply.then((err, msg) => {
if (err)
setTimeout(sendMsg, 60000);
else
errorMessageSending = false;
});
}
sendMsg();
});
/* Ping command */
bot.command("ping", (msg, reply, next) => {
if (msg.chat.id !== config.backoffice_id) return next();
const { version } = require("./package.json");
reply.html(
`Pong! Status:
Version %s
MQTT: <strong>%s</strong>
Timbre: <strong>%s</strong>
UPS: <strong>%s</strong>
Router Manel: <strong>%s</strong>`,
version,
client.connected ? "connected" : "disconnected!",
timbreCurrentOnline ? "online" : "offline!",
reachable ? "reachable" : "unreachable!",
manelCurrentOnline ? "online" : "offline!");
});
/** TIMBRE CASA **/
var timbreCurrentOnline = true;
(function () {
function setCurrentOnline(online) {
if (online == timbreCurrentOnline) return;
if (online) secReply.silent().markdown("Vocore online again.");
else secReply.markdown("Vocore offline!");
timbreCurrentOnline = online;
}
var onlineTimer = new Timer(1000);
onlineTimer.on("fire", () => {
setCurrentOnline(false);
});
client.on("message", function (topic, msg) {
try {
msg = msg.toString("utf-8");
} catch (e) {
return;
}
if (topic === "vocore-timbre/ring-time") {
if (ignore) return;
var n = parseInt(msg, 10);
if (isNaN(n) || n < Date.now()/1000 - 5)
reply.markdown("Llaman al timbre, fuera de rango: " + n + " (" + (Math.floor(Date.now()/1000)-n) + ")");
else
reply.markdown("🛎 Llaman al timbre");
}
if (topic === "vocore-timbre/online") {
console.log("[%s] timbre going online = %s", new Date().toISOString(), msg);
if (msg !== "true" && msg !== "false") return;
var online = JSON.parse(msg);
if (!online) onlineTimer.reset();
else {
onlineTimer.clear();
setCurrentOnline(true);
}
}
});
})();
/** UPS **/
var reachable = true;
function setReachable(r, e) {
if (reachable === r) return;
reachable = r;
if (r)
secReply.silent().markdown("UPS reachable again.");
else
secReply.markdown("UPS unreachable!\n" + e.toString());
}
var batteryCharge;
var batteryMessage;
var batteryUpdateTimer = new Timer(30 * 1000);
function renderBatteryMessage() {
return "🔋 Carga de las baterías: <strong>" + batteryCharge + "%</strong>";
}
function publishBatteryMessage() {
batteryMessage = new EditedMessage(reply.silent(), renderBatteryMessage(), "HTML");
batteryMessage.on("error", (e) => bot.emit("error", e));
batteryMessage.on("editError", (e) => bot.emit("error", e));
batteryUpdateTimer.reset();
}
batteryUpdateTimer.on("fire", () => {
batteryMessage.edit(renderBatteryMessage());
batteryUpdateTimer.reset();
});
function deactivateBatteryMessage() {
batteryUpdateTimer.clear();
batteryMessage = null;
}
var upsOnline = true;
var batteryPublishTimer = new Timer(5 * 1000);
batteryPublishTimer.on("fire", () => {
publishBatteryMessage();
});
function setUpsOnline(ol) {
if (upsOnline === ol) return;
upsOnline = ol;
if (ol) {
reply.markdown("🔌✅ Electricidad restablecida");
batteryPublishTimer.clear();
deactivateBatteryMessage();
} else {
reply.markdown("🔌❌ ¡No hay electricidad!");
batteryPublishTimer.reset();
}
}
var fsdSeen = false;
mainUps.on("state", () => {
if (mainUps.lastError)
setReachable(false, mainUps.lastError);
else if (mainUps.lastResults)
setReachable(true);
if (!mainUps.lastResults) return;
var r = mainUps.lastResults;
var charge = Math.pow(parseFloat(r["battery.voltage"]) / 12.36, 16.00);
charge = Math.max(0, Math.min(1, charge));
batteryCharge = Math.round(charge * 100);
var status = r["ups.status"].split(/\s+/g);
if (status.indexOf("OL")!==-1)
setUpsOnline(true);
else
setUpsOnline(false);
if ((status.indexOf("OB")!==-1 && status.indexOf("LB")!==-1) || status.indexOf("FSD")!==-1) {
if (!fsdSeen) {
fsdSeen = true;
reply.markdown("❗️ **Carga critica, petición de apagado general** ❗️");
}
}
});
/** DASHES MANEL **/
var manelCurrentOnline = true;
(function () {
function setCurrentOnline(online) {
if (online == manelCurrentOnline) return;
if (online) secReply.silent().markdown("manel-router online again.");
else secReply.markdown("manel-router offline!");
manelCurrentOnline = online;
}
var onlineTimer = new Timer(1000);
onlineTimer.on("fire", () => {
setCurrentOnline(false);
});
client.on("message", function (topic, msg) {
try {
msg = msg.toString("utf-8");
} catch (e) {
return;
}
if (topic === "manel-router/dash-1/press-time") {
if (ignore) return;
var n = parseInt(msg, 10);
if (isNaN(n) || n < Date.now()/1000 - 5)
reply.markdown("Botón presionado fuera de rango: " + n + " (" + (Math.floor(Date.now()/1000)-n) + ")");
else
reply.markdown("‼️ Emergencia");
}
if (topic === "manel-router/online") {
console.log("[%s] manel-router online = %s", new Date().toISOString(), msg);
if (msg !== "true" && msg !== "false") return;
var online = JSON.parse(msg);
if (!online) onlineTimer.reset();
else {
onlineTimer.clear();
setCurrentOnline(true);
}
}
});
})();