homebridge-brother-printer 0.1.4 → 0.2.1

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 CHANGED
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1 - 2026-11-03
4
+
5
+ ### Fixed
6
+ - Settings screen: each printer's fields now form one group. Before, Sensors, Advanced and
7
+ the name/host fields each acted as a separate printer, so the screen showed values from a
8
+ blank entry (for example a 60 s poll interval when 10 was saved) and saved empty printer
9
+ rows. Remove any empty printer rows left in your config.
10
+ - Port, poll interval and offline count are number boxes instead of sliders.
11
+
12
+ ## 0.2.0 - 2026-11-03
13
+
14
+ ### Added
15
+ - Color lasers: toner per color, drum per color, belt, fuser, laser unit and paper feed kits.
16
+ - Inkjets: ink per color and the ink waste box. Toner wording becomes Ink.
17
+ - The battery shows the lowest color, and turns low when any color reaches the threshold by
18
+ either reading, or when the printer flags low toner.
19
+ - Toner / ink tiles: one per color on color printers.
20
+ - SNMP v1 for older printers (`snmpVersion`, automatic by default).
21
+ - Printers that report no levels (older and ink tank models) get no battery instead of 0%.
22
+ - Warnings in the log when the drum or another part nears end of life.
23
+ - Problem log lines name the condition (cover open, paper jam...).
24
+ - Page count from mono + color counts on inkjets that don't report a total.
25
+
26
+ ### Changed
27
+ - Status text is decoded in the printer's character set, so non-English displays read
28
+ correctly. Problems and printing rely on language-neutral status codes first.
29
+ - Model and serial also read from Brother's own records, for printers without the
30
+ standard ones; page count falls back to the Printer MIB.
31
+ - When coarse levels tie (they move in 10% steps), the finer reading picks the lowest
32
+ color, so the battery names the color that is actually running out.
33
+ - Tested against SNMP captures from 14 Brother models.
34
+
3
35
  ## 0.1.4 - 2026-11-03
4
36
 
5
37
  First public release.
