optolink-bridge 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  This file documents all *major & minor* releases. For revisions, please consult the [commit history](https://github.com/kristian/optolink-bridge/commits/main).
4
4
 
5
+ ## [1.5] - 2026-11-29
6
+
7
+ Switch VS2 packet parsing and encoding to `binary-parser-codec` and upgrade configuration file watching to Chokidar 6. The bridge now rejects VS2 frames whose declared length differs from their payload length.
8
+
5
9
  ## [1.4] 2026-06-14
6
10
 
7
11
  Upgrade to Node.js 24 and bump dependencies.
package/config.toml CHANGED
@@ -22,7 +22,7 @@ data_points = [
22
22
  # "vdatetime" for Viessmann specific date and time values
23
23
  # "unixtime" for unix timestamps
24
24
  # "utf8" for utf8 encoded strings
25
- # or any data types supported by binary-parser (e.g. uint16)
25
+ # or an explicit numeric type such as uint16, int32be or floatle
26
26
  # note that byte-bit filters are *not* yet supported
27
27
  # scale: a factor to scale the numeric value by, e.g. 0.1 to convert 100 to 10.0
28
28
  # if type is set to a number, the data point is treated as a integer matching the size of the data (e.g. (u)int16
package/index.js CHANGED
@@ -85,6 +85,10 @@ async function applyConfig(config) {
85
85
  const device = config.mqtt?.device_discovery?.overrides?.device;
86
86
  deviceSerialNo = device?.serial_number || device?.identifiers || deviceSerialNo;
87
87
  Array.isArray(deviceSerialNo) && (deviceSerialNo = deviceSerialNo[0]);
88
+
89
+ if (deviceSerialNo) {
90
+ logger.warn('No device serial number set in the config.toml, device discovery will be deferred until Vitoconnect sends it')
91
+ }
88
92
  }
89
93
 
90
94
  deviceDiscoveryOptions = config.mqtt?.device_discovery;
@@ -105,7 +109,10 @@ let mqttClient, mqttTopic, mqttAvailabilityTopic, mqttDpTopic = dp => {
105
109
  };
106
110
 
107
111
  deviceDiscovery = async function(options = (deviceDiscoveryOptions ?? { enabled: true })) {
108
- if (!mqttClient?.connected || !deviceSerialNo || !(options?.enabled ?? true)) {
112
+ if (!mqttClient?.connected || !deviceSerialNo) {
113
+ return;
114
+ } else if (!(options?.enabled ?? true)) {
115
+ logger.warn('Device discovery is disabled in the config.toml');
109
116
  return;
110
117
  }
111
118
 
@@ -156,7 +163,9 @@ if (config.mqtt && config.mqtt.url) {
156
163
  };
157
164
 
158
165
  // connect to MQTT broker
166
+ logger.info('Connecting to MQTT broker and waiting for connection...');
159
167
  mqttClient = await mqttConnect(config.mqtt.url, mqttOptions);
168
+ logger.info('MQTT connected, proceeding with publishing online topic / device discovery');
160
169
  const mqttConnected = async () => {
161
170
  config.mqtt.online && await mqttClient.publishAsync(
162
171
  mqttAvailabilityTopic, `${true}`, { retain: true });
@@ -216,6 +225,7 @@ const packetQueue = async.queue(async task => {
216
225
  // we wait for the serial number to be sent by Vitoconnect (0xF010) and then publish the discovery message
217
226
  if (!deviceSerialNo && packet.addr === 0xF010 && (config.mqtt?.device_discovery?.enabled ?? true)) {
218
227
  deviceSerialNo = parseValue('string', packet.data)?.trim?.();
228
+ logger.info(`Device serial number received from Vitoconnect: ${deviceSerialNo}`);
219
229
  await deviceDiscovery();
220
230
  }
221
231
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "optolink-bridge",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Safely bridge the Optolink bus of your Viessmann heating system and publish attributes via MQTT + Home Assistant Device Discovery",
5
5
  "keywords": [
6
6
  "viessmann",
@@ -50,13 +50,13 @@
50
50
  "license": "Apache-2.0",
51
51
  "dependencies": {
52
52
  "async": "^3.2.6",
53
- "binary-parser-encoder-bump": "^2.2.1",
53
+ "binary-parser-codec": "^1.0.1",
54
54
  "buffer-to-str": "^1.0.0",
55
55
  "change-case": "^5.4.4",
56
- "chokidar": "^5.0.0",
57
- "mqtt": "^5.15.2",
56
+ "chokidar": "^6.0.0",
57
+ "mqtt": "^5.16.1",
58
58
  "serialport": "^13.0.0",
59
- "smol-toml": "^1.8.0",
59
+ "smol-toml": "^1.9.1",
60
60
  "yocto-queue": "^1.2.2"
61
61
  },
62
62
  "packageManager": "yarn@4.12.0"
package/parse_vs2.js CHANGED
@@ -1,180 +1,113 @@
1
1
  import { Buffer } from 'node:buffer';
2
- import { Parser } from 'binary-parser-encoder-bump';
2
+ import { Parser } from 'binary-parser-codec';
3
3
 
4
- function crc256(data, crc = 0) {
5
- for (const byte of data) {
6
- crc += byte;
7
- crc %= 0x100;
4
+ // The checksum covers the length byte and the payload, excluding the start byte.
5
+ function checksum(payload, length) {
6
+ if (payload.length !== length) {
7
+ throw new Error(`Expected VS2 payload length ${length}, got ${payload.length}`);
8
8
  }
9
- return crc;
10
- }
11
-
12
- function when({ tag, type }) {
13
- return {
14
- tag: function() {
15
- return tag.apply(this) ? 1 : 0;
16
- },
17
- defaultChoice: new Parser(), // nothing
18
- choices: {
19
- 1: type
20
- }
9
+ let sum = length;
10
+ for (const byte of payload) {
11
+ sum += byte;
21
12
  }
22
- }
23
-
24
- function assertFunction(text, fn) {
25
- const textFunction = function() {
26
- return fn.apply(this, arguments);
27
- };
28
- textFunction.toString = () => text;
29
- return textFunction;
30
- }
31
-
32
- /**
33
- * @returns a function that can be used for readUntil, to only peek a single byte (if any)
34
- */
35
- function peek() {
36
- return function() {
37
- if (!this.peeked) {
38
- this.peeked = true;
39
- return false;
40
- } else {
41
- delete this.peeked;
42
- return true;
43
- }
44
- };
13
+ return sum & 0xff;
45
14
  }
46
15
 
47
16
  const parser = new Parser()
48
- .useContextVars()
49
17
  .uint8('start')
50
18
  .choice({
51
19
  tag: 'start',
52
20
  choices: {
53
21
  0x04: new Parser(), // EOT (end of transmission / sync. start)
54
- 0x16: new Parser() // SYN (synchronous idle / start of transmission)
55
- .uint16('zero', {
56
- assert: assertFunction('not matching the expected 16 00 00 start sequence', function(zero) {
57
- return !zero; // has to start with 16 00 00 (zero!)
58
- })
59
- }),
22
+ 0x16: new Parser().uint16('zero', { assert: 0 }), // SYN (16 00 00)
60
23
  0x41: new Parser() // VS2_DAP_STANDARD (packet start)
61
24
  .uint8('len')
62
- .saveOffset('crc')
63
- .pointer('raw', {
64
- offset: 'crc',
65
- type: new Parser()
66
- .buffer('hoist', { length: '$parent.len' }),
67
- formatter: struct => struct.hoist
68
- })
69
25
  .bit4('unused')
70
- .bit4('id')
71
- .choice({
72
- tag: 'id',
73
- choices: {
74
- 0x0: new Parser(), // REQ
75
- 0x1: new Parser(), // RESP
76
- 0x2: new Parser(), // UNACK
77
- 0x3: new Parser() // ERRMSG
78
- }
79
- })
26
+ .bit4('id', { assert: id => id <= 3 }) // REQ, RESP, UNACK, ERRMSG
80
27
  .bit3('seq')
81
- .bit5('fn')
28
+ .bit5('fn', { assert: fn => [0x01, 0x02, 0x07].includes(fn) })
29
+ .uint16be('addr') // addresses are big-endian, values are little-endian
30
+ .uint8('dlen')
82
31
  .choice({
83
- tag: 'fn',
32
+ tag() {
33
+ // Read responses, write requests, RPCs and errors carry data.
34
+ return Number((this.fn === 0x01 && this.id === 0x1) ||
35
+ (this.fn === 0x02 && this.id === 0x0) || this.fn === 0x07 || this.id === 0x3);
36
+ },
84
37
  choices: {
85
- 0x01: new Parser(), // Virtual_READ
86
- 0x02: new Parser(), // Virtual_WRITE
87
- 0x07: new Parser() // Remote_Procedure_Call
38
+ 0: new Parser(),
39
+ 1: new Parser().buffer('data', { length: 'dlen' })
88
40
  }
89
41
  })
90
- .uint16be('addr') // addresses are specified in big-endian, while values are little-endian
91
- .uint8('dlen') // data length
92
- .choice(when({
93
- tag: function() {
94
- // when reading (fn = 0x01) grab data from the response (id = 0x1), when writing (fn = 0x02) from the request (id = 0x0),
95
- // for rpcs (fn = 0x07) it is function input & output (so both req / res have data), for errors (0x3) the data is err. msg
96
- return (this.fn === 0x01 && this.id === 0x1) || (this.fn === 0x02 && this.id === 0x0) || (this.fn === 0x07) || (this.id === 0x3);
97
- },
98
- type: new Parser()
99
- .buffer('data', { length: 'dlen' })
100
- }))
101
42
  .uint8('crc', {
102
- type: 'uint8',
103
- assert: assertFunction('a mismatch to the calculated CRC', function(crc) {
104
- // if raw is not set / empty, we are in the encoding case, CRC will be calculated in the encode function
105
- return !this.raw?.length || crc256(this.raw, this.len) === crc;
106
- })
107
- })
108
- .buffer('rest', {
109
- readUntil: 'eof'
43
+ encoder(value, context) {
44
+ return checksum(context.slice(2), this.len);
45
+ }
110
46
  })
47
+ .buffer('rest', { readUntil: 'eof' })
111
48
  }
112
49
  });
113
50
 
51
+ // ENQ, ACK or NACK. Only an ACK can prefix another frame.
114
52
  const responseParser = new Parser()
115
- .useContextVars()
116
- .uint8('res')
117
- .choice({
118
- tag: 'res',
119
- choices: {
120
- 0x05: new Parser(), // ENQ (enquiry / sync. end)
121
- 0x06: new Parser() // ACK
122
- .saveOffset('peek')
123
- .pointer('peek', { // corner case: during the handshake, single ACK (0x06) without any data, so peek for one byte
124
- offset: 'peek',
125
- type: new Parser()
126
- .buffer('hoist', {
127
- readUntil: peek(),
128
- encoder: function() {
129
- return Buffer.from(this.start ? [0xFF] : []);
130
- }
131
- }),
132
- formatter: struct => struct.hoist
133
- })
134
- .choice({
135
- tag: 'peek.length',
136
- defaultChoice: parser,
137
- choices: {
138
- 0: new Parser()
139
- }
140
- }),
141
- 0x15: new Parser() // NACK
142
- }
143
- });
53
+ .uint8('res', { assert: res => [0x05, 0x06, 0x15].includes(res) });
144
54
 
145
55
  /**
146
56
  * Parse the VS2 / 300 Optolink protocol packet.
147
- *
57
+ *
148
58
  * @param {Buffer} data the data of the packet to parse
149
59
  * @param {boolean} [response] true in case it was a response (Optolink -> Vitoconnect) packet
150
60
  * @returns {object} the parsed data packet
151
61
  */
152
62
  export function parsePacket(data, response) {
153
- return (response ? responseParser : parser).parse(data);
63
+ if (response) {
64
+ const header = responseParser.parse(data);
65
+ if (header.res === 0x06) {
66
+ header.peek = data.subarray(1, 2);
67
+ if (header.peek.length) {
68
+ Object.assign(header, parsePacket(data.subarray(1)));
69
+ }
70
+ }
71
+ return header;
72
+ }
73
+
74
+ const packet = parser.parse(data);
75
+ if (packet.start === 0x41) {
76
+ packet.raw = data.subarray(2, data.length - packet.rest.length - 1);
77
+ if (checksum(packet.raw, packet.len) !== packet.crc) {
78
+ throw new Error('VS2 packet CRC mismatch');
79
+ }
80
+ }
81
+ return packet;
154
82
  }
155
83
 
156
84
  // make parsing the default
157
85
  export default parsePacket;
158
86
 
159
- const emptyBuffer = Buffer.allocUnsafe(0);
87
+ const emptyBuffer = Buffer.alloc(0);
160
88
  export function encodePacket(packet, response) {
161
- const data = (response ? responseParser : parser).encode(Object.assign({}, packet, {
162
- peek: 'start' in packet || 'zero' in packet ? Buffer.from([0xFF]) : emptyBuffer,
89
+ if (response) {
90
+ const header = responseParser.serialize(packet);
91
+ return packet.res === 0x06 && ('start' in packet || 'zero' in packet)
92
+ ? Buffer.concat([header, encodePacket(packet)])
93
+ : Buffer.from(header);
94
+ }
95
+
96
+ const dataLength = packet.data?.length ?? 0;
97
+ return Buffer.from(parser.serialize({
98
+ ...packet,
99
+ zero: packet.zero ?? 0,
163
100
  unused: packet.unused ?? 0,
164
- len: packet.len ?? ((packet.data ? packet.data.length : 0) + /* 1/2 unused, 1/2 id, 3/8 seq, 5/8 fn, 2x addr, dlen */ 5),
165
- dlen: packet.dlen ?? (packet.data ? packet.data.length : 0),
166
- raw: emptyBuffer,
167
- rest: emptyBuffer,
168
- crc: 0
101
+ seq: packet.seq ?? 0,
102
+ addr: packet.addr ?? 0,
103
+ len: packet.len ?? 5 + dataLength, // id, function, address (2 bytes), data length
104
+ dlen: packet.dlen ?? dataLength,
105
+ rest: emptyBuffer
169
106
  }));
170
-
171
- return packet.start === 0x41 ? Buffer.concat([data.subarray(0, data.length - 1), Buffer.from([
172
- crc256(data.subarray(/* start byte */ 1 + (response ? /* res byte */ 1 : 0), data.length - /* crc byte */ 1))
173
- ])]) : data;
174
107
  }
175
108
 
176
109
  /**
177
- * All types supported by binary-parser
110
+ * Data point types supported by the bridge
178
111
  */
179
112
  export const types = Object.fromEntries([
180
113
  'uint8', 'int8',
@@ -196,7 +129,7 @@ const valueParser = new Parser()
196
129
  tag: 'type',
197
130
  choices: Object.fromEntries(Object.keys(types).map((type, index) => [
198
131
  index, (() => {
199
- const parser = new Parser().endianess('little');
132
+ const parser = new Parser().endianness('little');
200
133
 
201
134
  let options;
202
135
  if (type === 'string') {
@@ -214,7 +147,7 @@ const valueParser = new Parser()
214
147
  /**
215
148
  * Parses the given value of the specified type.
216
149
  *
217
- * @param {string} [type] the type to parse, one of `types` / all supported types of binary-parser, or 'debug' for all possible types
150
+ * @param {string} [type] a data point type or alias, or 'debug' for all types matching the data length
218
151
  * @param {Buffer} data the data to parse for the given type
219
152
  * @returns {(any|object)} the parsed value, or in case no type was given, an object of all possible types matching the types length (fuzzy, types that are one byte short [e.g. int8 + status byte] will also match, ignoring the last byte of data)
220
153
  */
package/utils.js CHANGED
@@ -42,8 +42,7 @@ export async function readConfig(watchCallback) {
42
42
  if (typeof watchCallback === 'function') {
43
43
  watch(configFile, {
44
44
  awaitWriteFinish: true,
45
- persistent: false, // do not keep the process running
46
- encoding: 'utf8'
45
+ persistent: false // do not keep the process running
47
46
  }).on('change', async () => {
48
47
  await watchCallback(await readConfig());
49
48
  });