-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMMM-STStatus.js
More file actions
618 lines (536 loc) · 19.6 KB
/
Copy pathMMM-STStatus.js
File metadata and controls
618 lines (536 loc) · 19.6 KB
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
/* MMM-STStatus.js
* MagicMirror² module for displaying SmartThings device status
*
* By: Sonny Bertoncini
* License: MIT
*/
Module.register("MMM-STStatus", {
// Module requirements
requiresVersion: "2.25.0",
// Default configuration
defaults: {
token: "", // Legacy: SmartThings Personal Access Token (deprecated)
devices: [], // Explicit device list: [{ id: "xxx", name: "Name" }]
hiddenDevices: [], // Device IDs to hide from display while still fetching/broadcasting
rooms: [], // Room names to include: ["Living Room", "Kitchen"]
pollInterval: 60000, // Polling interval in ms (default: 60 seconds)
registrationCheckInterval: 30000, // Re-register after a node_helper restart
broadcastDeviceData: false, // Broadcast normalized device data for other modules
broadcastNotification: "STSTATUS_DEVICE_DATA",
showLastUpdated: true, // Show last updated timestamp
showDeviceType: true, // Show device type column
fontSize: 100, // Font size as percentage (100 = default)
temperatureUnit: "F", // "F" or "C"
defaultSort: "name", // Sort by: "name", "room", "capability"
debug: false, // Enable verbose logging
testMode: false // Use mock data instead of live API
},
// Thermostat capability rules
CAPABILITY_RULES: {
thermostatOperatingState: {
heating: "thermostat-heating",
cooling: "thermostat-cooling",
"fan only": "thermostat-fan-only",
fan: "thermostat-fan-only",
idle: "thermostat-idle"
}
},
// Capability to icon mapping
CAPABILITY_ICONS: {
switch: { on: "fa-lightbulb", off: "fa-lightbulb" },
contact: { open: "fa-door-open", closed: "fa-door-closed" },
motion: { active: "fa-person-walking", inactive: "fa-person" },
lock: { locked: "fa-lock", unlocked: "fa-lock-open" },
presence: { present: "fa-house-user", notPresent: "fa-house" },
temperature: "fa-thermometer-half",
humidity: "fa-droplet",
blinds: { open: "fa-window-maximize", closed: "fa-window-maximize", partially: "fa-window-maximize" },
level: "fa-sliders",
battery: {
high: "fa-battery-full",
medium: "fa-battery-half",
low: "fa-battery-quarter"
}
},
// State color classes
STATE_CLASSES: {
on: "state-on",
off: "state-off",
open: "state-open",
closed: "state-closed",
locked: "state-locked",
unlocked: "state-unlocked",
active: "state-motion",
inactive: "state-inactive",
present: "state-home",
notPresent: "state-away",
partially: "state-partially"
},
// Capability to friendly label translation keys
CAPABILITY_LABELS: {
switch: "TYPE_SWITCH",
contact: "TYPE_DOOR_SENSOR",
motion: "TYPE_MOTION_SENSOR",
lock: "TYPE_LOCK",
presence: "TYPE_PRESENCE",
temperature: "TYPE_THERMOSTAT",
humidity: "TYPE_HUMIDITY",
blinds: "TYPE_BLINDS",
level: "TYPE_DIMMER",
battery: "TYPE_BATTERY"
},
// Module state
deviceData: [],
loading: true,
error: null,
lastUpdate: null,
currentAlert: null, // { type: string, messageKey: string }
registrationCheckTimer: null,
/**
* Called when module starts
*/
start: function () {
Log.info("[MMM-STStatus] Starting module...");
// Config validation is minimal now - OAuth data is loaded from encrypted file by node_helper
// Only validate that we have devices/rooms configured (unless in test mode)
if (this.config.devices.length === 0 && this.config.rooms.length === 0 && !this.config.testMode) {
this.error = this.translate("ERROR_NO_DEVICES");
Log.error("[MMM-STStatus] ERROR: " + this.error);
return;
}
this.registerBackend();
// Browser socket reconnects do not call start() again. Periodically ask
// the helper whether this instance is still registered so a helper/PM2
// restart can rebuild its in-memory poll timer without a browser reload.
const registrationCheckInterval = Math.max(
Number(this.config.registrationCheckInterval) || 30000,
10000
);
this.registrationCheckTimer = setInterval(() => {
this.sendSocketNotification("CHECK_INSTANCE", {
identifier: this.identifier
});
}, registrationCheckInterval);
},
registerBackend: function () {
// Send config to backend with this instance identifier so the helper can
// keep per-instance state when multiple MagicMirror configs load the module.
this.sendSocketNotification("SET_CONFIG", {
...this.config,
identifier: this.identifier
});
},
/**
* Load CSS styles
*/
getStyles: function () {
return [
this.file("node_modules/@fortawesome/fontawesome-free/css/all.min.css"),
this.file("css/MMM-STStatus.css")
];
},
/**
* Load translations
*/
getTranslations: function () {
return {
en: "translations/en.json",
de: "translations/de.json",
fr: "translations/fr.json",
es: "translations/es.json",
nl: "translations/nl.json"
};
},
/**
* Handle socket notifications from node_helper
*/
socketNotificationReceived: function (notification, payload) {
if (this.config.debug) {
Log.info("[MMM-STStatus] Received: " + notification);
}
if (payload && payload.identifier && payload.identifier !== this.identifier) {
return;
}
switch (notification) {
case "DEVICE_DATA":
this.loading = false;
this.error = null;
this.deviceData = this.filterDevices(payload.devices || []);
this.lastUpdate = payload.timestamp || new Date().toISOString();
if (this.config.broadcastDeviceData && this.config.broadcastNotification) {
this.sendNotification(this.config.broadcastNotification, {
devices: payload.devices || [],
timestamp: this.lastUpdate
});
}
this.updateDom();
break;
case "INSTANCE_REGISTRATION_REQUIRED":
this.registerBackend();
break;
case "ERROR":
this.loading = false;
this.error = payload.message || "Unknown error";
Log.error("[MMM-STStatus] ERROR: " + this.error);
// Keep showing old data if available
if (payload.cached && payload.devices) {
this.deviceData = payload.devices;
this.lastUpdate = payload.timestamp;
}
this.updateDom();
break;
case "LOADING":
this.loading = true;
this.updateDom();
break;
case "ALERT":
this.currentAlert = {
type: payload.type,
messageKey: payload.messageKey
};
Log.warn("[MMM-STStatus] Alert: " + payload.type);
this.updateDom();
break;
case "ALERT_CLEAR":
this.currentAlert = null;
Log.info("[MMM-STStatus] Alert cleared");
this.updateDom();
break;
}
},
/**
* Generate the DOM for this module
*/
getDom: function () {
const wrapper = document.createElement("div");
wrapper.className = "mmm-ststatus";
// Apply font size scaling
const fontScale = (this.config.fontSize || 100) / 100;
wrapper.style.setProperty("--mmm-ststatus-font-scale", fontScale);
// Show loading state
if (this.loading && this.deviceData.length === 0) {
wrapper.innerHTML = this.getLoadingHtml();
return wrapper;
}
// Show error state (but still show cached data if available)
if (this.error) {
const errorDiv = document.createElement("div");
errorDiv.className = "error-message";
errorDiv.innerHTML = '<i class="fas fa-exclamation-triangle"></i> ' + this.error;
wrapper.appendChild(errorDiv);
}
// Show device table
if (this.deviceData.length > 0) {
wrapper.appendChild(this.getDeviceTable());
} else if (!this.error) {
wrapper.innerHTML = '<div class="no-devices">' + this.translate("NO_DEVICES") + '</div>';
}
// Footer: Show alert OR last update time (alert takes precedence)
if (this.currentAlert) {
const alertDiv = document.createElement("div");
alertDiv.className = "footer-alert";
alertDiv.innerHTML = '<i class="fas fa-exclamation-triangle"></i> ' + this.translate(this.currentAlert.messageKey);
wrapper.appendChild(alertDiv);
} else if (this.config.showLastUpdated && this.lastUpdate) {
const footer = document.createElement("div");
footer.className = "last-updated";
footer.innerHTML = this.translate("LAST_UPDATE") + ": " + this.formatTime(this.lastUpdate);
wrapper.appendChild(footer);
}
return wrapper;
},
/**
* Generate loading HTML
*/
getLoadingHtml: function () {
return '<div class="loading"><i class="fas fa-spinner fa-spin"></i> ' + this.translate("LOADING") + '</div>';
},
/**
* Generate device table
*/
getDeviceTable: function () {
const table = document.createElement("table");
table.className = "device-table";
// Sort devices
const sortedDevices = this.sortDevices(this.deviceData);
// Create rows
sortedDevices.forEach(device => {
const row = this.createDeviceRow(device);
table.appendChild(row);
});
return table;
},
/**
* Create a row for a device
*/
createDeviceRow: function (device) {
const row = document.createElement("tr");
row.className = "device-row";
// Icon cell
const iconCell = document.createElement("td");
iconCell.className = "device-icon";
iconCell.innerHTML = this.getDeviceIcon(device);
row.appendChild(iconCell);
// Name cell
const nameCell = document.createElement("td");
nameCell.className = "device-name";
nameCell.textContent = device.name || device.label || this.translate("UNKNOWN_DEVICE");
row.appendChild(nameCell);
// Type cell (optional)
if (this.config.showDeviceType) {
const typeCell = document.createElement("td");
typeCell.className = "device-type";
typeCell.textContent = this.getDeviceTypeLabel(device);
row.appendChild(typeCell);
}
// Primary status cell
const statusCell = document.createElement("td");
statusCell.className = "device-status";
statusCell.innerHTML = this.getPrimaryStatus(device);
row.appendChild(statusCell);
// Secondary attributes cell
const secondaryCell = document.createElement("td");
secondaryCell.className = "device-secondary";
secondaryCell.innerHTML = this.getSecondaryStatus(device);
row.appendChild(secondaryCell);
return row;
},
/**
* Get friendly label for device type based on primary capability
*/
getDeviceTypeLabel: function (device) {
const capability = device.primaryCapability;
if (capability && this.CAPABILITY_LABELS[capability]) {
return this.translate(this.CAPABILITY_LABELS[capability]);
}
// Fallback: capitalize the capability name or show "Unknown"
if (capability) {
return capability.charAt(0).toUpperCase() + capability.slice(1);
}
return this.translate("TYPE_UNKNOWN");
},
/**
* Get the icon for a device based on its capability and state
*/
getDeviceIcon: function (device) {
const capability = device.primaryCapability;
const state = device.primaryState;
let iconClass = "fa-question";
let stateClass = "";
if (capability && this.CAPABILITY_ICONS[capability]) {
const iconDef = this.CAPABILITY_ICONS[capability];
if (typeof iconDef === "string") {
iconClass = iconDef;
} else if (typeof iconDef === "object") {
// Handle battery levels
if (capability === "battery" && typeof state === "number") {
if (state > 60) iconClass = iconDef.high;
else if (state >= 20) iconClass = iconDef.medium;
else iconClass = iconDef.low;
// Handle blinds based on level
} else if (capability === "blinds" && device.level !== undefined) {
if (device.level === 0) {
iconClass = iconDef.closed;
stateClass = "state-closed";
} else if (device.level === 100) {
iconClass = iconDef.open;
stateClass = "state-open";
} else {
iconClass = iconDef.partially;
stateClass = "state-partially";
}
} else {
// Handle state-based icons
iconClass = iconDef[state] || iconDef[Object.keys(iconDef)[0]];
}
}
// Get state class for coloring
if (!stateClass && state && this.STATE_CLASSES[state]) {
stateClass = this.STATE_CLASSES[state];
}
}
return '<i class="fas ' + iconClass + ' ' + stateClass + '"></i>';
},
/**
* Get primary status display for a device
*/
getPrimaryStatus: function (device) {
const capability = device.primaryCapability;
const state = device.primaryState;
let displayValue = "—";
let stateClass = "";
let valueClass = "";
// Normalize display values
switch (capability) {
case "switch":
displayValue = state === "on" ? this.translate("ON") : this.translate("OFF");
stateClass = state === "on" ? "state-on" : "state-off";
break;
case "lock":
displayValue = state === "locked" ? this.translate("LOCKED") : this.translate("UNLOCKED");
stateClass = state === "locked" ? "state-locked" : "state-unlocked";
break;
case "contact":
displayValue = state === "open" ? this.translate("OPEN") : this.translate("CLOSED");
stateClass = state === "open" ? "state-open" : "state-closed";
break;
case "motion":
displayValue = state === "active" ? this.translate("MOTION") : "—";
stateClass = state === "active" ? "state-motion" : "state-inactive";
break;
case "presence":
displayValue = state === "present" ? this.translate("HOME") : this.translate("AWAY");
stateClass = state === "present" ? "state-home" : "state-away";
break;
case "temperature": {
const temp =
typeof state === "number"
? state
: typeof device.temperature === "number"
? device.temperature
: undefined;
displayValue =
typeof temp === "number"
? this.formatTemperature(temp)
: "—";
break;
}
case "blinds": {
// Use level from device if primaryState is not a number
const level = typeof state === "number" ? state : device.level;
if (typeof level === "number") {
displayValue = level + "%";
// Determine state class based on level
if (level === 0) {
stateClass = "state-closed";
} else if (level === 100) {
stateClass = "state-open";
} else {
stateClass = "state-partially";
}
} else {
displayValue = "—";
}
break;
}
default:
if (state && typeof state === "object" && "value" in state) {
displayValue = state.value.toString();
} else if (state !== undefined && state !== null) {
displayValue = state.toString();
}
break;
}
// Apply capability-based styling rules (e.g. thermostat operating state)
if (device.capabilities) {
for (const cap in this.CAPABILITY_RULES) {
const capValue = device.capabilities[cap];
const ruleSet = this.CAPABILITY_RULES[cap];
if (capValue && ruleSet[capValue]) {
valueClass += " " + ruleSet[capValue];
}
}
}
return (
'<span class="status-value ' +
stateClass + ' ' + valueClass +
'">' +
displayValue +
'</span>'
);
},
/**
* Get secondary status attributes (battery, temperature, etc.)
*/
getSecondaryStatus: function (device) {
const parts = [];
// Add battery if present and not primary
if (device.battery !== undefined && device.primaryCapability !== "battery") {
const batteryClass = device.battery < 20 ? "state-battery-low" : "";
parts.push('<span class="secondary-item ' + batteryClass + '"><i class="fas fa-battery-half"></i> ' + device.battery + '%</span>');
}
// Add temperature if present and not primary
if (device.temperature !== undefined && device.primaryCapability !== "temperature") {
parts.push('<span class="secondary-item"><i class="fas fa-thermometer-half"></i> ' + this.formatTemperature(device.temperature) + '</span>');
}
// Add humidity if present and not primary
if (device.humidity !== undefined && device.primaryCapability !== "humidity") {
parts.push('<span class="secondary-item"><i class="fas fa-droplet"></i> ' + device.humidity + '%</span>');
}
// Add dimmer level for switch devices that have a level (not blinds)
if (device.level !== undefined && device.primaryCapability === "switch") {
parts.push('<span class="secondary-item"><i class="fas fa-sliders"></i> ' + device.level + '%</span>');
}
// Add thermostat setpoints for temperature devices (thermostats)
if (device.heatingSetpoint !== undefined || device.coolingSetpoint !== undefined) {
let setpointText = '';
if (device.heatingSetpoint !== undefined && device.coolingSetpoint !== undefined) {
// Show both setpoints for auto mode
setpointText = this.formatTemperature(device.heatingSetpoint) + ' - ' + this.formatTemperature(device.coolingSetpoint);
} else if (device.heatingSetpoint !== undefined) {
setpointText = this.translate("HEAT") + ': ' + this.formatTemperature(device.heatingSetpoint);
} else if (device.coolingSetpoint !== undefined) {
setpointText = this.translate("COOL") + ': ' + this.formatTemperature(device.coolingSetpoint);
}
if (setpointText) {
parts.push('<span class="secondary-item"><i class="fas fa-crosshairs"></i> ' + setpointText + '</span>');
}
}
return parts.join(" ");
},
/**
* Format temperature based on config
*/
formatTemperature: function (value) {
if (value === undefined || value === null) return "—";
const unit = this.config.temperatureUnit.toUpperCase();
if (unit === "C") {
// Assume SmartThings returns Fahrenheit, convert to Celsius
const celsius = Math.round((value - 32) * 5 / 9);
return celsius + "°C";
}
return Math.round(value) + "°F";
},
/**
* Sort devices based on config
*/
sortDevices: function (devices) {
const sortBy = this.config.defaultSort;
return devices.slice().sort((a, b) => {
switch (sortBy) {
case "room":
return (a.room || "").localeCompare(b.room || "");
case "capability":
return (a.primaryCapability || "").localeCompare(b.primaryCapability || "");
case "name":
default:
return (a.name || "").localeCompare(b.name || "");
}
});
},
/**
* Filter devices based on config.devices array (frontend filtering for multi-instance support)
*/
filterDevices: function (devices) {
const hiddenIds = new Set(Array.isArray(this.config.hiddenDevices) ? this.config.hiddenDevices : []);
const visibleDevices = devices.filter(function (device) {
return !hiddenIds.has(device.id);
});
if (!this.config.devices || this.config.devices.length === 0) {
return visibleDevices;
}
const configDeviceIds = this.config.devices.map(function (d) {
return d.id;
});
return visibleDevices.filter(function (device) {
return configDeviceIds.indexOf(device.id) !== -1;
});
},
/**
* Format timestamp for display as clock time
*/
formatTime: function (isoString) {
const date = new Date(isoString);
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}
});