package/README.md CHANGED
@@ -3,9 +3,9 @@
3
3
  [![npm](https://badgen.net/npm/v/homebridge-brother-printer)](https://www.npmjs.com/package/homebridge-brother-printer)
4
4
  [![license](https://badgen.net/github/license/zmanuel1234/homebridge-brother-printer)](LICENSE)
5
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.
6
+ Shows a Brother laser or inkjet printer in HomeKit: whether it's printing, whether it
7
+ needs attention, and how much toner or ink is left. Everything is read locally over SNMP,
8
+ with no cloud or Brother account.
9
9
 
10
10
  Generic AirPrint/IPP plugins can't show real toner levels on many Brother printers,
11
11
  because the standard Printer MIB only reports "some remaining". Brother's own SNMP
@@ -17,17 +17,29 @@ Each printer gets these sensors:
17
17
  - **Printer** (occupancy sensor): Detected while a job prints. Use it in automations.
18
18
  - **Printer Problem** (contact sensor): Open on a jam, open cover, empty tray or other
19
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.
20
+ - **Toner / Ink** (battery level on the Printer accessory): the toner or ink %, with Home's
21
+ native low-battery alert at or below your threshold. On color printers it shows the
22
+ lowest color, so the alert fires when any color runs low.
23
+ - **Toner / ink tiles** (optional humidity sensors): the level as a number on its own tile,
24
+ one per color on color printers.
23
25
 
24
26
  While the printer can't be reached, all of them show No Response.
25
27
 
26
28
  ## Requirements
27
29
 
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.
30
+ - A Brother printer with SNMP. Tested on a real **MFC-L2750DW**, and against SNMP
31
+ captures from these models (from the [brother](https://github.com/bieniu/brother)
32
+ library, which Home Assistant's Brother integration uses):
33
+
34
+ | Kind | Models | What's read |
35
+ |---|---|---|
36
+ | Mono laser | MFC-L2750DW, HL-L2340DW, DCP-L2540DN, DCP-7070DW, DCP-1618W | Toner, drum |
37
+ | Color laser | DCP-L3550CDW, DCP-9020CDW | Toner per color, drums, belt, fuser, paper feed kit |
38
+ | Inkjet | MFC-J680DW, MFC-J5110DW, DCP-J132W, DCP-T735DW, MFC-5490CN | Ink per color, ink waste box |
39
+ | Older / ink tank | HL-2270DW, HL-5350DN, MFC-T910DW | Status, problems, page count; these don't report levels |
40
+
41
+ Other Brother models generally use the same records. Reports, with the probe output
42
+ below, are welcome.
31
43
  - SNMP turned on in the printer's web page: **Network → Protocol → SNMP** (v1/v2c,
32
44
  read-only is enough). The default community is `public`.
33
45
  - A fixed address for the printer: reserve its IP in your router, or use its mDNS
@@ -66,12 +78,13 @@ Set it up in the plugin's settings screen, or in `config.json`:
66
78
  | `host` | | Printer IP address or hostname. Printers without one are ignored. |
67
79
  | `community` | `public` | SNMP community string. |
68
80
  | `port` | `161` | SNMP port. |
81
+ | `snmpVersion` | `auto` | `auto` tries v2c, then v1. Set `1` for older printers that only answer v1. |
69
82
  | `pollInterval` | `60` | Seconds between polls (10–3600). |
70
- | `lowTonerThreshold` | `10` | Toner % at or below which Home shows it as low. |
83
+ | `lowTonerThreshold` | `10` | Toner or ink % at or below which Home shows it as low (any color, on color printers). |
71
84
  | `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. |
85
+ | `tonerTile` | `false` | Add humidity sensors showing the toner or ink %, one per color on color printers. They also count in Home's climate summary. |
73
86
  | `showDrum` | `false` | Add drum life as a second battery. See below. |
74
- | `lowDrumThreshold` | `10` | Drum % at or below which Home shows it as low. |
87
+ | `lowDrumThreshold` | `10` | Drum and parts % (belt, fuser, laser unit, paper feed kit, ink waste box) at or below which a warning is logged, and the drum battery shows low. |
75
88
  | `offlineAfter` | `3` | Failed polls in a row before the printer shows No Response. |
76
89
  | `debug` | `false` | Log every poll at info level. |
77
90
 
@@ -81,7 +94,7 @@ HomeKit has no printer accessory type, so the plugin uses the closest sensors an
81
94
  words them its own way:
82
95
 
83
96
  - The printing sensor reads **Detected** / **Not Detected**.
84
- - Low toner is announced as **"battery is low"**. For a clearer message, add a Home
97
+ - Low toner or ink is announced as **"battery is low"**. For a clearer message, add a Home
85
98
  automation on that trigger that sends your own notification.
86
99
  - Home shows only one battery per accessory. With `showDrum` on, it may show the drum
87
100
  instead of the toner, which is why the drum is off by default. It's still read, and the
@@ -89,6 +102,17 @@ words them its own way:
89
102
  - The page count is a custom characteristic, visible in Eve, Controller and the Homebridge
90
103
  UI, not in Apple Home.
91
104
 
105
+ ## Levels and low alerts
106
+
107
+ Brother printers report two readings per supply: a coarse one (the number on the
108
+ printer's web page and display) and a finer one. The battery and tiles show the coarse
109
+ one, so they match the printer. A supply counts as low when either reading is at or below
110
+ `lowTonerThreshold`, or when the printer itself flags low toner, so a cartridge that shows
111
+ 10% but is really at 2% still raises the alert.
112
+
113
+ Printers without level reporting (some older models and ink tank printers) get no
114
+ battery; status, problems and the page count still work.
115
+
92
116
  ## Going offline
93
117
 
94
118
  The time before a printer shows No Response is about
@@ -116,6 +140,10 @@ model.
116
140
  - **"Can't reach … Request timed out"**: SNMP is off on the printer, the address is wrong,
117
141
  or a firewall blocks UDP port 161. Test from the Homebridge machine with
118
142
  `snmpget -v2c -c public <printer-ip> 1.3.6.1.2.1.1.1.0` (from the `snmp` package).
143
+ - **Status text in another language**: the plugin reads the printer's character set, so
144
+ the log shows the display text as the printer shows it. Problems and printing are
145
+ detected from language-neutral status codes, with English display text as a fallback.
146
+ - **Old printer never connects**: set `snmpVersion` to `1`.
119
147
  - **Toner shows 0% with a full cartridge**: some non-genuine cartridges aren't recognised
120
148
  by the printer, which then reports no level.
121
149
 
@@ -123,18 +151,23 @@ model.
123
151
 
124
152
  Brother printers expose maintenance data as packed records in their private MIB
125
153
  (`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:
154
+ code, `0x01`, a length byte and a big-endian value; older models use a two-byte
155
+ current/max form. The main codes:
127
156
 
128
157
  | Code | Meaning |
129
158
  |---|---|
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 |
159
+ | `0x81`–`0x84` | Black, cyan, magenta, yellow toner or ink, % (coarse) |
160
+ | `0x6f`–`0x72`, `0xa1`–`0xa4` | The same, finer reading |
161
+ | `0x41`, `0x80`, `0x79`–`0x7b` | Drum life (mono; black, cyan, magenta, yellow) |
162
+ | `0x69`–`0x6d`, `0x85` | Belt, fuser, laser unit, paper feed kits, ink waste box |
163
+ | next care `0x82`, `0xa4`–`0xa7` | Drum pages remaining |
164
+ | counter `0x00` | Total pages printed |
135
165
 
136
166
  Printing and problem state come from the standard Host Resources MIB (`hrPrinterStatus`,
137
- `hrPrinterDetectedErrorState`) plus the text on the printer's display.
167
+ `hrPrinterDetectedErrorState`), with the display text as a fallback.
168
+
169
+ The record codes follow the [brother](https://github.com/bieniu/brother) Python library
170
+ by Maciej Bieniek (Apache-2.0), and the tests use SNMP captures from its test suite.
138
171
 
139
172
  ## License
140
173
 
@@ -2,7 +2,7 @@
2
2
  "pluginAlias": "BrotherPrinter",
3
3
  "pluginType": "platform",
4
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).",
5
+ "headerDisplay": "Shows Brother laser and inkjet printers in HomeKit: printing state, problems, and toner or ink levels. SNMP must be on in the printer's web page (Network > Protocol).",
6
6
  "schema": {
7
7
  "type": "object",
8
8
  "properties": {
@@ -40,6 +40,31 @@
40
40
  "minimum": 1,
41
41
  "maximum": 65535
42
42
  },
43
+ "snmpVersion": {
44
+ "title": "SNMP version",
45
+ "type": "string",
46
+ "default": "auto",
47
+ "oneOf": [
48
+ {
49
+ "title": "Automatic (v2c, then v1)",
50
+ "enum": [
51
+ "auto"
52
+ ]
53
+ },
54
+ {
55
+ "title": "v2c",
56
+ "enum": [
57
+ "2c"
58
+ ]
59
+ },
60
+ {
61
+ "title": "v1 (older printers)",
62
+ "enum": [
63
+ "1"
64
+ ]
65
+ }
66
+ ]
67
+ },
43
68
  "pollInterval": {
44
69
  "title": "Poll every (seconds)",
45
70
  "type": "integer",
@@ -48,11 +73,12 @@
48
73
  "maximum": 3600
49
74
  },
50
75
  "lowTonerThreshold": {
51
- "title": "Toner low at (%)",
76
+ "title": "Toner / ink low at (%)",
52
77
  "type": "integer",
53
78
  "default": 10,
54
79
  "minimum": 0,
55
- "maximum": 100
80
+ "maximum": 100,
81
+ "description": "On color printers, the battery shows the lowest color and turns low when any color reaches this."
56
82
  },
57
83
  "showDrum": {
58
84
  "title": "Show drum life as a second battery",
@@ -61,18 +87,16 @@
61
87
  "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
88
  },
63
89
  "lowDrumThreshold": {
64
- "title": "Drum low at (%)",
90
+ "title": "Drum and parts low at (%)",
65
91
  "type": "integer",
66
92
  "default": 10,
67
93
  "minimum": 0,
68
94
  "maximum": 100,
69
- "condition": {
70
- "functionBody": "return model.printers[arrayIndices].showDrum === true;"
71
- }
95
+ "description": "Logs a warning when the drum, belt, fuser, laser unit, paper feed kit or ink waste box reaches this."
72
96
  },
73
97
  "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.",
98
+ "title": "Show toner / ink % on tiles",
99
+ "description": "Adds a humidity sensor whose value is the level: one for a mono printer, one per color for a color printer. They also count in Home's climate summary.",
76
100
  "type": "boolean",
77
101
  "default": false
78
102
  },
@@ -107,30 +131,45 @@
107
131
  "orderable": false,
108
132
  "buttonText": "Add printer",
109
133
  "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
134
  {
125
- "type": "fieldset",
126
- "title": "Advanced",
127
- "expandable": true,
135
+ "type": "section",
128
136
  "items": [
129
- "printers[].community",
130
- "printers[].port",
131
- "printers[].pollInterval",
132
- "printers[].offlineAfter",
133
- "printers[].debug"
137
+ "printers[].name",
138
+ "printers[].host",
139
+ {
140
+ "type": "fieldset",
141
+ "title": "Sensors",
142
+ "expandable": true,
143
+ "items": [
144
+ "printers[].lowTonerThreshold",
145
+ "printers[].showDrum",
146
+ "printers[].lowDrumThreshold",
147
+ "printers[].tonerTile",
148
+ "printers[].faultSensor"
149
+ ]
150
+ },
151
+ {
152
+ "type": "fieldset",
153
+ "title": "Advanced",
154
+ "expandable": true,
155
+ "items": [
156
+ "printers[].community",
157
+ {
158
+ "key": "printers[].port",
159
+ "type": "number"
160
+ },
161
+ "printers[].snmpVersion",
162
+ {
163
+ "key": "printers[].pollInterval",
164
+ "type": "number"
165
+ },
166
+ {
167
+ "key": "printers[].offlineAfter",
168
+ "type": "number"
169
+ },
170
+ "printers[].debug"
171
+ ]
172
+ }
134
173
  ]
135
174
  }
136
175
  ]
package/lib/accessory.js CHANGED
@@ -26,6 +26,17 @@ function pagesCharacteristic(hap) {
26
26
  }
27
27
 
28
28
  const clamp = (v) => Math.max(0, Math.min(100, Math.round(v)));
29
+ const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
30
+ const TILE_SUBTYPE = { black: 'tonerTile', cyan: 'tile-cyan', magenta: 'tile-magenta', yellow: 'tile-yellow' };
31
+ const FAULT_NAMES = {
32
+ noPaper: 'out of paper', noToner: 'toner or ink empty', doorOpen: 'cover open', jammed: 'paper jam',
33
+ serviceRequested: 'service requested', inputTrayMissing: 'tray missing', outputTrayMissing: 'output tray missing',
34
+ markerSupplyMissing: 'cartridge missing', outputFull: 'output tray full',
35
+ };
36
+ const PART_NAMES = {
37
+ belt: 'Belt unit', fuser: 'Fuser unit', laser: 'Laser unit',
38
+ paperFeed1: 'Paper feed kit (tray 1)', paperFeedMP: 'Paper feed kit (MP tray)', inkWasteBox: 'Ink waste box',
39
+ };
29
40
 
30
41
  class PrinterAccessory {
31
42
  constructor(platform, accessory, config) {
@@ -42,6 +53,8 @@ class PrinterAccessory {
42
53
  community: config.community || 'public',
43
54
  timeout: 5000,
44
55
  retries: 1,
56
+ version: ['1', '2c'].includes(String(config.snmpVersion)) ? String(config.snmpVersion) : 'auto',
57
+ state: {},
45
58
  };
46
59
  this.interval = Math.max(10, Number(config.pollInterval) || 60) * 1000;
47
60
  this.lowToner = clamp(config.lowTonerThreshold ?? 10);
@@ -57,6 +70,8 @@ class PrinterAccessory {
57
70
  this.last = {};
58
71
  this.timer = null;
59
72
  this.stopped = false;
73
+ this.tiles = {};
74
+ this.guarded = [];
60
75
 
61
76
  this.buildServices();
62
77
  this.guardReads();
@@ -113,14 +128,39 @@ class PrinterAccessory {
113
128
  this.removeSubtype(Service.ContactSensor, 'problem');
114
129
  }
115
130
 
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');
131
+ // Supply tiles are created once the printer says which colors it has;
132
+ // here only the ones restored from the cache are picked up.
133
+ for (const [color, subtype] of Object.entries(TILE_SUBTYPE)) {
134
+ const svc = acc.getServiceById(Service.HumiditySensor, subtype);
135
+ if (!svc) { continue; }
136
+ if (this.tonerTile) { this.tiles[color] = svc; } else { acc.removeService(svc); }
137
+ }
138
+ }
139
+
140
+ /** Make one tile per reported supply; remove tiles for colors not reported */
141
+ ensureTiles(d) {
142
+ if (!this.tonerTile) { return; }
143
+ const { Service, Characteristic: C } = this.hap;
144
+ const colors = new Set(d.supplies.map((s) => s.color));
145
+ const mono = d.supplies.length === 1;
146
+ const kind = d.type === 'ink' ? 'Ink' : 'Toner';
147
+
148
+ for (const [color, subtype] of Object.entries(TILE_SUBTYPE)) {
149
+ if (!colors.has(color)) {
150
+ if (this.tiles[color]) {
151
+ this.accessory.removeService(this.tiles[color]);
152
+ delete this.tiles[color];
153
+ }
154
+ continue;
155
+ }
156
+ if (this.tiles[color]) { continue; }
157
+ const name = mono ? `${this.name} ${kind}` : `${this.name} ${cap(color)}`;
158
+ const svc = this.accessory.addService(Service.HumiditySensor, name, subtype);
159
+ this.label(svc, name);
160
+ if (!svc.testCharacteristic(C.StatusActive)) { svc.addOptionalCharacteristic(C.StatusActive); }
161
+ svc.getCharacteristic(C.StatusActive).updateValue(true);
162
+ this.guard(svc.getCharacteristic(C.CurrentRelativeHumidity));
163
+ this.tiles[color] = svc;
124
164
  }
125
165
  }
126
166
 
@@ -138,17 +178,22 @@ class PrinterAccessory {
138
178
  [this.drum, C.BatteryLevel],
139
179
  [this.drum, C.StatusLowBattery],
140
180
  [this.problem, C.ContactSensorState],
141
- [this.tile, C.CurrentRelativeHumidity],
181
+ ...Object.values(this.tiles).map((svc) => [svc, C.CurrentRelativeHumidity]),
142
182
  ];
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
- });
183
+ for (const [svc, type] of pairs) {
184
+ if (svc) { this.guard(svc.getCharacteristic(type)); }
149
185
  }
150
186
  }
151
187
 
188
+ guard(ch) {
189
+ if (this.guarded.includes(ch)) { return; }
190
+ this.guarded.push(ch);
191
+ ch.onGet(() => {
192
+ if (!this.online) { throw this.noResponse(); }
193
+ return ch.value;
194
+ });
195
+ }
196
+
152
197
  noResponse() {
153
198
  const { HapStatusError, HAPStatus } = this.hap;
154
199
  return new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
@@ -219,7 +264,7 @@ class PrinterAccessory {
219
264
  for (const ch of this.guarded) { ch.updateValue(ch.value); }
220
265
  }
221
266
  this.occupancy.updateCharacteristic(C.StatusActive, online);
222
- if (this.tile) { this.tile.updateCharacteristic(C.StatusActive, online); }
267
+ for (const svc of Object.values(this.tiles)) { svc.updateCharacteristic(C.StatusActive, online); }
223
268
  if (this.problem) { this.problem.updateCharacteristic(C.StatusActive, online); }
224
269
  if (!online) {
225
270
  this.occupancy.updateCharacteristic(C.OccupancyDetected, 0);
@@ -250,7 +295,9 @@ class PrinterAccessory {
250
295
  : C.ContactSensorState.CONTACT_DETECTED);
251
296
  }
252
297
  if (d.fault && !this.last.fault) {
253
- this.log.warn(`[${this.name}] Problem: ${d.statusText || d.faults.join(', ')}`);
298
+ const what = d.faults.map((f) => FAULT_NAMES[f] || f).join(', ');
299
+ const shown = d.statusText ? `display: "${d.statusText}"` : '';
300
+ this.log.warn(`[${this.name}] Problem: ${[what, shown].filter(Boolean).join('; ')}`);
254
301
  } else if (!d.fault && this.last.fault) {
255
302
  this.log.info(`[${this.name}] Problem cleared.`);
256
303
  }
@@ -260,40 +307,106 @@ class PrinterAccessory {
260
307
  this.log.info(`[${this.name}] Status: ${d.statusText}`);
261
308
  }
262
309
 
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
- }
310
+ this.applySupplies(d);
311
+ this.applyDrumAndParts(d);
286
312
 
287
313
  if (d.totalPages !== null) { this.pages.updateValue(d.totalPages); }
288
314
  this.last.statusText = d.statusText;
289
315
 
290
316
  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'}".`);
317
+ const kind = d.type === 'ink' ? 'ink' : 'toner';
318
+ const levels = d.supplies.length
319
+ ? d.supplies.map((s) => (d.supplies.length === 1 ? `${kind} ${s.level}%` : `${s.color} ${s.level}%`)).join(', ')
320
+ : `no ${kind} levels reported`;
321
+ const drum = d.drumPercent !== null ? `, drum ${d.drumPercent}%` : '';
322
+ this.log.info(`[${this.name}] Connected to ${d.model || 'printer'} (SNMP v${d.snmpVersion}): ${levels}${drum}, `
323
+ + `${d.totalPages ?? '?'} pages, status "${d.statusText || 'unknown'}".`);
293
324
  this.last.summary = true;
294
325
  }
295
326
  }
