forked from shaarkys/Homey_Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckLastUpdate_any.js
More file actions
251 lines (212 loc) · 8.71 KB
/
checkLastUpdate_any.js
File metadata and controls
251 lines (212 loc) · 8.71 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
// v0.8 — Any-device LastUpdated + Battery monitor
// - NA/invalid lastUpdated ⇒ NOK with reason codes (“no updates”)
// - Uses system/runtime time zone by default (universal); optional TIME_ZONE override
// - Battery: measure_battery (<= threshold) and/or alarm_battery=true
// - Tags: InvalidatedDevices, notReportingCount, LowBatteryDevices, lowBatteryCount
// ───────────────────────── configurable ─────────────────────────
const NOT_REPORTING_THRESHOLD_HOURS = 0.8; // 48 minutes
const THRESHOLD_IN_MILLIS = NOT_REPORTING_THRESHOLD_HOURS * 3600000;
const BATTERY_THRESHOLD_PERCENT = 30;
const INCLUDE_BATTERY_ALARM_AS_LOW = true;
// Optional time zone override (e.g., "Europe/Prague"). Leave null/'' to use system TZ.
const TIME_ZONE = null;
// Zones, drivers, names, classes
const EXCLUDED_ZONES = ['Garage', 'Living Room']; // case-insensitive full-string match
const EXCLUDED_DRIVER_URI_PATTERN =
/vdevice|nl\.qluster-it\.DeviceCapabilities|nl\.fellownet\.chronograph|net\.i-dev\.betterlogic|com\.swttt\.devicegroups|com\.gruijter\.callmebot|com\.netscan/i;
const INCLUDED_DEVICE_NAME_REGEX = /.*/i; // include all by default
const EXCLUDED_DEVICE_NAME_PATTERN =
/Flood|Netatmo Rain|Motion|Flora|Rear gate Vibration Sensor|Vibration Sensor Attic Doors/i;
// NOTE: Homey class is "light" (singular), not "lights"
const INCLUDED_DEVICE_CLASS_REGEX = /sensor|button|remote|socket|light|bulb|other|switch/i;
// Technology flags
const EXCLUDED_FLAGS = ['']; // e.g.: ['zigbee','zwave'] to exclude those stacks
const EXCLUDE_EMPTY_FLAGS = false; // true => exclude devices with empty flags
// Label used when there have been no updates (invalid/absent timestamp)
const NO_UPDATES_LABEL = 'No updates';
// ───────────────────────── internals ────────────────────────────
let okDevices = [];
let nokDevices = [];
let DevicesNotReporting = [];
let notReportingCount = 0;
let DevicesLowBattery = [];
let lowBatteryCount = 0;
const devices = await Homey.devices.getDevices();
const zones = await Homey.zones.getZones();
const zonesArray = Array.isArray(zones) ? zones : Object.values(zones);
const zoneMap = {};
zonesArray.forEach(z => { zoneMap[z.id] = z.name; });
// Function to format date as "dd-mm-yyyy, hh:mm:ss"
function formatDate(date) {
if (!date || isNaN(date.getTime())) return NO_UPDATES_LABEL;
const d = date;
// Use system time zone unless TIME_ZONE is set
const opts = {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false
};
if (TIME_ZONE) opts.timeZone = TIME_ZONE;
const parts = new Intl.DateTimeFormat('en-GB', opts).formatToParts(d);
const get = (t) => parts.find(p => p.type === t)?.value ?? '';
const DD = get('day').padStart(2, '0');
const MM = get('month').padStart(2, '0');
const YYYY = get('year');
const HH = get('hour').padStart(2, '0');
const mm = get('minute').padStart(2, '0');
const ss = get('second').padStart(2, '0');
return `${DD}-${MM}-${YYYY}, ${HH}:${mm}:${ss}`;
}
// Simple right-padding function for column formatting
function padRight(str, width) {
str = String(str);
if (str.length >= width) return str.slice(0, width);
return str + ' '.repeat(width - str.length);
}
for (const device of Object.values(devices)) {
// 1) Exclude certain driver URIs (virtual devices, app placeholders, etc.)
if (device.driverUri && EXCLUDED_DRIVER_URI_PATTERN.test(device.driverUri)) continue;
// 2) Zone checks
const zoneName = device.zone ? zoneMap[device.zone] : null;
if (zoneName && EXCLUDED_ZONES.some(z => z.toLowerCase() === zoneName.toLowerCase())) continue;
// 3) Name/class filters
if (!device.name || !INCLUDED_DEVICE_NAME_REGEX.test(device.name)) continue;
if (EXCLUDED_DEVICE_NAME_PATTERN.test(device.name)) continue;
if (!device.class || !INCLUDED_DEVICE_CLASS_REGEX.test(device.class)) continue;
// 4) Exclude based on technology
if (
(device.flags && EXCLUDED_FLAGS.some(flag => device.flags.includes(flag))) ||
(EXCLUDE_EMPTY_FLAGS && Array.isArray(device.flags) && (device.flags.length === 0))
) continue;
// Most recent lastUpdated across capabilities
let mostRecentTs = NaN;
if (device.capabilitiesObj) {
for (const cap of Object.values(device.capabilitiesObj)) {
const iso = cap?.lastUpdated;
if (!iso) continue;
const ts = new Date(iso).getTime();
if (Number.isNaN(ts)) continue;
if (Number.isNaN(mostRecentTs) || ts > mostRecentTs) mostRecentTs = ts;
}
}
// Reporting decision
const now = Date.now();
let isReporting = false;
let reason = '';
if (Number.isNaN(mostRecentTs)) {
isReporting = false;
reason = 'NOK: no updates';
} else {
const age = now - mostRecentTs;
if (age < THRESHOLD_IN_MILLIS) {
isReporting = true;
} else {
isReporting = false;
reason = `NOK: threshold ${NOT_REPORTING_THRESHOLD_HOURS}h`;
}
}
// -------- Battery checks --------
let batteryStr = 'N/A';
let isLowBattery = false;
const caps = device.capabilities || [];
const capsObj = device.capabilitiesObj || {};
if (caps.includes('measure_battery')) {
const v = capsObj.measure_battery?.value;
if (typeof v === 'number' && !Number.isNaN(v)) {
batteryStr = `${Math.round(v)}%`;
if (v <= BATTERY_THRESHOLD_PERCENT) isLowBattery = true;
}
}
if (caps.includes('alarm_battery')) {
const alarmVal = !!(capsObj.alarm_battery?.value === true);
if (alarmVal && INCLUDE_BATTERY_ALARM_AS_LOW) {
isLowBattery = true;
if (batteryStr === 'N/A') batteryStr = 'ALARM';
} else if (batteryStr === 'N/A') {
batteryStr = 'OK';
}
}
if (isLowBattery) {
lowBatteryCount++;
DevicesLowBattery.push(`${device.name} ${batteryStr}`);
}
const formatted = Number.isNaN(mostRecentTs) ? NO_UPDATES_LABEL : formatDate(new Date(mostRecentTs));
const rowObj = {
name: device.name,
formattedDate: formatted,
class: device.class,
batt: batteryStr,
status: isReporting ? '(OK)' : '(NOK)'
};
if (!isReporting) {
notReportingCount++;
const reasonSuffix = reason ? ` - ${reason}` : '';
DevicesNotReporting.push(`${rowObj.name} (${rowObj.formattedDate} - ${rowObj.class}) (NOK)${reasonSuffix}`);
nokDevices.push(rowObj);
} else {
okDevices.push(rowObj);
}
}
// Log results in columns
const totalDevices = okDevices.length + nokDevices.length;
console.log(`${totalDevices} device(s) scanned.`);
console.log(`OK: ${okDevices.length}`);
console.log(`NOK: ${nokDevices.length}`);
console.log(`Low Battery (≤${BATTERY_THRESHOLD_PERCENT}%${INCLUDE_BATTERY_ALARM_AS_LOW ? ' or alarm' : ''}): ${lowBatteryCount}`);
console.log('---------------------------------------------');
// Prepare column headers
const header = [
padRight('#', 4),
padRight('Device Name', 35),
padRight('Last Updated', 20),
padRight('Class', 10),
padRight('Batt', 6),
padRight('Status', 6)
].join(' ');
// Helper to print rows in columns
function printRows(devArray) {
devArray.forEach((row, idx) => {
const line = [
padRight(String(idx + 1), 4),
padRight(row.name, 35),
padRight(row.formattedDate, 20),
padRight(row.class, 10),
padRight(row.batt, 6),
padRight(row.status, 6)
].join(' ');
console.log(line);
});
}
// Print OK devices
if (okDevices.length > 0) {
console.log(`\nOK device(s): ${okDevices.length}`);
console.log(header);
console.log('-'.repeat(header.length));
printRows(okDevices);
}
// Print NOK devices
if (nokDevices.length > 0) {
console.log(`\nNOK device(s): ${nokDevices.length}`);
console.log(header);
console.log('-'.repeat(header.length));
printRows(nokDevices);
}
// Print Low Battery devices (summary list)
if (lowBatteryCount > 0) {
console.log(`\nLow-battery device(s) (≤${BATTERY_THRESHOLD_PERCENT}%${INCLUDE_BATTERY_ALARM_AS_LOW ? ' or alarm' : ''}): ${lowBatteryCount}`);
DevicesLowBattery.forEach((d, i) => console.log(`${i + 1}. ${d}`));
}
console.log('---------------------------------------------\n');
// Output for script AND card
await tag('InvalidatedDevices', DevicesNotReporting.join('\n'));
await tag('notReportingCount', notReportingCount);
// Added battery tags
await tag('LowBatteryDevices', DevicesLowBattery.join('\n'));
await tag('lowBatteryCount', lowBatteryCount);
// Define a return value
const myTag =
`Not Reporting Count: ${notReportingCount}\n` +
`Low Battery Count: ${lowBatteryCount}\n` +
`Devices Not Reporting:\n${DevicesNotReporting.join('\n')}` +
(DevicesLowBattery.length ? `\nDevices Low Battery:\n${DevicesLowBattery.join('\n')}` : '');
return myTag;