@homebridge-plugins/homebridge-printer 0.0.0-stage → 1.0.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/energy.js ADDED
@@ -0,0 +1,485 @@
1
+ /**
2
+ * Estimated energy use for a printer, published to Apple Home through Homebridge's
3
+ * Matter bridge (Homebridge 2.3+, iOS 27+ Home app "Electricity" view).
4
+ *
5
+ * Printers don't report how much power they draw, only what they are doing, so
6
+ * the power is ESTIMATED from the printer's state using per-state wattages (HP's
7
+ * published figures for the DeskJet 2800 series by default), and the running
8
+ * total is the integral of that estimate over time.
9
+ */
10
+
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+
14
+ const MIN_HB = '2.3.0'
15
+ const POWER_UPDATE_MS = 10 * 1000 // matter.js throttles power reports to ~10 s anyway
16
+ const ENERGY_UPDATE_MS = 60 * 1000 // energy events are not throttled: update once a minute
17
+ const SAVE_MS = 60 * 1000
18
+ const PART_ID = 'outlet'
19
+
20
+ /** Defaults: HP DeskJet 2800e series data sheet (ready 2.8 W, sleep 1.4 W, off 0.3 W). Printing isn't published. */
21
+ const DEFAULT_WATTS = {
22
+ printing: 10,
23
+ ready: 2.8,
24
+ sleep: 1.4,
25
+ off: 0.3,
26
+ }
27
+
28
+ function num(v, d) {
29
+ return v === '' || v === null || v === undefined || !Number.isFinite(Number(v))
30
+ ? d
31
+ : Math.max(0, Number(v))
32
+ }
33
+
34
+ function normaliseEnergyConfig(p) {
35
+ const e = (p && typeof p.energy === 'object' && p.energy) || {}
36
+ return {
37
+ enabled: e.enabled !== false,
38
+ watts: {
39
+ printing: num(e.printingWatts, DEFAULT_WATTS.printing),
40
+ ready: num(e.readyWatts, DEFAULT_WATTS.ready),
41
+ sleep: num(e.sleepWatts, DEFAULT_WATTS.sleep),
42
+ off: num(e.offWatts, DEFAULT_WATTS.off),
43
+ },
44
+ sleepAfterMinutes: num(e.sleepAfterMinutes, 5),
45
+ }
46
+ }
47
+
48
+ /** Which power state the printer is in, from what IPP tells us. */
49
+ function powerState(state, idleSince, now, sleepAfterMinutes) {
50
+ if (!state || !state.online) {
51
+ return 'off'
52
+ } // switched off, deep sleep off the network, or unreachable
53
+ if (state.printing || state.status === 'processing') {
54
+ return 'printing'
55
+ }
56
+ const reasons = (state.reasons || []).join(' ')
57
+ if (/sleep|power-sav|standby/i.test(reasons)) {
58
+ return 'sleep'
59
+ }
60
+ if (idleSince && now - idleSince >= sleepAfterMinutes * 60 * 1000) {
61
+ return 'sleep'
62
+ }
63
+ return 'ready'
64
+ }
65
+
66
+ class EnergyMeter {
67
+ /**
68
+ * @param {{ id: string, watts: object, sleepAfterMinutes: number, file: string, log: object, name: string }} opts
69
+ */
70
+ constructor(opts) {
71
+ this.opts = opts
72
+ this.watts = opts.watts
73
+ this.totalMWh = 0 // milliwatt-hours, Matter's unit
74
+ this.since = Date.now() // when the running total started
75
+ this.lastTick = null
76
+ this.stateName = 'off'
77
+ this.idleSince = null
78
+ this.load()
79
+ }
80
+
81
+ load() {
82
+ try {
83
+ const saved = JSON.parse(fs.readFileSync(this.opts.file, 'utf8'))
84
+ if (Number.isFinite(saved.totalMWh) && saved.totalMWh >= 0) {
85
+ this.totalMWh = saved.totalMWh
86
+ }
87
+ if (Number.isFinite(saved.since)) {
88
+ this.since = saved.since
89
+ }
90
+ } catch (_) {
91
+ /* first run */
92
+ }
93
+ }
94
+
95
+ save() {
96
+ try {
97
+ fs.mkdirSync(path.dirname(this.opts.file), { recursive: true })
98
+ const tmp = `${this.opts.file}.tmp`
99
+ fs.writeFileSync(
100
+ tmp,
101
+ JSON.stringify({
102
+ totalMWh: Math.round(this.totalMWh),
103
+ since: this.since,
104
+ savedAt: Date.now(),
105
+ }),
106
+ )
107
+ fs.renameSync(tmp, this.opts.file)
108
+ } catch (err) {
109
+ this.opts.log.debug(`${this.opts.name}: could not save energy total (${err.message})`)
110
+ }
111
+ }
112
+
113
+ get currentWatts() {
114
+ return this.watts[this.stateName] || 0
115
+ }
116
+
117
+ /** Add the energy used since the last tick at the current wattage, then switch to the new state. */
118
+ tick(state, now = Date.now()) {
119
+ if (this.lastTick !== null && now > this.lastTick) {
120
+ // Cap one gap at 10 minutes so a suspended/asleep host doesn't add a huge block at once
121
+ const ms = Math.min(now - this.lastTick, 10 * 60 * 1000)
122
+ this.totalMWh += (this.currentWatts * 1000 * ms) / 3600000
123
+ }
124
+ this.lastTick = now
125
+
126
+ if (state) {
127
+ const idle = state.online && !state.printing && state.status !== 'processing'
128
+ if (!idle) {
129
+ this.idleSince = null
130
+ } else if (this.idleSince === null) {
131
+ this.idleSince = now
132
+ }
133
+ this.stateName = powerState(state, this.idleSince, now, this.opts.sleepAfterMinutes)
134
+ }
135
+ return this.snapshot()
136
+ }
137
+
138
+ snapshot() {
139
+ return {
140
+ state: this.stateName,
141
+ watts: this.currentWatts,
142
+ kWh: Math.round(this.totalMWh) / 1e6,
143
+ since: new Date(this.since).toISOString(),
144
+ estimated: true,
145
+ }
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Publishes one Matter "outlet" per printer, carrying the estimated power and energy.
151
+ * Apple Home shows watts on outlet tiles and adds bridged devices to the home's total.
152
+ */
153
+ class MatterEnergyPublisher {
154
+ constructor(platform) {
155
+ this.platform = platform
156
+ this.api = platform.api
157
+ this.log = platform.log
158
+ this.cached = new Map() // UUID -> cached Matter accessory
159
+ this.entries = [] // { device, poller, meter, uuid }
160
+ this.timers = []
161
+ }
162
+
163
+ /** Why energy can't be published here, or null if it can. */
164
+ unavailableReason() {
165
+ if (!this.api.versionGreaterOrEqual || !this.api.versionGreaterOrEqual(MIN_HB)) {
166
+ return `needs Homebridge ${MIN_HB} or newer (this is ${this.api.serverVersion})`
167
+ }
168
+ const enabled = typeof this.api.isMatterEnabled === 'function'
169
+ ? this.api.isMatterEnabled()
170
+ : false
171
+ if (!enabled || !this.api.matter) {
172
+ return 'Matter is not turned on for the bridge this plugin runs on. In the Homebridge UI open Settings → Matter Settings, turn Matter on for the main bridge and restart, then add the Matter QR code from the Status page in the Home app (or, if this plugin runs as a child bridge, turn Matter on in its Child Bridge Config)'
173
+ }
174
+ return null
175
+ }
176
+
177
+ configureMatterAccessory(accessory) {
178
+ this.cached.set(accessory.UUID, accessory)
179
+ }
180
+
181
+ energyFile(device) {
182
+ return path.join(this.api.user.storagePath(), 'hp-printer', `energy-${device.id}.json`)
183
+ }
184
+
185
+ /**
186
+ * @param {object[]} devices
187
+ * @param {Map} pollers
188
+ * @param {{ matterOnly?: boolean }} [opts] matterOnly: also publish Printing over Matter, and Online
189
+ * even with energy turned off, because no HomeKit accessories are published.
190
+ */
191
+ async start(devices, pollers, opts = {}) {
192
+ const matterOnly = !!opts.matterOnly
193
+ const withEnergy = devices.filter(d => d.energy && d.energy.enabled)
194
+ const wantsMatter = devices.some(
195
+ d => (d.energy && d.energy.enabled) || (matterOnly && (d.onlineSwitch || d.printingSwitch)),
196
+ )
197
+ if (!wantsMatter) {
198
+ // Homebridge restores cached Matter accessories by itself, so an outlet from before
199
+ // stays in Home until it is removed here
200
+ await this.removeStale(new Set())
201
+ return
202
+ }
203
+ // The estimate always runs (it is shown on the dashboard); Apple Home needs Matter.
204
+ const reason = this.unavailableReason()
205
+ if (reason && withEnergy.length) {
206
+ this.log.info(`Energy in Apple Home is off: ${reason}. The estimate is still shown on the dashboard.`)
207
+ }
208
+
209
+ const matter = this.api.matter
210
+ const uuidGen = matter ? matter.uuid : this.api.hap.uuid
211
+ const toRegister = []
212
+ for (const device of devices) {
213
+ const poller = pollers.get(device.id)
214
+ const energyOn = device.energy && device.energy.enabled
215
+
216
+ // Switch 1: "<name> Online" outlet (carries the energy reading when energy is on)
217
+ if (energyOn || (matterOnly && device.onlineSwitch)) {
218
+ const meter = energyOn
219
+ ? new EnergyMeter({
220
+ id: device.id,
221
+ name: device.name,
222
+ watts: device.energy.watts,
223
+ sleepAfterMinutes: device.energy.sleepAfterMinutes,
224
+ file: this.energyFile(device),
225
+ log: this.log,
226
+ })
227
+ : null
228
+ const entry = {
229
+ kind: 'online',
230
+ device,
231
+ poller,
232
+ meter,
233
+ uuid: uuidGen.generate(`hp-printer:${device.name}:outlet-v2`),
234
+ lastPower: null,
235
+ lastOn: null,
236
+ }
237
+ this.entries.push(entry)
238
+ if (meter) {
239
+ meter.tick(poller.state)
240
+ }
241
+ poller.on('update', state => this.pushPower(entry, meter
242
+ ? meter.tick(state)
243
+ : null))
244
+ const name = (
245
+ device.onlineSwitch
246
+ ? device.onlineName || `${device.name} Online`
247
+ : `${device.name} Energy`
248
+ ).slice(0, 32)
249
+ if (!reason) {
250
+ toRegister.push(this.outletAccessory(entry, name, '-E'))
251
+ }
252
+ }
253
+
254
+ // Switch 2: "<name> Printing" outlet, Matter-only mode
255
+ if (matterOnly && device.printingSwitch) {
256
+ const entry = {
257
+ kind: 'printing',
258
+ device,
259
+ poller,
260
+ meter: null,
261
+ uuid: uuidGen.generate(`hp-printer:${device.name}:printing-v2`),
262
+ lastPower: null,
263
+ lastOn: null,
264
+ }
265
+ this.entries.push(entry)
266
+ poller.on('update', () => this.pushPower(entry, null))
267
+ if (!reason) {
268
+ toRegister.push(
269
+ this.outletAccessory(entry, (device.printingName || `${device.name} Printing`).slice(0, 32), '-P'),
270
+ )
271
+ }
272
+ }
273
+ }
274
+
275
+ const metered = () => this.entries.filter(e => e.meter)
276
+ const tickAll = () => metered().forEach(e => this.pushPower(e, e.meter.tick(e.poller.state)))
277
+ const energyAll = () => metered().forEach(e => this.pushEnergy(e))
278
+ const saveAll = () => metered().forEach(e => e.meter.save())
279
+ this.timers.push(
280
+ setInterval(tickAll, POWER_UPDATE_MS),
281
+ setInterval(energyAll, ENERGY_UPDATE_MS),
282
+ setInterval(saveAll, SAVE_MS),
283
+ )
284
+ this.timers.forEach(t => t.unref && t.unref())
285
+ if (reason) {
286
+ return
287
+ }
288
+
289
+ await this.register(toRegister)
290
+ // Remove Matter accessories for printers that were removed or had a switch/energy turned off
291
+ await this.removeStale(new Set(this.entries.map(e => e.uuid)))
292
+ }
293
+
294
+ /** Removes cached Matter accessories that are no longer wanted. */
295
+ async removeStale(keep) {
296
+ const stale = [
297
+ ...this.cached.values(),
298
+ ].filter(a => !keep.has(a.UUID))
299
+ if (!stale.length || !this.api.matter) {
300
+ return
301
+ }
302
+ try {
303
+ await this.api.matter.unregisterPlatformAccessories(this.platform.pluginName, this.platform.platformName, stale)
304
+ stale.forEach(a => this.log.info(`Removed Matter accessory: ${a.displayName}`))
305
+ } catch (err) {
306
+ this.log.warn(`Could not remove old Matter accessories: ${err.message}`)
307
+ }
308
+ }
309
+
310
+ /** The value an entry's outlet shows: printer reachable (Online) or printing (Printing). */
311
+ isOn(entry) {
312
+ return entry.kind === 'printing'
313
+ ? !!entry.poller.state.printing
314
+ : !!entry.poller.state.online
315
+ }
316
+
317
+ /**
318
+ * Composed shape, like certified Matter plugs and the Shelly plugin: a BridgedNode parent with
319
+ * the outlet as its part. Apple Home shows live watts on the tile with this shape; a flat
320
+ * bridged outlet only showed them in the accessory's details.
321
+ */
322
+ outletAccessory(entry, name, serialSuffix) {
323
+ const matter = this.api.matter
324
+ const { device, poller, meter } = entry
325
+ const cached = this.cached.get(entry.uuid)
326
+ const clusters = {
327
+ onOff: {
328
+ onOff: this.isOn(entry),
329
+ },
330
+ }
331
+ if (meter) {
332
+ clusters.electricalPowerMeasurement = {
333
+ activePower: Math.round(meter.currentWatts * 1000),
334
+ }
335
+ clusters.electricalEnergyMeasurement = {
336
+ cumulativeEnergyImported: {
337
+ energy: Math.round(meter.totalMWh),
338
+ startTimestamp: Math.floor(meter.since / 1000),
339
+ },
340
+ }
341
+ }
342
+ return {
343
+ UUID: entry.uuid,
344
+ displayName: name,
345
+ deviceType: matter.deviceTypes.BridgedNode,
346
+ manufacturer: String(device.manufacturer || 'HP').slice(0, 32),
347
+ model: String(device.model || poller.state.model || 'Printer')
348
+ .replace(/^HP\s+/i, '')
349
+ .slice(0, 32),
350
+ serialNumber: `${String(device.serialNumber || device.id.replace(/-/g, '').slice(0, 12)).slice(0, 29)}${serialSuffix}`,
351
+ firmwareRevision: this.platform.version,
352
+ context: (cached && cached.context) || {},
353
+ parts: [
354
+ {
355
+ id: PART_ID,
356
+ displayName: name,
357
+ deviceType: matter.deviceTypes.OnOffOutlet,
358
+ clusters,
359
+ // Status only: a printer can't be switched or started over the network,
360
+ // so a tap in Home is undone a moment later.
361
+ handlers: {
362
+ onOff: {
363
+ on: async () => this.snapBack(entry),
364
+ off: async () => this.snapBack(entry),
365
+ },
366
+ },
367
+ },
368
+ ],
369
+ }
370
+ }
371
+
372
+ async register(accessories, attempt = 1) {
373
+ try {
374
+ await this.api.matter.registerPlatformAccessories(
375
+ this.platform.pluginName,
376
+ this.platform.platformName,
377
+ accessories,
378
+ )
379
+ this.registered = true
380
+ // Readings that arrived while registration was pending were never sent: send the current ones now
381
+ for (const e of this.entries) {
382
+ e.lastPower = null
383
+ e.lastOn = null
384
+ this.pushPower(e, e.meter
385
+ ? e.meter.snapshot()
386
+ : null)
387
+ if (e.meter) {
388
+ this.pushEnergy(e)
389
+ }
390
+ }
391
+ accessories.forEach(a =>
392
+ this.log.info(
393
+ `Matter: "${a.displayName}" is published${
394
+ this.entries.some(e => e.uuid === a.UUID && e.meter)
395
+ ? ' with energy'
396
+ : ''
397
+ }.`,
398
+ ),
399
+ )
400
+ } catch (err) {
401
+ // Thrown while the bridge's Matter server is still starting: try again shortly
402
+ if (attempt < 6) {
403
+ this.log.debug(`Matter not ready yet (${err.message}); retrying in 10 s`)
404
+ const t = setTimeout(() => this.register(accessories, attempt + 1), 10000)
405
+ if (t.unref) {
406
+ t.unref()
407
+ }
408
+ } else {
409
+ this.log.warn(`Could not publish energy over Matter: ${err.message}. Restart Homebridge to try again.`)
410
+ }
411
+ }
412
+ }
413
+
414
+ async update(entry, cluster, attributes) {
415
+ if (!this.registered) {
416
+ return
417
+ }
418
+ try {
419
+ await this.api.matter.updateAccessoryState(entry.uuid, cluster, attributes, PART_ID)
420
+ } catch (err) {
421
+ this.log.debug(`${entry.device.name}: energy update failed (${err.message})`)
422
+ }
423
+ }
424
+
425
+ pushPower(entry, snap) {
426
+ if (snap) {
427
+ const mW = Math.round(snap.watts * 1000)
428
+ if (mW !== entry.lastPower) {
429
+ entry.lastPower = mW
430
+ this.update(entry, 'electricalPowerMeasurement', { activePower: mW })
431
+ }
432
+ }
433
+ const on = this.isOn(entry)
434
+ if (on !== entry.lastOn) {
435
+ entry.lastOn = on
436
+ this.update(entry, 'onOff', { onOff: on })
437
+ }
438
+ }
439
+
440
+ pushEnergy(entry) {
441
+ this.update(entry, 'electricalEnergyMeasurement', {
442
+ cumulativeEnergyImported: {
443
+ energy: Math.round(entry.meter.totalMWh),
444
+ startTimestamp: Math.floor(entry.meter.since / 1000),
445
+ endTimestamp: Math.floor(Date.now() / 1000),
446
+ },
447
+ })
448
+ }
449
+
450
+ snapBack(entry) {
451
+ // Handlers must not update state themselves; put the real value back just after.
452
+ const t = setTimeout(() => {
453
+ entry.lastOn = null
454
+ this.pushPower(entry, entry.meter
455
+ ? entry.meter.snapshot()
456
+ : null)
457
+ }, 800)
458
+ if (t.unref) {
459
+ t.unref()
460
+ }
461
+ }
462
+
463
+ /** For the dashboard: id -> estimate */
464
+ status() {
465
+ const out = {}
466
+ for (const e of this.entries) {
467
+ if (e.meter) {
468
+ out[e.device.id] = e.meter.snapshot()
469
+ }
470
+ }
471
+ return out
472
+ }
473
+
474
+ shutdown() {
475
+ this.timers.forEach(t => clearInterval(t))
476
+ this.entries
477
+ .filter(e => e.meter)
478
+ .forEach((e) => {
479
+ e.meter.tick(null)
480
+ e.meter.save()
481
+ })
482
+ }
483
+ }
484
+
485
+ export { DEFAULT_WATTS, EnergyMeter, MatterEnergyPublisher, MIN_HB, normaliseEnergyConfig, powerState }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 simont77
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.