296
327
 
328
+ /**
329
+ * Toner/ink battery: the lowest supply, so Home alerts when any color runs
330
+ * low. A supply counts as low when its level or its finer reading is at or
331
+ * below the threshold, or the printer itself flags low/no toner.
332
+ */
333
+ applySupplies(d) {
334
+ const C = this.hap.Characteristic;
335
+ const kind = d.type === 'ink' ? 'Ink' : 'Toner';
336
+
337
+ if (!d.supplies.length) {
338
+ // Some models (e.g. ink tank printers) report no levels at all
339
+ if (this.toner) {
340
+ this.log.info(`[${this.name}] This printer doesn't report ${kind.toLowerCase()} levels; `
341
+ + 'leaving out the battery.');
342
+ this.accessory.removeService(this.toner);
343
+ this.guarded = this.guarded.filter((ch) => !this.toner.characteristics.includes(ch));
344
+ this.toner = null;
345
+ }
346
+ return;
347
+ }
348
+ if (!this.toner) {
349
+ this.toner = this.battery('toner', `${this.name} ${kind}`);
350
+ this.occupancy.addLinkedService(this.toner);
351
+ this.guard(this.toner.getCharacteristic(C.BatteryLevel));
352
+ this.guard(this.toner.getCharacteristic(C.StatusLowBattery));
353
+ }
354
+
355
+ const flagged = d.errors.includes('lowToner') || d.errors.includes('noToner');
356
+ const isLow = (s) => s.level <= this.lowToner || (s.fine !== null && s.fine <= this.lowToner);
357
+ const low = d.supplies.filter(isLow);
358
+ const lowest = d.lowestSupply;
359
+ const level = clamp(lowest.level);
360
+
361
+ this.toner.updateCharacteristic(C.BatteryLevel, level);
362
+ this.toner.updateCharacteristic(C.StatusLowBattery, low.length || flagged
363
+ ? C.StatusLowBattery.BATTERY_LEVEL_LOW
364
+ : C.StatusLowBattery.BATTERY_LEVEL_NORMAL);
365
+
366
+ this.ensureTiles(d);
367
+ for (const s of d.supplies) {
368
+ if (this.tiles[s.color]) { this.tiles[s.color].updateCharacteristic(C.CurrentRelativeHumidity, clamp(s.level)); }
369
+ }
370
+
371
+ const mono = d.supplies.length === 1;
372
+ const label = (s) => (mono ? kind : `${cap(s.color)} ${kind.toLowerCase()}`);
373
+ const prev = this.last.supplies || {};
374
+ for (const s of d.supplies) {
375
+ const was = prev[s.color];
376
+ if (was && was.level !== s.level) { this.log.info(`[${this.name}] ${label(s)} ${s.level}%`); }
377
+ if (isLow(s) && !(was && was.low)) {
378
+ const fine = s.fine !== null && s.fine !== s.level ? ` (${s.fine}% by the finer reading)` : '';
379
+ this.log.warn(`[${this.name}] ${label(s)} is low: ${s.level}%${fine}.`);
380
+ }
381
+ }
382
+ this.last.supplies = Object.fromEntries(d.supplies.map((s) => [s.color, { level: s.level, low: isLow(s) }]));
383
+ }
384
+
385
+ /** Drum battery (optional) and log warnings for drums and other parts */
386
+ applyDrumAndParts(d) {
387
+ const drums = Object.entries(d.drums).filter(([, v]) => typeof v.percent === 'number');
388
+ if (drums.length) {
389
+ const [color, lowest] = drums.reduce((a, b) => (b[1].percent < a[1].percent ? b : a));
390
+ const level = clamp(lowest.percent);
391
+ if (this.drum) { this.setBattery(this.drum, level, this.lowDrum); }
392
+ const name = drums.length > 1 ? `${cap(color)} drum` : 'Drum';
393
+ this.warnOnce('drum', level <= this.lowDrum,
394
+ `${name} is near end of life (${level}%, ${lowest.pagesRemaining ?? '?'} pages left).`);
395
+ }
396
+ for (const [key, part] of Object.entries(d.parts)) {
397
+ if (typeof part.percent !== 'number' || !PART_NAMES[key]) { continue; }
398
+ const left = part.pagesRemaining !== undefined ? `, ${part.pagesRemaining} pages left` : '';
399
+ this.warnOnce(`part-${key}`, part.percent <= this.lowDrum,
400
+ `${PART_NAMES[key]} is near end of life (${part.percent}%${left}).`);
401
+ }
402
+ }
403
+
404
+ warnOnce(key, condition, message) {
405
+ this.last.warned = this.last.warned || {};
406
+ if (condition && !this.last.warned[key]) { this.log.warn(`[${this.name}] ${message}`); }
407
+ this.last.warned[key] = condition;
408
+ }
409
+
297
410
  setBattery(svc, level, threshold) {
298
411
  const C = this.hap.Characteristic;
299
412
  svc.updateCharacteristic(C.BatteryLevel, level);
package/lib/decode.js CHANGED
@@ -1,36 +1,81 @@
1
1
  'use strict';
2
2
 
3
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.
4
+ * Brother printers pack maintenance data into OctetString "blobs" of records:
5
+ * [code(1)] [0x01] [length(1)] [value(length bytes, big-endian)]
6
+ * terminated by 0xFF. Older models use length 2 with [current][max], read as
7
+ * current / max %.
7
8
  *
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.
9
+ * Record codes follow the bieniu/brother library (Apache-2.0), which Home
10
+ * Assistant's Brother integration uses, and were checked against a real
11
+ * MFC-L2750DW.
10
12
  */
11
13
 
14
+ const COLORS = ['black', 'cyan', 'magenta', 'yellow'];
15
+
16
+ // Maintenance blob (brInfoMaintenance)
12
17
  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 },
