homebridge-brother-printer 0.0.0-stage → 0.1.4
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/CHANGELOG.md +27 -0
- package/LICENSE +21 -0
- package/README.md +140 -2
- package/bin/brother-printer-probe.js +27 -0
- package/config.schema.json +139 -0
- package/index.js +8 -0
- package/lib/accessory.js +320 -0
- package/lib/decode.js +146 -0
- package/lib/platform.js +87 -0
- package/lib/settings.js +6 -0
- package/lib/snmp.js +95 -0
- package/package.json +53 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.4 - 2026-11-03
|
|
4
|
+
|
|
5
|
+
First public release.
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
- Printing state as an occupancy sensor, from `hrPrinterStatus` and the printer's display.
|
|
9
|
+
- Printer Problem contact sensor that opens on a jam, open cover, empty tray or other error.
|
|
10
|
+
Apple Home doesn't show Status Fault on occupancy sensors.
|
|
11
|
+
- Toner % as a battery level with a configurable low threshold, read from Brother's own
|
|
12
|
+
SNMP records rather than the standard Printer MIB.
|
|
13
|
+
- No Response in the Home app while the printer can't be reached, recovering when it answers.
|
|
14
|
+
- Optional toner tile (humidity sensor) and optional drum-life battery.
|
|
15
|
+
- Page count as a custom characteristic.
|
|
16
|
+
- `brother-printer-probe` command to check what a printer reports.
|
|
17
|
+
- Settings screen, tests and linting.
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
- Drum life is off by default: Home shows one battery per accessory and was showing the
|
|
21
|
+
drum instead of the toner. The drum is still read and warned about in the log.
|
|
22
|
+
- Settings screen no longer reports a validation error for the blank printer row it adds.
|
|
23
|
+
Rows without a host are ignored, with a warning only if they were filled in.
|
|
24
|
+
|
|
25
|
+
## 0.1.3 - 2026-11-03
|
|
26
|
+
|
|
27
|
+
Private pre-releases (0.1.0 to 0.1.3), tested on an MFC-L2750DW.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Manuel Zamfir
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,141 @@
|
|
|
1
|
-
#
|
|
1
|
+
# homebridge-brother-printer
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/homebridge-brother-printer)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
Shows a Brother laser printer in HomeKit: whether it's printing, whether it needs
|
|
7
|
+
attention, and how much toner is left. Everything is read locally over SNMP, with no
|
|
8
|
+
cloud or Brother account.
|
|
9
|
+
|
|
10
|
+
Generic AirPrint/IPP plugins can't show real toner levels on many Brother printers,
|
|
11
|
+
because the standard Printer MIB only reports "some remaining". Brother's own SNMP
|
|
12
|
+
records carry the actual percentages shown on the printer's web page, and this plugin
|
|
13
|
+
reads those.
|
|
14
|
+
|
|
15
|
+
Each printer gets these sensors:
|
|
16
|
+
|
|
17
|
+
- **Printer** (occupancy sensor): Detected while a job prints. Use it in automations.
|
|
18
|
+
- **Printer Problem** (contact sensor): Open on a jam, open cover, empty tray or other
|
|
19
|
+
error. Turn on notifications for it in the Home app.
|
|
20
|
+
- **Toner** (battery level on the Printer accessory): the toner %, with Home's native
|
|
21
|
+
low-battery alert at or below your threshold.
|
|
22
|
+
- **Printer Toner** (optional humidity sensor): the toner % as a number on its own tile.
|
|
23
|
+
|
|
24
|
+
While the printer can't be reached, all of them show No Response.
|
|
25
|
+
|
|
26
|
+
## Requirements
|
|
27
|
+
|
|
28
|
+
- A Brother laser printer with SNMP. Tested on an **MFC-L2750DW**. Other mono lasers from
|
|
29
|
+
the same generation (HL-L23xx, DCP-L25xx, MFC-L27xx) use the same records and should
|
|
30
|
+
work; reports for other models are welcome.
|
|
31
|
+
- SNMP turned on in the printer's web page: **Network → Protocol → SNMP** (v1/v2c,
|
|
32
|
+
read-only is enough). The default community is `public`.
|
|
33
|
+
- A fixed address for the printer: reserve its IP in your router, or use its mDNS
|
|
34
|
+
hostname (for example `brn3c2af4919dfc.local`).
|
|
35
|
+
- Homebridge 1.6 or later (including 2.x), Node.js 18, 20, 22 or 24.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
Search for **Brother Printer** in the Homebridge UI's Plugins tab, or run:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npm install -g homebridge-brother-printer
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Running it as a child bridge is recommended.
|
|
46
|
+
|
|
47
|
+
## Configuration
|
|
48
|
+
|
|
49
|
+
Set it up in the plugin's settings screen, or in `config.json`:
|
|
50
|
+
|
|
51
|
+
```json
|
|
52
|
+
{
|
|
53
|
+
"platform": "BrotherPrinter",
|
|
54
|
+
"printers": [
|
|
55
|
+
{
|
|
56
|
+
"name": "Printer",
|
|
57
|
+
"host": "10.0.4.150"
|
|
58
|
+
}
|
|
59
|
+
]
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
| Option | Default | Description |
|
|
64
|
+
|---|---|---|
|
|
65
|
+
| `name` | `Printer` | Accessory name. Must be unique per printer. |
|
|
66
|
+
| `host` | | Printer IP address or hostname. Printers without one are ignored. |
|
|
67
|
+
| `community` | `public` | SNMP community string. |
|
|
68
|
+
| `port` | `161` | SNMP port. |
|
|
69
|
+
| `pollInterval` | `60` | Seconds between polls (10–3600). |
|
|
70
|
+
| `lowTonerThreshold` | `10` | Toner % at or below which Home shows it as low. |
|
|
71
|
+
| `faultSensor` | `true` | Add the Printer Problem contact sensor. |
|
|
72
|
+
| `tonerTile` | `false` | Add a humidity sensor showing toner % on its own tile. It also counts in Home's climate summary. |
|
|
73
|
+
| `showDrum` | `false` | Add drum life as a second battery. See below. |
|
|
74
|
+
| `lowDrumThreshold` | `10` | Drum % at or below which Home shows it as low. |
|
|
75
|
+
| `offlineAfter` | `3` | Failed polls in a row before the printer shows No Response. |
|
|
76
|
+
| `debug` | `false` | Log every poll at info level. |
|
|
77
|
+
|
|
78
|
+
## What the Home app shows
|
|
79
|
+
|
|
80
|
+
HomeKit has no printer accessory type, so the plugin uses the closest sensors and Home
|
|
81
|
+
words them its own way:
|
|
82
|
+
|
|
83
|
+
- The printing sensor reads **Detected** / **Not Detected**.
|
|
84
|
+
- Low toner is announced as **"battery is low"**. For a clearer message, add a Home
|
|
85
|
+
automation on that trigger that sends your own notification.
|
|
86
|
+
- Home shows only one battery per accessory. With `showDrum` on, it may show the drum
|
|
87
|
+
instead of the toner, which is why the drum is off by default. It's still read, and the
|
|
88
|
+
plugin logs a warning when it nears end of life. Apps like Eve show both.
|
|
89
|
+
- The page count is a custom characteristic, visible in Eve, Controller and the Homebridge
|
|
90
|
+
UI, not in Apple Home.
|
|
91
|
+
|
|
92
|
+
## Going offline
|
|
93
|
+
|
|
94
|
+
The time before a printer shows No Response is about
|
|
95
|
+
`offlineAfter` × (`pollInterval` + 10 s), where 10 s is the SNMP timeout. With the
|
|
96
|
+
defaults that's about 3.5 minutes; `pollInterval: 30` with `offlineAfter: 1` brings it to
|
|
97
|
+
about 40 s. With `offlineAfter: 1`, a single lost packet can make it flash No Response for
|
|
98
|
+
one poll.
|
|
99
|
+
|
|
100
|
+
Brother lasers normally still answer SNMP in Sleep and Deep Sleep.
|
|
101
|
+
|
|
102
|
+
## Checking what your printer reports
|
|
103
|
+
|
|
104
|
+
The package includes a command that prints what the plugin reads:
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
npx -p homebridge-brother-printer brother-printer-probe 10.0.4.150
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Compare `tonerPercent` with **Remaining Life** on the printer's web page. If it doesn't
|
|
111
|
+
match, or values are `null`, please open an issue with the probe output and your printer
|
|
112
|
+
model.
|
|
113
|
+
|
|
114
|
+
## Troubleshooting
|
|
115
|
+
|
|
116
|
+
- **"Can't reach … Request timed out"**: SNMP is off on the printer, the address is wrong,
|
|
117
|
+
or a firewall blocks UDP port 161. Test from the Homebridge machine with
|
|
118
|
+
`snmpget -v2c -c public <printer-ip> 1.3.6.1.2.1.1.1.0` (from the `snmp` package).
|
|
119
|
+
- **Toner shows 0% with a full cartridge**: some non-genuine cartridges aren't recognised
|
|
120
|
+
by the printer, which then reports no level.
|
|
121
|
+
|
|
122
|
+
## How it works
|
|
123
|
+
|
|
124
|
+
Brother printers expose maintenance data as packed records in their private MIB
|
|
125
|
+
(`1.3.6.1.4.1.2435.2.3.9.4.2.1.5.5.8`, `.5.10` and `.5.11`). Each record is a one-byte
|
|
126
|
+
code, `0x01`, a length byte and a big-endian value. The codes this plugin uses:
|
|
127
|
+
|
|
128
|
+
| Code | Meaning |
|
|
129
|
+
|---|---|
|
|
130
|
+
| `0x81` | Toner remaining, % |
|
|
131
|
+
| `0x41` | Drum life remaining, hundredths of a % |
|
|
132
|
+
| `0x11` | Pages printed on this drum |
|
|
133
|
+
| `0x82` (next care) | Drum pages remaining |
|
|
134
|
+
| `0x00` (counter) | Total pages printed |
|
|
135
|
+
|
|
136
|
+
Printing and problem state come from the standard Host Resources MIB (`hrPrinterStatus`,
|
|
137
|
+
`hrPrinterDetectedErrorState`) plus the text on the printer's display.
|
|
138
|
+
|
|
139
|
+
## License
|
|
140
|
+
|
|
141
|
+
MIT
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/*
|
|
5
|
+
* Quick check from the command line:
|
|
6
|
+
* npx brother-printer-probe 10.0.4.150 [community]
|
|
7
|
+
* Prints what the plugin would read from the printer.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const { query } = require('../lib/snmp');
|
|
11
|
+
|
|
12
|
+
const [target, community = 'public'] = process.argv.slice(2);
|
|
13
|
+
const [host, port] = (target || '').split(':');
|
|
14
|
+
if (!host) {
|
|
15
|
+
console.error('Usage: brother-printer-probe <printer-ip-or-hostname[:port]> [community]');
|
|
16
|
+
process.exit(2);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
query({ host, port: Number(port) || 161, community })
|
|
20
|
+
.then((d) => {
|
|
21
|
+
console.log(JSON.stringify(d, null, 2));
|
|
22
|
+
})
|
|
23
|
+
.catch((err) => {
|
|
24
|
+
console.error(`Couldn't read ${host}: ${err.message}`);
|
|
25
|
+
console.error('Check the address, and that SNMP is enabled on the printer (Network > Protocol).');
|
|
26
|
+
process.exit(1);
|
|
27
|
+
});
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
{
|
|
2
|
+
"pluginAlias": "BrotherPrinter",
|
|
3
|
+
"pluginType": "platform",
|
|
4
|
+
"singular": true,
|
|
5
|
+
"headerDisplay": "Shows a Brother laser printer's printing state, toner and drum life in HomeKit. SNMP must be on in the printer's web page (Network > Protocol).",
|
|
6
|
+
"schema": {
|
|
7
|
+
"type": "object",
|
|
8
|
+
"properties": {
|
|
9
|
+
"name": {
|
|
10
|
+
"title": "Platform name",
|
|
11
|
+
"type": "string",
|
|
12
|
+
"default": "Brother Printer"
|
|
13
|
+
},
|
|
14
|
+
"printers": {
|
|
15
|
+
"title": "Printers",
|
|
16
|
+
"type": "array",
|
|
17
|
+
"items": {
|
|
18
|
+
"type": "object",
|
|
19
|
+
"properties": {
|
|
20
|
+
"name": {
|
|
21
|
+
"title": "Name",
|
|
22
|
+
"type": "string",
|
|
23
|
+
"default": "Printer"
|
|
24
|
+
},
|
|
25
|
+
"host": {
|
|
26
|
+
"title": "IP address or hostname",
|
|
27
|
+
"type": "string",
|
|
28
|
+
"placeholder": "10.0.4.150",
|
|
29
|
+
"description": "Required. Printers without an address are ignored."
|
|
30
|
+
},
|
|
31
|
+
"community": {
|
|
32
|
+
"title": "SNMP community",
|
|
33
|
+
"type": "string",
|
|
34
|
+
"default": "public"
|
|
35
|
+
},
|
|
36
|
+
"port": {
|
|
37
|
+
"title": "SNMP port",
|
|
38
|
+
"type": "integer",
|
|
39
|
+
"default": 161,
|
|
40
|
+
"minimum": 1,
|
|
41
|
+
"maximum": 65535
|
|
42
|
+
},
|
|
43
|
+
"pollInterval": {
|
|
44
|
+
"title": "Poll every (seconds)",
|
|
45
|
+
"type": "integer",
|
|
46
|
+
"default": 60,
|
|
47
|
+
"minimum": 10,
|
|
48
|
+
"maximum": 3600
|
|
49
|
+
},
|
|
50
|
+
"lowTonerThreshold": {
|
|
51
|
+
"title": "Toner low at (%)",
|
|
52
|
+
"type": "integer",
|
|
53
|
+
"default": 10,
|
|
54
|
+
"minimum": 0,
|
|
55
|
+
"maximum": 100
|
|
56
|
+
},
|
|
57
|
+
"showDrum": {
|
|
58
|
+
"title": "Show drum life as a second battery",
|
|
59
|
+
"type": "boolean",
|
|
60
|
+
"default": false,
|
|
61
|
+
"description": "Apple's Home app shows only one battery per accessory, and may pick the drum over the toner. Leave off unless you use Eve or another app that shows both."
|
|
62
|
+
},
|
|
63
|
+
"lowDrumThreshold": {
|
|
64
|
+
"title": "Drum low at (%)",
|
|
65
|
+
"type": "integer",
|
|
66
|
+
"default": 10,
|
|
67
|
+
"minimum": 0,
|
|
68
|
+
"maximum": 100,
|
|
69
|
+
"condition": {
|
|
70
|
+
"functionBody": "return model.printers[arrayIndices].showDrum === true;"
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
"tonerTile": {
|
|
74
|
+
"title": "Show toner % on its own tile",
|
|
75
|
+
"description": "Adds a humidity sensor whose value is the toner level, so it's visible on the Home tile. It also appears in Home's climate summary.",
|
|
76
|
+
"type": "boolean",
|
|
77
|
+
"default": false
|
|
78
|
+
},
|
|
79
|
+
"faultSensor": {
|
|
80
|
+
"title": "Problem sensor",
|
|
81
|
+
"description": "Adds a contact sensor that opens on a jam, open cover, empty tray or other error, so Home can show and notify it.",
|
|
82
|
+
"type": "boolean",
|
|
83
|
+
"default": true
|
|
84
|
+
},
|
|
85
|
+
"offlineAfter": {
|
|
86
|
+
"title": "Mark offline after (failed polls)",
|
|
87
|
+
"type": "integer",
|
|
88
|
+
"default": 3,
|
|
89
|
+
"minimum": 1,
|
|
90
|
+
"maximum": 20
|
|
91
|
+
},
|
|
92
|
+
"debug": {
|
|
93
|
+
"title": "Log every poll",
|
|
94
|
+
"type": "boolean",
|
|
95
|
+
"default": false
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
"layout": [
|
|
103
|
+
"name",
|
|
104
|
+
{
|
|
105
|
+
"key": "printers",
|
|
106
|
+
"type": "array",
|
|
107
|
+
"orderable": false,
|
|
108
|
+
"buttonText": "Add printer",
|
|
109
|
+
"items": [
|
|
110
|
+
"printers[].name",
|
|
111
|
+
"printers[].host",
|
|
112
|
+
{
|
|
113
|
+
"type": "fieldset",
|
|
114
|
+
"title": "Sensors",
|
|
115
|
+
"expandable": true,
|
|
116
|
+
"items": [
|
|
117
|
+
"printers[].lowTonerThreshold",
|
|
118
|
+
"printers[].showDrum",
|
|
119
|
+
"printers[].lowDrumThreshold",
|
|
120
|
+
"printers[].tonerTile",
|
|
121
|
+
"printers[].faultSensor"
|
|
122
|
+
]
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
"type": "fieldset",
|
|
126
|
+
"title": "Advanced",
|
|
127
|
+
"expandable": true,
|
|
128
|
+
"items": [
|
|
129
|
+
"printers[].community",
|
|
130
|
+
"printers[].port",
|
|
131
|
+
"printers[].pollInterval",
|
|
132
|
+
"printers[].offlineAfter",
|
|
133
|
+
"printers[].debug"
|
|
134
|
+
]
|
|
135
|
+
}
|
|
136
|
+
]
|
|
137
|
+
}
|
|
138
|
+
]
|
|
139
|
+
}
|
package/index.js
ADDED
package/lib/accessory.js
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { query } = require('./snmp');
|
|
4
|
+
const { version } = require('../package.json');
|
|
5
|
+
|
|
6
|
+
const PAGES_UUID = 'B0E5A1C2-7D3E-4F1A-9C6B-2E8D4F7A1B30';
|
|
7
|
+
let PagesPrinted;
|
|
8
|
+
|
|
9
|
+
function pagesCharacteristic(hap) {
|
|
10
|
+
if (PagesPrinted) { return PagesPrinted; }
|
|
11
|
+
const { Characteristic, Formats, Perms } = hap;
|
|
12
|
+
PagesPrinted = class extends Characteristic {
|
|
13
|
+
constructor() {
|
|
14
|
+
super('Pages Printed', PAGES_UUID, {
|
|
15
|
+
format: Formats.UINT32,
|
|
16
|
+
perms: [Perms.PAIRED_READ, Perms.NOTIFY],
|
|
17
|
+
minValue: 0,
|
|
18
|
+
maxValue: 4294967295,
|
|
19
|
+
minStep: 1,
|
|
20
|
+
});
|
|
21
|
+
this.value = this.getDefaultValue();
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
PagesPrinted.UUID = PAGES_UUID;
|
|
25
|
+
return PagesPrinted;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const clamp = (v) => Math.max(0, Math.min(100, Math.round(v)));
|
|
29
|
+
|
|
30
|
+
class PrinterAccessory {
|
|
31
|
+
constructor(platform, accessory, config) {
|
|
32
|
+
this.platform = platform;
|
|
33
|
+
this.log = platform.log;
|
|
34
|
+
this.api = platform.api;
|
|
35
|
+
this.hap = platform.api.hap;
|
|
36
|
+
this.accessory = accessory;
|
|
37
|
+
this.name = config.name;
|
|
38
|
+
|
|
39
|
+
this.options = {
|
|
40
|
+
host: config.host,
|
|
41
|
+
port: Number(config.port) || 161,
|
|
42
|
+
community: config.community || 'public',
|
|
43
|
+
timeout: 5000,
|
|
44
|
+
retries: 1,
|
|
45
|
+
};
|
|
46
|
+
this.interval = Math.max(10, Number(config.pollInterval) || 60) * 1000;
|
|
47
|
+
this.lowToner = clamp(config.lowTonerThreshold ?? 10);
|
|
48
|
+
this.lowDrum = clamp(config.lowDrumThreshold ?? 10);
|
|
49
|
+
this.showDrum = config.showDrum === true;
|
|
50
|
+
this.tonerTile = config.tonerTile === true;
|
|
51
|
+
this.faultSensor = config.faultSensor !== false;
|
|
52
|
+
this.offlineAfter = Math.max(1, Number(config.offlineAfter) || 3);
|
|
53
|
+
this.debug = config.debug === true;
|
|
54
|
+
|
|
55
|
+
this.failures = 0;
|
|
56
|
+
this.online = true;
|
|
57
|
+
this.last = {};
|
|
58
|
+
this.timer = null;
|
|
59
|
+
this.stopped = false;
|
|
60
|
+
|
|
61
|
+
this.buildServices();
|
|
62
|
+
this.guardReads();
|
|
63
|
+
this.poll();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/* ------------------------------------------------------------ services */
|
|
67
|
+
|
|
68
|
+
buildServices() {
|
|
69
|
+
const { Service, Characteristic: C } = this.hap;
|
|
70
|
+
const acc = this.accessory;
|
|
71
|
+
|
|
72
|
+
acc.getService(Service.AccessoryInformation)
|
|
73
|
+
.setCharacteristic(C.Manufacturer, 'Brother')
|
|
74
|
+
.setCharacteristic(C.Model, acc.context.model || 'Brother printer')
|
|
75
|
+
.setCharacteristic(C.SerialNumber, acc.context.serial || this.options.host)
|
|
76
|
+
.setCharacteristic(C.FirmwareRevision, version);
|
|
77
|
+
|
|
78
|
+
// Printing state: the tile people see in the Home app
|
|
79
|
+
this.occupancy = acc.getService(Service.OccupancySensor)
|
|
80
|
+
|| acc.addService(Service.OccupancySensor, this.name);
|
|
81
|
+
this.label(this.occupancy, this.name);
|
|
82
|
+
this.occupancy.setPrimaryService(true);
|
|
83
|
+
for (const ch of [C.StatusActive, C.StatusFault]) {
|
|
84
|
+
if (!this.occupancy.testCharacteristic(ch)) { this.occupancy.addOptionalCharacteristic(ch); }
|
|
85
|
+
this.occupancy.getCharacteristic(ch);
|
|
86
|
+
}
|
|
87
|
+
this.occupancy.getCharacteristic(C.StatusActive).updateValue(true);
|
|
88
|
+
const Pages = pagesCharacteristic(this.hap);
|
|
89
|
+
if (!this.occupancy.testCharacteristic(Pages)) { this.occupancy.addCharacteristic(Pages); }
|
|
90
|
+
this.pages = this.occupancy.getCharacteristic(Pages);
|
|
91
|
+
|
|
92
|
+
// Toner and drum as batteries so Home raises native "low" alerts
|
|
93
|
+
this.toner = this.battery('toner', `${this.name} Toner`);
|
|
94
|
+
this.occupancy.addLinkedService(this.toner);
|
|
95
|
+
|
|
96
|
+
if (this.showDrum) {
|
|
97
|
+
this.drum = this.battery('drum', `${this.name} Drum`);
|
|
98
|
+
this.occupancy.addLinkedService(this.drum);
|
|
99
|
+
} else {
|
|
100
|
+
this.removeSubtype(Service.Battery, 'drum');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Home doesn't surface StatusFault on occupancy sensors, so problems
|
|
104
|
+
// (jam, cover open, no paper...) also open a contact sensor.
|
|
105
|
+
if (this.faultSensor) {
|
|
106
|
+
this.problem = acc.getServiceById(Service.ContactSensor, 'problem')
|
|
107
|
+
|| acc.addService(Service.ContactSensor, `${this.name} Problem`, 'problem');
|
|
108
|
+
this.label(this.problem, `${this.name} Problem`);
|
|
109
|
+
if (!this.problem.testCharacteristic(C.StatusActive)) { this.problem.addOptionalCharacteristic(C.StatusActive); }
|
|
110
|
+
this.problem.getCharacteristic(C.StatusActive).updateValue(true);
|
|
111
|
+
this.occupancy.addLinkedService(this.problem);
|
|
112
|
+
} else {
|
|
113
|
+
this.removeSubtype(Service.ContactSensor, 'problem');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (this.tonerTile) {
|
|
117
|
+
this.tile = acc.getServiceById(Service.HumiditySensor, 'tonerTile')
|
|
118
|
+
|| acc.addService(Service.HumiditySensor, `${this.name} Toner`, 'tonerTile');
|
|
119
|
+
this.label(this.tile, `${this.name} Toner`);
|
|
120
|
+
if (!this.tile.testCharacteristic(C.StatusActive)) { this.tile.addOptionalCharacteristic(C.StatusActive); }
|
|
121
|
+
this.tile.getCharacteristic(C.StatusActive);
|
|
122
|
+
} else {
|
|
123
|
+
this.removeSubtype(Service.HumiditySensor, 'tonerTile');
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Home ignores StatusActive on sensors. It shows "No Response" only when a
|
|
129
|
+
* read fails, so while the printer is offline the state reads fail too.
|
|
130
|
+
*/
|
|
131
|
+
guardReads() {
|
|
132
|
+
const C = this.hap.Characteristic;
|
|
133
|
+
const pairs = [
|
|
134
|
+
[this.occupancy, C.OccupancyDetected],
|
|
135
|
+
[this.occupancy, C.StatusFault],
|
|
136
|
+
[this.toner, C.BatteryLevel],
|
|
137
|
+
[this.toner, C.StatusLowBattery],
|
|
138
|
+
[this.drum, C.BatteryLevel],
|
|
139
|
+
[this.drum, C.StatusLowBattery],
|
|
140
|
+
[this.problem, C.ContactSensorState],
|
|
141
|
+
[this.tile, C.CurrentRelativeHumidity],
|
|
142
|
+
];
|
|
143
|
+
this.guarded = pairs.filter(([svc]) => svc).map(([svc, type]) => svc.getCharacteristic(type));
|
|
144
|
+
for (const ch of this.guarded) {
|
|
145
|
+
ch.onGet(() => {
|
|
146
|
+
if (!this.online) { throw this.noResponse(); }
|
|
147
|
+
return ch.value;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
noResponse() {
|
|
153
|
+
const { HapStatusError, HAPStatus } = this.hap;
|
|
154
|
+
return new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
battery(subtype, name) {
|
|
158
|
+
const { Service, Characteristic: C } = this.hap;
|
|
159
|
+
const svc = this.accessory.getServiceById(Service.Battery, subtype)
|
|
160
|
+
|| this.accessory.addService(Service.Battery, name, subtype);
|
|
161
|
+
this.label(svc, name);
|
|
162
|
+
svc.setCharacteristic(C.ChargingState, C.ChargingState.NOT_CHARGEABLE);
|
|
163
|
+
return svc;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
label(svc, name) {
|
|
167
|
+
const C = this.hap.Characteristic;
|
|
168
|
+
svc.setCharacteristic(C.Name, name);
|
|
169
|
+
if (!svc.testCharacteristic(C.ConfiguredName)) { svc.addOptionalCharacteristic(C.ConfiguredName); }
|
|
170
|
+
// Only seed the name; don't overwrite a name the user set in the Home app
|
|
171
|
+
const current = svc.getCharacteristic(C.ConfiguredName).value;
|
|
172
|
+
if (!current) { svc.setCharacteristic(C.ConfiguredName, name); }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
removeSubtype(type, subtype) {
|
|
176
|
+
const svc = this.accessory.getServiceById(type, subtype);
|
|
177
|
+
if (svc) { this.accessory.removeService(svc); }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/* ------------------------------------------------------------- polling */
|
|
181
|
+
|
|
182
|
+
async poll() {
|
|
183
|
+
if (this.stopped) { return; }
|
|
184
|
+
let data;
|
|
185
|
+
try {
|
|
186
|
+
data = await query(this.options);
|
|
187
|
+
} catch (err) {
|
|
188
|
+
this.failures += 1;
|
|
189
|
+
const msg = err && err.message ? err.message : String(err);
|
|
190
|
+
if (this.failures === this.offlineAfter) {
|
|
191
|
+
this.log.warn(`[${this.name}] Can't reach ${this.options.host} (${msg}). Showing it as offline.`);
|
|
192
|
+
this.setOnline(false);
|
|
193
|
+
} else if (this.debug || this.failures < this.offlineAfter) {
|
|
194
|
+
this.log.debug(`[${this.name}] Poll failed (${this.failures}/${this.offlineAfter}): ${msg}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (data) {
|
|
198
|
+
this.failures = 0;
|
|
199
|
+
try {
|
|
200
|
+
this.apply(data);
|
|
201
|
+
} catch (err) {
|
|
202
|
+
this.log.error(`[${this.name}] Couldn't update HomeKit: ${err && err.stack ? err.stack : err}`);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (!this.stopped) { this.timer = setTimeout(() => this.poll(), this.interval); }
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
stop() {
|
|
209
|
+
this.stopped = true;
|
|
210
|
+
if (this.timer) { clearTimeout(this.timer); }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
setOnline(online) {
|
|
214
|
+
const C = this.hap.Characteristic;
|
|
215
|
+
const wasOnline = this.online;
|
|
216
|
+
if (online && !wasOnline) {this.log.info(`[${this.name}] Back online.`);}
|
|
217
|
+
this.online = online;
|
|
218
|
+
if (online && !wasOnline) {
|
|
219
|
+
for (const ch of this.guarded) { ch.updateValue(ch.value); }
|
|
220
|
+
}
|
|
221
|
+
this.occupancy.updateCharacteristic(C.StatusActive, online);
|
|
222
|
+
if (this.tile) { this.tile.updateCharacteristic(C.StatusActive, online); }
|
|
223
|
+
if (this.problem) { this.problem.updateCharacteristic(C.StatusActive, online); }
|
|
224
|
+
if (!online) {
|
|
225
|
+
this.occupancy.updateCharacteristic(C.OccupancyDetected, 0);
|
|
226
|
+
// Push the failure so Home shows "No Response" without waiting for a read
|
|
227
|
+
for (const ch of this.guarded) { ch.updateValue(this.noResponse()); }
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
apply(d) {
|
|
232
|
+
const C = this.hap.Characteristic;
|
|
233
|
+
const log = (m) => (this.debug ? this.log.info(m) : this.log.debug(m));
|
|
234
|
+
|
|
235
|
+
log(`[${this.name}] ${JSON.stringify(d)}`);
|
|
236
|
+
this.setOnline(true);
|
|
237
|
+
this.updateInfo(d);
|
|
238
|
+
|
|
239
|
+
// Printing / fault
|
|
240
|
+
this.occupancy.updateCharacteristic(C.OccupancyDetected, d.printing
|
|
241
|
+
? C.OccupancyDetected.OCCUPANCY_DETECTED
|
|
242
|
+
: C.OccupancyDetected.OCCUPANCY_NOT_DETECTED);
|
|
243
|
+
this.occupancy.updateCharacteristic(C.StatusFault, d.fault
|
|
244
|
+
? C.StatusFault.GENERAL_FAULT
|
|
245
|
+
: C.StatusFault.NO_FAULT);
|
|
246
|
+
|
|
247
|
+
if (this.problem) {
|
|
248
|
+
this.problem.updateCharacteristic(C.ContactSensorState, d.fault
|
|
249
|
+
? C.ContactSensorState.CONTACT_NOT_DETECTED
|
|
250
|
+
: C.ContactSensorState.CONTACT_DETECTED);
|
|
251
|
+
}
|
|
252
|
+
if (d.fault && !this.last.fault) {
|
|
253
|
+
this.log.warn(`[${this.name}] Problem: ${d.statusText || d.faults.join(', ')}`);
|
|
254
|
+
} else if (!d.fault && this.last.fault) {
|
|
255
|
+
this.log.info(`[${this.name}] Problem cleared.`);
|
|
256
|
+
}
|
|
257
|
+
this.last.fault = d.fault;
|
|
258
|
+
|
|
259
|
+
if (d.statusText && d.statusText !== this.last.statusText) {
|
|
260
|
+
this.log.info(`[${this.name}] Status: ${d.statusText}`);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Toner
|
|
264
|
+
if (d.tonerPercent !== null) {
|
|
265
|
+
const level = clamp(d.tonerPercent);
|
|
266
|
+
this.setBattery(this.toner, level, this.lowToner);
|
|
267
|
+
if (this.tile) { this.tile.updateCharacteristic(C.CurrentRelativeHumidity, level); }
|
|
268
|
+
if (level !== this.last.toner) {
|
|
269
|
+
if (this.last.toner !== undefined || this.debug) {this.log.info(`[${this.name}] Toner ${level}%`);}
|
|
270
|
+
if (level <= this.lowToner && (this.last.toner === undefined || this.last.toner > this.lowToner)) {
|
|
271
|
+
this.log.warn(`[${this.name}] Toner is low (${level}%).`);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
this.last.toner = level;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// Drum
|
|
278
|
+
if (d.drumPercent !== null) {
|
|
279
|
+
const level = clamp(d.drumPercent);
|
|
280
|
+
if (this.drum) { this.setBattery(this.drum, level, this.lowDrum); }
|
|
281
|
+
if (level <= this.lowDrum && (this.last.drum === undefined || this.last.drum > this.lowDrum)) {
|
|
282
|
+
this.log.warn(`[${this.name}] Drum is near end of life (${level}%, ${d.drumPagesRemaining ?? '?'} pages left).`);
|
|
283
|
+
}
|
|
284
|
+
this.last.drum = level;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
if (d.totalPages !== null) { this.pages.updateValue(d.totalPages); }
|
|
288
|
+
this.last.statusText = d.statusText;
|
|
289
|
+
|
|
290
|
+
if (this.last.summary === undefined) {
|
|
291
|
+
this.log.info(`[${this.name}] Connected to ${d.model || 'printer'}: toner ${d.tonerPercent ?? '?'}%, `
|
|
292
|
+
+ `drum ${d.drumPercent ?? '?'}%, ${d.totalPages ?? '?'} pages, status "${d.statusText || 'unknown'}".`);
|
|
293
|
+
this.last.summary = true;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
setBattery(svc, level, threshold) {
|
|
298
|
+
const C = this.hap.Characteristic;
|
|
299
|
+
svc.updateCharacteristic(C.BatteryLevel, level);
|
|
300
|
+
svc.updateCharacteristic(C.StatusLowBattery, level <= threshold
|
|
301
|
+
? C.StatusLowBattery.BATTERY_LEVEL_LOW
|
|
302
|
+
: C.StatusLowBattery.BATTERY_LEVEL_NORMAL);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
updateInfo(d) {
|
|
306
|
+
const { Service, Characteristic: C } = this.hap;
|
|
307
|
+
const ctx = this.accessory.context;
|
|
308
|
+
let changed = false;
|
|
309
|
+
const model = d.model ? d.model.replace(/^Brother\s+/i, '') : null;
|
|
310
|
+
if (model && model !== ctx.model) { ctx.model = model; changed = true; }
|
|
311
|
+
if (d.serial && d.serial !== ctx.serial) { ctx.serial = d.serial; changed = true; }
|
|
312
|
+
if (!changed) { return; }
|
|
313
|
+
this.accessory.getService(Service.AccessoryInformation)
|
|
314
|
+
.updateCharacteristic(C.Model, ctx.model || 'Brother printer')
|
|
315
|
+
.updateCharacteristic(C.SerialNumber, ctx.serial || this.options.host);
|
|
316
|
+
this.api.updatePlatformAccessories([this.accessory]);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
module.exports = { PrinterAccessory };
|
package/lib/decode.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Brother printers pack maintenance data into OctetString "blobs" made of
|
|
5
|
+
* records: [code(1)] [0x01] [length(1)] [value(length bytes, big-endian)]
|
|
6
|
+
* terminated by 0xFF.
|
|
7
|
+
*
|
|
8
|
+
* Record codes below were verified against an MFC-L2750DW (mono laser) by
|
|
9
|
+
* comparing SNMP output with the printer's own "Remaining Life" web page.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const MAINTENANCE = {
|
|
13
|
+
0x11: { key: 'drumPagesUsed', scale: 1 },
|
|
14
|
+
0x41: { key: 'drumPercent', scale: 0.01 },
|
|
15
|
+
0x63: { key: 'drumStatus', scale: 1 },
|
|
16
|
+
0x31: { key: 'tonerStatus', scale: 1 },
|
|
17
|
+
0x6f: { key: 'tonerPercentFine', scale: 0.01 },
|
|
18
|
+
0x81: { key: 'tonerPercent', scale: 1 },
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const COUNTERS = {
|
|
22
|
+
0x00: { key: 'totalPages', scale: 1 },
|
|
23
|
+
0x01: { key: 'monoPages', scale: 1 },
|
|
24
|
+
0x06: { key: 'duplexPages', scale: 1 },
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const NEXT_CARE = {
|
|
28
|
+
0x82: { key: 'drumPagesRemaining', scale: 1 },
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
function toBuffer(value) {
|
|
32
|
+
if (value === null || value === undefined) { return null; }
|
|
33
|
+
if (Buffer.isBuffer(value)) { return value; }
|
|
34
|
+
if (typeof value === 'string') {
|
|
35
|
+
const hex = value.replace(/[^0-9a-f]/gi, '');
|
|
36
|
+
if (hex.length && hex.length % 2 === 0) { return Buffer.from(hex, 'hex'); }
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Parse a Brother record blob into [{ code, value }] */
|
|
42
|
+
function parseRecords(input) {
|
|
43
|
+
const buf = toBuffer(input);
|
|
44
|
+
const records = [];
|
|
45
|
+
if (!buf) { return records; }
|
|
46
|
+
|
|
47
|
+
let i = 0;
|
|
48
|
+
while (i < buf.length) {
|
|
49
|
+
const code = buf[i];
|
|
50
|
+
if (code === 0xff) { break; }
|
|
51
|
+
if (i + 3 > buf.length) { break; }
|
|
52
|
+
const len = buf[i + 2];
|
|
53
|
+
const start = i + 3;
|
|
54
|
+
const end = start + len;
|
|
55
|
+
if (end > buf.length || len === 0 || len > 6) { break; }
|
|
56
|
+
|
|
57
|
+
let value = 0;
|
|
58
|
+
for (let j = start; j < end; j++) { value = value * 256 + buf[j]; }
|
|
59
|
+
records.push({ code, value });
|
|
60
|
+
i = end;
|
|
61
|
+
}
|
|
62
|
+
return records;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function decodeWith(map, input) {
|
|
66
|
+
const out = {};
|
|
67
|
+
const unknown = {};
|
|
68
|
+
for (const { code, value } of parseRecords(input)) {
|
|
69
|
+
const def = map[code];
|
|
70
|
+
if (def) {
|
|
71
|
+
out[def.key] = def.scale === 1 ? value : Math.round(value * def.scale * 100) / 100;
|
|
72
|
+
} else {
|
|
73
|
+
unknown[`0x${code.toString(16).padStart(2, '0')}`] = value;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (Object.keys(unknown).length) { out.unknown = unknown; }
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const decodeMaintenance = (input) => decodeWith(MAINTENANCE, input);
|
|
81
|
+
const decodeCounters = (input) => decodeWith(COUNTERS, input);
|
|
82
|
+
const decodeNextCare = (input) => decodeWith(NEXT_CARE, input);
|
|
83
|
+
|
|
84
|
+
/** Decode an SNMP OctetString that holds ASCII text */
|
|
85
|
+
function decodeText(input) {
|
|
86
|
+
const buf = toBuffer(input);
|
|
87
|
+
if (!buf) { return typeof input === 'string' ? input.trim() : ''; }
|
|
88
|
+
// eslint-disable-next-line no-control-regex
|
|
89
|
+
return buf.toString('latin1').replace(/[\x00-\x1f]+/g, ' ').trim();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** hrPrinterDetectedErrorState bit names (RFC 3805 / RFC 2790) */
|
|
93
|
+
const ERROR_BITS = [
|
|
94
|
+
'lowPaper', 'noPaper', 'lowToner', 'noToner',
|
|
95
|
+
'doorOpen', 'jammed', 'offline', 'serviceRequested',
|
|
96
|
+
'inputTrayMissing', 'outputTrayMissing', 'markerSupplyMissing', 'outputNearFull',
|
|
97
|
+
'outputFull', 'inputTrayEmpty', 'overduePreventMaint',
|
|
98
|
+
];
|
|
99
|
+
|
|
100
|
+
function decodeErrorState(input) {
|
|
101
|
+
const buf = toBuffer(input);
|
|
102
|
+
const errors = [];
|
|
103
|
+
if (!buf) { return errors; }
|
|
104
|
+
for (let bit = 0; bit < ERROR_BITS.length; bit++) {
|
|
105
|
+
const byte = buf[bit >> 3];
|
|
106
|
+
if (byte === undefined) { break; }
|
|
107
|
+
if (byte & (0x80 >> (bit & 7))) { errors.push(ERROR_BITS[bit]); }
|
|
108
|
+
}
|
|
109
|
+
return errors;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Errors that stop the printer and deserve a HomeKit fault badge */
|
|
113
|
+
const FAULT_ERRORS = new Set([
|
|
114
|
+
'noPaper', 'noToner', 'doorOpen', 'jammed', 'serviceRequested',
|
|
115
|
+
'inputTrayMissing', 'outputTrayMissing', 'markerSupplyMissing', 'outputFull',
|
|
116
|
+
]);
|
|
117
|
+
|
|
118
|
+
const FAULT_TEXT = /jam|cover is open|open|no paper|paper empty|replace|no toner|toner end|drum end|drum stop|error|call service|unable|cannot|no tray|size mismatch|out of memory/i;
|
|
119
|
+
const WARNING_TEXT = /\blow\b|end soon|soon/i;
|
|
120
|
+
const PRINTING_TEXT = /printing|receiving|copying/i;
|
|
121
|
+
|
|
122
|
+
/** hrPrinterStatus: 1 other, 2 unknown, 3 idle, 4 printing, 5 warmup */
|
|
123
|
+
function summarizeStatus({ statusText = '', printerStatus = null, errors = [] }) {
|
|
124
|
+
const text = statusText || '';
|
|
125
|
+
const faults = errors.filter((e) => FAULT_ERRORS.has(e));
|
|
126
|
+
// "Toner Low" / "Drum End Soon" are warnings handled by the battery services
|
|
127
|
+
const textFault = FAULT_TEXT.test(text) && !WARNING_TEXT.test(text);
|
|
128
|
+
const printing = printerStatus === 4 || (PRINTING_TEXT.test(text) && !textFault);
|
|
129
|
+
return {
|
|
130
|
+
printing,
|
|
131
|
+
fault: faults.length > 0 || textFault,
|
|
132
|
+
faults,
|
|
133
|
+
sleeping: /sleep/i.test(text),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
module.exports = {
|
|
138
|
+
parseRecords,
|
|
139
|
+
decodeMaintenance,
|
|
140
|
+
decodeCounters,
|
|
141
|
+
decodeNextCare,
|
|
142
|
+
decodeText,
|
|
143
|
+
decodeErrorState,
|
|
144
|
+
summarizeStatus,
|
|
145
|
+
toBuffer,
|
|
146
|
+
};
|
package/lib/platform.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { PLATFORM_NAME, PLUGIN_NAME } = require('./settings');
|
|
4
|
+
const { PrinterAccessory } = require('./accessory');
|
|
5
|
+
const schema = require('../config.schema.json');
|
|
6
|
+
|
|
7
|
+
const DEFAULTS = Object.fromEntries(
|
|
8
|
+
Object.entries(schema.schema.properties.printers.items.properties)
|
|
9
|
+
.filter(([, v]) => 'default' in v)
|
|
10
|
+
.map(([k, v]) => [k, v.default]),
|
|
11
|
+
);
|
|
12
|
+
|
|
13
|
+
class BrotherPrinterPlatform {
|
|
14
|
+
constructor(log, config, api) {
|
|
15
|
+
this.log = log;
|
|
16
|
+
this.config = config || {};
|
|
17
|
+
this.api = api;
|
|
18
|
+
this.cached = new Map();
|
|
19
|
+
this.printers = [];
|
|
20
|
+
|
|
21
|
+
this.api.on('didFinishLaunching', () => {
|
|
22
|
+
try {
|
|
23
|
+
this.setup();
|
|
24
|
+
} catch (err) {
|
|
25
|
+
this.log.error(`Setup failed: ${err && err.stack ? err.stack : err}`);
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
this.api.on('shutdown', () => this.printers.forEach((p) => p.stop()));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
configureAccessory(accessory) {
|
|
32
|
+
this.cached.set(accessory.UUID, accessory);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
setup() {
|
|
36
|
+
const entries = Array.isArray(this.config.printers) ? this.config.printers : [];
|
|
37
|
+
const active = new Set();
|
|
38
|
+
|
|
39
|
+
entries.forEach((rawEntry, idx) => {
|
|
40
|
+
let entry = rawEntry;
|
|
41
|
+
if (!entry || !String(entry.host || '').trim()) {
|
|
42
|
+
// The settings screen can save a blank row; only warn when it was filled in
|
|
43
|
+
const filled = entry && Object.entries(entry).some(([k, v]) => k !== 'host' && v !== DEFAULTS[k] && v !== '');
|
|
44
|
+
const msg = `Printer #${idx + 1} has no host set, skipping it.`;
|
|
45
|
+
if (filled) { this.log.warn(msg); } else { this.log.debug(msg); }
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
entry = { ...entry, host: String(entry.host).trim() };
|
|
49
|
+
const name = String(entry.name || 'Printer').trim();
|
|
50
|
+
const uuid = this.api.hap.uuid.generate(`${PLUGIN_NAME}:${name}`);
|
|
51
|
+
if (active.has(uuid)) {
|
|
52
|
+
this.log.warn(`Two printers are named "${name}". Give each a unique name; skipping the second.`);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
active.add(uuid);
|
|
56
|
+
|
|
57
|
+
let accessory = this.cached.get(uuid);
|
|
58
|
+
const isNew = !accessory;
|
|
59
|
+
if (isNew) {
|
|
60
|
+
accessory = new this.api.platformAccessory(name, uuid, this.api.hap.Categories.SENSOR);
|
|
61
|
+
}
|
|
62
|
+
accessory.context.host = entry.host;
|
|
63
|
+
|
|
64
|
+
try {
|
|
65
|
+
this.printers.push(new PrinterAccessory(this, accessory, { ...entry, name }));
|
|
66
|
+
} catch (err) {
|
|
67
|
+
this.log.error(`[${name}] Couldn't set up this printer: ${err && err.message ? err.message : err}`);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (isNew) {
|
|
72
|
+
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]);
|
|
73
|
+
this.log.info(`Added printer "${name}" (${entry.host}).`);
|
|
74
|
+
} else {
|
|
75
|
+
this.api.updatePlatformAccessories([accessory]);
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const stale = [...this.cached.values()].filter((a) => !active.has(a.UUID));
|
|
80
|
+
if (stale.length) {
|
|
81
|
+
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, stale);
|
|
82
|
+
stale.forEach((a) => this.log.info(`Removed printer "${a.displayName}", no longer in config.`));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
module.exports = { BrotherPrinterPlatform };
|
package/lib/settings.js
ADDED
package/lib/snmp.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const snmp = require('net-snmp');
|
|
4
|
+
const decode = require('./decode');
|
|
5
|
+
|
|
6
|
+
const OID = {
|
|
7
|
+
maintenance: '1.3.6.1.4.1.2435.2.3.9.4.2.1.5.5.8.0', // brInfoMaintenance
|
|
8
|
+
counters: '1.3.6.1.4.1.2435.2.3.9.4.2.1.5.5.10.0', // brInfoCounter
|
|
9
|
+
nextCare: '1.3.6.1.4.1.2435.2.3.9.4.2.1.5.5.11.0', // brInfoNextCare
|
|
10
|
+
statusText: '1.3.6.1.4.1.2435.2.3.9.4.2.1.5.4.5.2.0', // LCD status line
|
|
11
|
+
model: '1.3.6.1.2.1.25.3.2.1.3.1', // hrDeviceDescr
|
|
12
|
+
serial: '1.3.6.1.2.1.43.5.1.1.17.1', // prtGeneralSerialNumber
|
|
13
|
+
printerStatus: '1.3.6.1.2.1.25.3.5.1.1.1', // hrPrinterStatus
|
|
14
|
+
errorState: '1.3.6.1.2.1.25.3.5.1.2.1', // hrPrinterDetectedErrorState
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const NAMES = Object.keys(OID);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Query the printer once and return decoded values.
|
|
21
|
+
* Rejects only when the printer can't be reached at all.
|
|
22
|
+
*/
|
|
23
|
+
function query({ host, port = 161, community = 'public', timeout = 5000, retries = 1 }) {
|
|
24
|
+
return new Promise((resolve, reject) => {
|
|
25
|
+
let session;
|
|
26
|
+
try {
|
|
27
|
+
session = snmp.createSession(host, community, {
|
|
28
|
+
port,
|
|
29
|
+
version: snmp.Version2c,
|
|
30
|
+
timeout,
|
|
31
|
+
retries,
|
|
32
|
+
idBitsSize: 32,
|
|
33
|
+
});
|
|
34
|
+
} catch (err) {
|
|
35
|
+
reject(err);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let settled = false;
|
|
40
|
+
const finish = (err, result) => {
|
|
41
|
+
if (settled) { return; }
|
|
42
|
+
settled = true;
|
|
43
|
+
try { session.close(); } catch { /* already closed */ }
|
|
44
|
+
if (err) { reject(err); } else { resolve(result); }
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
session.on('error', (err) => finish(err));
|
|
48
|
+
|
|
49
|
+
session.get(NAMES.map((n) => OID[n]), (err, varbinds) => {
|
|
50
|
+
if (err) {
|
|
51
|
+
finish(err);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const raw = {};
|
|
55
|
+
varbinds.forEach((vb, idx) => {
|
|
56
|
+
raw[NAMES[idx]] = snmp.isVarbindError(vb) ? null : vb.value;
|
|
57
|
+
});
|
|
58
|
+
finish(null, parse(raw));
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function parse(raw) {
|
|
64
|
+
const maintenance = decode.decodeMaintenance(raw.maintenance);
|
|
65
|
+
const counters = decode.decodeCounters(raw.counters);
|
|
66
|
+
const nextCare = decode.decodeNextCare(raw.nextCare);
|
|
67
|
+
const statusText = decode.decodeText(raw.statusText);
|
|
68
|
+
const printerStatus = typeof raw.printerStatus === 'number' ? raw.printerStatus : null;
|
|
69
|
+
const errors = decode.decodeErrorState(raw.errorState);
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
model: decode.decodeText(raw.model) || null,
|
|
73
|
+
serial: decode.decodeText(raw.serial) || null,
|
|
74
|
+
statusText,
|
|
75
|
+
printerStatus,
|
|
76
|
+
errors,
|
|
77
|
+
...decode.summarizeStatus({ statusText, printerStatus, errors }),
|
|
78
|
+
tonerPercent: pick(maintenance.tonerPercent),
|
|
79
|
+
tonerPercentFine: pick(maintenance.tonerPercentFine),
|
|
80
|
+
drumPercent: pick(maintenance.drumPercent),
|
|
81
|
+
drumPagesUsed: pick(maintenance.drumPagesUsed),
|
|
82
|
+
drumPagesRemaining: pick(nextCare.drumPagesRemaining),
|
|
83
|
+
totalPages: pick(counters.totalPages),
|
|
84
|
+
duplexPages: pick(counters.duplexPages),
|
|
85
|
+
unknown: {
|
|
86
|
+
maintenance: maintenance.unknown,
|
|
87
|
+
counters: counters.unknown,
|
|
88
|
+
nextCare: nextCare.unknown,
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const pick = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
|
94
|
+
|
|
95
|
+
module.exports = { query, parse, OID };
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "homebridge-brother-printer",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"displayName": "Brother Printer",
|
|
4
|
+
"version": "0.1.4",
|
|
5
|
+
"description": "Brother laser printers in HomeKit: printing state, problem alerts and toner level, read locally over SNMP.",
|
|
6
|
+
"author": "Manuel Zamfir",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"homepage": "https://github.com/zmanuel1234/homebridge-brother-printer#readme",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/zmanuel1234/homebridge-brother-printer.git"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/zmanuel1234/homebridge-brother-printer/issues"
|
|
15
|
+
},
|
|
16
|
+
"main": "index.js",
|
|
17
|
+
"bin": {
|
|
18
|
+
"brother-printer-probe": "bin/brother-printer-probe.js"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"index.js",
|
|
22
|
+
"lib/",
|
|
23
|
+
"bin/",
|
|
24
|
+
"config.schema.json",
|
|
25
|
+
"README.md",
|
|
26
|
+
"CHANGELOG.md",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
],
|
|
29
|
+
"scripts": {
|
|
30
|
+
"lint": "eslint .",
|
|
31
|
+
"test": "node --test test/*.test.js"
|
|
32
|
+
},
|
|
33
|
+
"keywords": [
|
|
34
|
+
"homebridge-plugin",
|
|
35
|
+
"homebridge",
|
|
36
|
+
"brother",
|
|
37
|
+
"printer",
|
|
38
|
+
"toner",
|
|
39
|
+
"snmp",
|
|
40
|
+
"homekit"
|
|
41
|
+
],
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": "^18.20.0 || ^20.15.0 || ^22.0.0 || ^24.0.0",
|
|
44
|
+
"homebridge": "^1.6.0 || ^2.0.0"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"net-snmp": "^3.29.2"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@eslint/js": "^9.17.0",
|
|
51
|
+
"eslint": "^9.17.0",
|
|
52
|
+
"globals": "^15.14.0",
|
|
53
|
+
"homebridge": "^2.5.0"
|
|
54
|
+
}
|
|
55
|
+
}
|