18
+ 0x81: { group: 'level', color: 'black' },
19
+ 0x82: { group: 'level', color: 'cyan' },
20
+ 0x83: { group: 'level', color: 'magenta' },
21
+ 0x84: { group: 'level', color: 'yellow' },
22
+ 0x6f: { group: 'fine', color: 'black', percent: true },
23
+ 0x70: { group: 'fine', color: 'cyan', percent: true },
24
+ 0x71: { group: 'fine', color: 'magenta', percent: true },
25
+ 0x72: { group: 'fine', color: 'yellow', percent: true },
26
+ 0xa1: { group: 'fine', color: 'black', percent: true },
27
+ 0xa2: { group: 'fine', color: 'cyan', percent: true },
28
+ 0xa3: { group: 'fine', color: 'magenta', percent: true },
29
+ 0xa4: { group: 'fine', color: 'yellow', percent: true },
30
+ 0x31: { group: 'supplyStatus', color: 'black' },
31
+ 0x32: { group: 'supplyStatus', color: 'cyan' },
32
+ 0x33: { group: 'supplyStatus', color: 'magenta' },
33
+ 0x34: { group: 'supplyStatus', color: 'yellow' },
34
+ 0x41: { group: 'drum', color: 'black', percent: true },
35
+ 0x80: { group: 'drum', color: 'black', percent: true },
36
+ 0x79: { group: 'drum', color: 'cyan', percent: true },
37
+ 0x7a: { group: 'drum', color: 'magenta', percent: true },
38
+ 0x7b: { group: 'drum', color: 'yellow', percent: true },
39
+ 0x11: { group: 'drumPagesUsed', color: 'black' },
40
+ 0x7e: { group: 'drumPagesUsed', color: 'black' },
41
+ 0x73: { group: 'drumPagesUsed', color: 'cyan' },
42
+ 0x74: { group: 'drumPagesUsed', color: 'magenta' },
43
+ 0x75: { group: 'drumPagesUsed', color: 'yellow' },
44
+ 0x63: { group: 'misc', key: 'drumStatus' },
45
+ 0x69: { group: 'parts', key: 'belt', percent: true },
46
+ 0x6a: { group: 'parts', key: 'fuser', percent: true },
47
+ 0x6b: { group: 'parts', key: 'laser', percent: true },
48
+ 0x6c: { group: 'parts', key: 'paperFeedMP', percent: true },
49
+ 0x6d: { group: 'parts', key: 'paperFeed1', percent: true },
50
+ 0x85: { group: 'parts', key: 'inkWasteBox' },
19
51
  };
20
52
 
53
+ // Counter blob (brInfoCounter)
21
54
  const COUNTERS = {
22
- 0x00: { key: 'totalPages', scale: 1 },
23
- 0x01: { key: 'monoPages', scale: 1 },
24
- 0x06: { key: 'duplexPages', scale: 1 },
55
+ 0x00: 'totalPages',
56
+ 0x01: 'monoPages',
57
+ 0x02: 'colorPages',
58
+ 0x06: 'duplexPages',
25
59
  };
26
60
 
61
+ // Next-care blob (brInfoNextCare), laser only: pages left
27
62
  const NEXT_CARE = {
28
- 0x82: { key: 'drumPagesRemaining', scale: 1 },
63
+ 0x82: { group: 'drumPagesRemaining', color: 'black' },
64
+ 0xa4: { group: 'drumPagesRemaining', color: 'black' },
65
+ 0xa5: { group: 'drumPagesRemaining', color: 'cyan' },
66
+ 0xa6: { group: 'drumPagesRemaining', color: 'magenta' },
67
+ 0xa7: { group: 'drumPagesRemaining', color: 'yellow' },
68
+ 0x73: { group: 'partPagesRemaining', key: 'laser' },
69
+ 0x77: { group: 'partPagesRemaining', key: 'paperFeed1' },
70
+ 0x86: { group: 'partPagesRemaining', key: 'paperFeedMP' },
71
+ 0x88: { group: 'partPagesRemaining', key: 'belt' },
72
+ 0x89: { group: 'partPagesRemaining', key: 'fuser' },
29
73
  };
30
74
 
31
75
  function toBuffer(value) {
32
76
  if (value === null || value === undefined) { return null; }
33
77
  if (Buffer.isBuffer(value)) { return value; }
78
+ if (Array.isArray(value)) { return toBuffer(value.join('')); }
34
79
  if (typeof value === 'string') {
35
80
  const hex = value.replace(/[^0-9a-f]/gi, '');
36
81
  if (hex.length && hex.length % 2 === 0) { return Buffer.from(hex, 'hex'); }
@@ -38,7 +83,7 @@ function toBuffer(value) {
38
83
  return null;
39
84
  }
40
85
 
41
- /** Parse a Brother record blob into [{ code, value }] */
86
+ /** Parse a Brother record blob into [{ code, value, legacy }] */
42
87
  function parseRecords(input) {
43
88
  const buf = toBuffer(input);
44
89
  const records = [];
@@ -54,39 +99,142 @@ function parseRecords(input) {
54
99
  const end = start + len;
55
100
  if (end > buf.length || len === 0 || len > 6) { break; }
56
101
 
57
- let value = 0;
58
- for (let j = start; j < end; j++) { value = value * 256 + buf[j]; }
59
- records.push({ code, value });
102
+ if (len === 2) {
103
+ // Legacy format: [current][max]
104
+ const [cur, max] = [buf[start], buf[start + 1]];
105
+ if (max > 0) { records.push({ code, value: Math.round((cur / max) * 100), legacy: true, len }); }
106
+ } else {
107
+ let value = 0;
108
+ for (let j = start; j < end; j++) { value = value * 256 + buf[j]; }
109
+ records.push({ code, value, legacy: false, len });
110
+ }
60
111
  i = end;
61
112
  }
62
113
  return records;
63
114
  }
64
115
 
65
- function decodeWith(map, input) {
66
- const out = {};
116
+ // Percent records are hundredths of a % in 4-byte form; short records with a
117
+ // percent code (seen on old models) aren't levels, so they're skipped.
118
+ const pct = (rec, def) => {
119
+ if (!def.percent || rec.legacy) { return rec.value; }
120
+ return rec.len >= 4 ? Math.round(rec.value / 100) : null;
121
+ };
122
+ const finite = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
123
+
124
+ function emptySupplies() {
125
+ return Object.fromEntries(COLORS.map((c) => [c, { level: null, fine: null, status: null }]));
126
+ }
127
+
128
+ /** Decode the maintenance and next-care blobs */
129
+ function decodeMaintenance(maintenance, nextCare) {
130
+ const supplies = emptySupplies();
131
+ const drums = {};
132
+ const parts = {};
133
+ const misc = {};
67
134
  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;
135
+
136
+ for (const rec of parseRecords(maintenance)) {
137
+ if (rec.legacy) { misc.legacy = true; }
138
+ const def = MAINTENANCE[rec.code];
139
+ if (!def) {
140
+ unknown[`0x${rec.code.toString(16).padStart(2, '0')}`] = rec.value;
141
+ continue;
142
+ }
143
+ const v = pct(rec, def);
144
+ if (v === null) { continue; }
145
+ switch (def.group) {
146
+ case 'level':
147
+ supplies[def.color].level = v;
148
+ break;
149
+ case 'fine':
150
+ supplies[def.color].fine = v;
151
+ break;
152
+ case 'supplyStatus':
153
+ supplies[def.color].status = v;
154
+ break;
155
+ case 'drum':
156
+ (drums[def.color] = drums[def.color] || {}).percent = v;
157
+ break;
158
+ case 'drumPagesUsed':
159
+ (drums[def.color] = drums[def.color] || {}).pagesUsed = v;
160
+ break;
161
+ case 'parts':
162
+ (parts[def.key] = parts[def.key] || {}).percent = v;
163
+ break;
164
+ default:
165
+ misc[def.key] = v;
166
+ }
167
+ }
168
+
169
+ for (const rec of parseRecords(nextCare)) {
170
+ const def = NEXT_CARE[rec.code];
171
+ if (!def) { continue; }
172
+ if (def.group === 'drumPagesRemaining') {
173
+ (drums[def.color] = drums[def.color] || {}).pagesRemaining = rec.value;
72
174
  } else {
73
- unknown[`0x${code.toString(16).padStart(2, '0')}`] = value;
175
+ (parts[def.key] = parts[def.key] || {}).pagesRemaining = rec.value;
74
176
  }
75
177
  }
76
- if (Object.keys(unknown).length) { out.unknown = unknown; }
178
+
179
+ // Drum entries that only carry a page count aren't useful on their own
180
+ for (const [color, d] of Object.entries(drums)) {
181
+ if (d.percent === undefined && d.pagesRemaining === undefined) { delete drums[color]; }
182
+ }
183
+
184
+ return { supplies, drums, parts, misc, unknown };
185
+ }
186
+
187
+ function decodeCounters(input) {
188
+ const out = {};
189
+ for (const { code, value } of parseRecords(input)) {
190
+ if (COUNTERS[code]) { out[COUNTERS[code]] = value; }
191
+ }
77
192
  return out;
78
193
  }
79
194
 
80
- const decodeMaintenance = (input) => decodeWith(MAINTENANCE, input);
81
- const decodeCounters = (input) => decodeWith(COUNTERS, input);
82
- const decodeNextCare = (input) => decodeWith(NEXT_CARE, input);
195
+ /** prtLocalizationCharacterSet (IANA MIBenum) to a TextDecoder label */
196
+ const CHARSETS = { 3: 'ascii', 4: 'latin1', 5: 'iso-8859-2', 8: 'iso-8859-5', 12: 'iso-8859-9', 106: 'utf-8' };
83
197
 
84
- /** Decode an SNMP OctetString that holds ASCII text */
85
- function decodeText(input) {
198
+ /** Decode an SNMP OctetString that holds text */
199
+ function decodeText(input, charset) {
86
200
  const buf = toBuffer(input);
87
201
  if (!buf) { return typeof input === 'string' ? input.trim() : ''; }
202
+ let text;
203
+ try {
204
+ text = new TextDecoder(CHARSETS[charset] || 'latin1', { fatal: true }).decode(buf);
205
+ } catch {
206
+ text = buf.toString('latin1');
207
+ }
88
208
  // eslint-disable-next-line no-control-regex
89
- return buf.toString('latin1').replace(/[\x00-\x1f]+/g, ' ').trim();
209
+ return text.replace(/[\x00-\x1f]+/g, ' ').replace(/\s+/g, ' ').trim();
210
+ }
211
+
212
+ /** Model from the PJL device ID, e.g. "MFG:Brother;CMD:PJL;MDL:DCP-L3550CDW;CLS:PRINTER;" */
213
+ function modelFromDeviceId(text) {
214
+ const m = /MDL:([^;]+)/.exec(text || '');
215
+ return m ? m[1].trim() : null;
216
+ }
217
+
218
+ /** "laser" or "ink", from what the printer reports */
219
+ function printerType(model, decoded, deviceId) {
220
+ if (decoded && decoded.parts.inkWasteBox) { return 'ink'; }
221
+ if (/CID:[^;]*Laser/i.test(deviceId || '')) { return 'laser'; }
222
+ if (/\b(?:DCP|MFC|HL)-[JT]/i.test(model || '')) { return 'ink'; }
223
+ // The current/max record format is only used by older inkjets
224
+ if (decoded && decoded.misc.legacy) { return 'ink'; }
225
+ return 'laser';
226
+ }
227
+
228
+ /** One entry per supply the printer reports a level for */
229
+ function supplyList(supplies) {
230
+ const list = [];
231
+ for (const color of COLORS) {
232
+ const s = supplies[color];
233
+ const level = finite(s.level) ?? finite(s.fine);
234
+ if (level === null) { continue; }
235
+ list.push({ color, level: Math.max(0, Math.min(100, level)), fine: finite(s.fine) });
236
+ }
237
+ return list;
90
238
  }
91
239
 
92
240
  /** hrPrinterDetectedErrorState bit names (RFC 3805 / RFC 2790) */
@@ -109,12 +257,14 @@ function decodeErrorState(input) {
109
257
  return errors;
110
258
  }
111
259
 
112
- /** Errors that stop the printer and deserve a HomeKit fault badge */
260
+ /** Errors that stop the printer and deserve the Problem sensor */
113
261
  const FAULT_ERRORS = new Set([
114
262
  'noPaper', 'noToner', 'doorOpen', 'jammed', 'serviceRequested',
115
263
  'inputTrayMissing', 'outputTrayMissing', 'markerSupplyMissing', 'outputFull',
116
264
  ]);
117
265
 
266
+ // Display text is in the printer's language; English patterns are only a
267
+ // fallback for printers that don't set the error bits.
118
268
  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
269
  const WARNING_TEXT = /\blow\b|end soon|soon/i;
120
270
  const PRINTING_TEXT = /printing|receiving|copying/i;
@@ -135,12 +285,15 @@ function summarizeStatus({ statusText = '', printerStatus = null, errors = [] })
135
285
  }
136
286
 
137
287
  module.exports = {
288
+ COLORS,
138
289
  parseRecords,
139
290
  decodeMaintenance,
140
291
  decodeCounters,
141
- decodeNextCare,
142
292
  decodeText,
143
293
  decodeErrorState,
294
+ modelFromDeviceId,
295
+ printerType,
296
+ supplyList,
144
297
  summarizeStatus,
145
298
  toBuffer,
146
299
  };
package/lib/snmp.js CHANGED
@@ -8,88 +8,145 @@ const OID = {
8
8
  counters: '1.3.6.1.4.1.2435.2.3.9.4.2.1.5.5.10.0', // brInfoCounter
9
9
  nextCare: '1.3.6.1.4.1.2435.2.3.9.4.2.1.5.5.11.0', // brInfoNextCare
10
10
  statusText: '1.3.6.1.4.1.2435.2.3.9.4.2.1.5.4.5.2.0', // LCD status line
11
+ deviceId: '1.3.6.1.4.1.2435.2.3.9.1.1.7.0', // PJL device ID (MDL:...)
12
+ brSerial: '1.3.6.1.4.1.2435.2.3.9.4.2.1.5.5.1.0', // brInfoSerialNumber
11
13
  model: '1.3.6.1.2.1.25.3.2.1.3.1', // hrDeviceDescr
12
14
  serial: '1.3.6.1.2.1.43.5.1.1.17.1', // prtGeneralSerialNumber
15
+ charset: '1.3.6.1.2.1.43.7.1.1.4.1.1', // prtLocalizationCharacterSet
16
+ pageCount: '1.3.6.1.2.1.43.10.2.1.4.1.1', // prtMarkerLifeCount
13
17
  printerStatus: '1.3.6.1.2.1.25.3.5.1.1.1', // hrPrinterStatus
14
18
  errorState: '1.3.6.1.2.1.25.3.5.1.2.1', // hrPrinterDetectedErrorState
15
19
  };
16
20
 
17
21
  const NAMES = Object.keys(OID);
22
+ const VERSIONS = { '2c': snmp.Version2c, 1: snmp.Version1 };
23
+
24
+ function get(session, oids) {
25
+ return new Promise((resolve, reject) => {
26
+ session.get(oids, (err, varbinds) => (err ? reject(err) : resolve(varbinds)));
27
+ });
28
+ }
18
29
 
19
30
  /**
20
- * Query the printer once and return decoded values.
21
- * Rejects only when the printer can't be reached at all.
31
+ * One request. Under SNMP v1 an OID the printer doesn't have fails the whole
32
+ * request (noSuchName), so that OID is dropped and the request repeated.
22
33
  */
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;
34
+ async function getAll(options, version) {
35
+ const session = snmp.createSession(options.host, options.community || 'public', {
36
+ port: options.port || 161,
37
+ version: VERSIONS[version],
38
+ timeout: options.timeout ?? 5000,
39
+ retries: options.retries ?? 1,
40
+ idBitsSize: 32,
41
+ });
42
+ session.on('error', () => { /* surfaced through the request callback */ });
43
+
44
+ const names = [...NAMES];
45
+ const raw = {};
46
+ try {
47
+ while (names.length) {
48
+ try {
49
+ const varbinds = await get(session, names.map((n) => OID[n]));
50
+ varbinds.forEach((vb, idx) => {
51
+ raw[names[idx]] = snmp.isVarbindError(vb) ? null : vb.value;
52
+ });
53
+ return raw;
54
+ } catch (err) {
55
+ const missing = err && err.name === 'RequestFailedError' && /NoSuchName: ([\d.]+)/.exec(err.message);
56
+ const idx = missing ? names.findIndex((n) => OID[n] === missing[1]) : -1;
57
+ if (idx < 0) { throw err; }
58
+ raw[names[idx]] = null;
59
+ names.splice(idx, 1);
60
+ }
37
61
  }
62
+ return raw;
63
+ } finally {
64
+ try { session.close(); } catch { /* already closed */ }
65
+ }
66
+ }
38
67
 
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
- };
68
+ /**
69
+ * Query the printer once and return decoded values. Rejects only when the
70
+ * printer can't be reached at all.
71
+ *
72
+ * options.version: '2c', '1' or 'auto' (default). With 'auto', v2c is tried
73
+ * first and v1 when v2c gets no answer; options.state remembers which worked.
74
+ */
75
+ async function query(options) {
76
+ const state = options.state || {};
77
+ const wanted = options.version && options.version !== 'auto' ? [String(options.version)] : null;
78
+ const order = wanted || (state.version ? [state.version] : ['2c', '1']);
46
79
 
47
- session.on('error', (err) => finish(err));
80
+ let lastErr;
81
+ for (const version of order) {
82
+ try {
83
+ const raw = await getAll(options, version);
84
+ state.version = version;
85
+ return { ...parse(raw), snmpVersion: version };
86
+ } catch (err) {
87
+ lastErr = err;
88
+ }
89
+ }
90
+ throw lastErr;
91
+ }
48
92
 
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
- });
93
+ /** Some inkjets only report mono and color page counts */
94
+ function sumPages(c) {
95
+ return typeof c.monoPages === 'number' && typeof c.colorPages === 'number' ? c.monoPages + c.colorPages : null;
61
96
  }
62
97
 
63
98
  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);
99
+ const charset = typeof raw.charset === 'number' ? raw.charset : Number(decode.decodeText(raw.charset)) || null;
100
+ const statusText = decode.decodeText(raw.statusText, charset);
68
101
  const printerStatus = typeof raw.printerStatus === 'number' ? raw.printerStatus : null;
69
102
  const errors = decode.decodeErrorState(raw.errorState);
70
103
 
104
+ const deviceId = decode.decodeText(raw.deviceId);
105
+ const model = decode.decodeText(raw.model) || decode.modelFromDeviceId(deviceId) || '';
106
+ const maint = decode.decodeMaintenance(raw.maintenance, raw.nextCare);
107
+ const counters = decode.decodeCounters(raw.counters);
108
+ const supplies = decode.supplyList(maint.supplies);
109
+ const type = decode.printerType(model, maint, deviceId);
110
+ const pageCount = typeof raw.pageCount === 'number' ? raw.pageCount : null;
111
+
112
+ // Inkjets have no drum; their 0x41 record means something else
113
+ if (type === 'ink') { maint.drums = {}; }
114
+
115
+ // Lowest supply; when coarse levels tie (they move in 10% steps), the finer
116
+ // reading decides, so a 2% yellow beats a 10% cyan
117
+ const rank = (s) => [s.level, s.fine ?? s.level];
118
+ const lowest = supplies.length
119
+ ? supplies.reduce((a, b) => {
120
+ const [al, af] = rank(a);
121
+ const [bl, bf] = rank(b);
122
+ return bl < al || (bl === al && bf < af) ? b : a;
123
+ })
124
+ : null;
125
+ const black = maint.drums.black || {};
126
+
71
127
  return {
72
- model: decode.decodeText(raw.model) || null,
73
- serial: decode.decodeText(raw.serial) || null,
128
+ model: model || null,
129
+ serial: decode.decodeText(raw.serial) || decode.decodeText(raw.brSerial) || null,
130
+ type,
74
131
  statusText,
75
132
  printerStatus,
76
133
  errors,
77
134
  ...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
- },
135
+ supplies,
136
+ lowestSupply: lowest,
137
+ drums: maint.drums,
138
+ parts: maint.parts,
139
+ totalPages: counters.totalPages ?? pageCount ?? sumPages(counters),
140
+ colorPages: counters.colorPages ?? null,
141
+ duplexPages: counters.duplexPages ?? null,
142
+ // Kept for the mono-laser view and the probe
143
+ tonerPercent: supplies.find((s) => s.color === 'black')?.level ?? null,
144
+ tonerPercentFine: supplies.find((s) => s.color === 'black')?.fine ?? null,
145
+ drumPercent: black.percent ?? null,
146
+ drumPagesUsed: black.pagesUsed ?? null,
147
+ drumPagesRemaining: black.pagesRemaining ?? null,
148
+ unknown: maint.unknown,
90
149
  };
91
150
  }
92
151
 
93
- const pick = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
94
-
95
152
  module.exports = { query, parse, OID };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "homebridge-brother-printer",
3
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.",
4
+ "version": "0.2.1",
5
+ "description": "Brother laser and inkjet printers in HomeKit: printing state, problem alerts and toner or ink levels, read locally over SNMP.",
6
6
  "author": "Manuel Zamfir",
7
7
  "license": "MIT",
8
8
  "homepage": "https://github.com/zmanuel1234/homebridge-brother-printer#readme",
@@ -33,11 +33,14 @@
33
33
  "keywords": [
34
34
  "homebridge-plugin",
35
35
  "homebridge",
36
+ "homekit",
36
37
  "brother",
37
38
  "printer",
39
+ "laser",
40
+ "inkjet",
38
41
  "toner",
39
- "snmp",
40
- "homekit"
42
+ "ink",
43
+ "snmp"
41
44
  ],
42
45
  "engines": {
43
46
  "node": "^18.20.0 || ^20.15.0 || ^22.0.0 || ^24.0.0",