@nexgen-os/sunspec 0.0.0-stage → 0.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/dist/index.js ADDED
@@ -0,0 +1,352 @@
1
+ // SunSpec Modbus, read into plain shapes and written back.
2
+ //
3
+ // A SunSpec device (an inverter, a meter, a battery, a tracker…) exposes its
4
+ // registers as a chain of information models after the marker "SunS", at
5
+ // one of the base addresses 40000, 50000 or 0: each model starts with its
6
+ // id and its length in registers, and the chain ends with the id 0xFFFF.
7
+ // What each register of a model holds — its name, type, scale factor,
8
+ // units, whether it may be written — is said by the model definitions the
9
+ // SunSpec Alliance publishes (src/models.ts, Apache-2.0).
10
+ //
11
+ // Everything here is a pure function on 16-bit registers: no Modbus
12
+ // connection, no clock, no database. A value is read in the units the model
13
+ // says, scaled by its scale factor as SunSpec defines (value = raw x 10^sf);
14
+ // a register the device does not implement reads as null.
15
+ import { MODELS } from './models.js';
16
+ export { MODELS };
17
+ /** The definition of a model by its id, among the published ones or the caller's. */
18
+ export function modelDefinition(id, definitions = MODELS) {
19
+ return definitions.find((m) => m.id === id) ?? null;
20
+ }
21
+ // ---------------------------------------------------------------------------
22
+ // The map of a device: "SunS", then models until 0xFFFF
23
+ // ---------------------------------------------------------------------------
24
+ /** "SunS" in two registers, at the base address of every SunSpec device. */
25
+ export const SUNS_MARKER = [0x5375, 0x6e53];
26
+ /** Where a device may start its map, in the order a client looks. */
27
+ export const BASE_ADDRESSES = [40000, 50000, 0];
28
+ export const END_MODEL_ID = 0xffff;
29
+ /**
30
+ * Cuts the registers read from a base address — "SunS" first — into the
31
+ * models they hold, up to the end model. Refuses `suns_missing` when the
32
+ * marker is not there, and `map_truncated`, with the address to read up to,
33
+ * when the chain runs past the registers given.
34
+ */
35
+ export function readModelBlocks(registers, baseAddress = 40000) {
36
+ if (registers[0] !== SUNS_MARKER[0] || registers[1] !== SUNS_MARKER[1]) {
37
+ throw new Error(`suns_missing: no "SunS" marker at address ${baseAddress}`);
38
+ }
39
+ const blocks = [];
40
+ let i = 2;
41
+ for (;;) {
42
+ if (i + 2 > registers.length)
43
+ throw truncated(baseAddress + i + 2);
44
+ const id = registers[i];
45
+ const length = registers[i + 1];
46
+ if (id === END_MODEL_ID)
47
+ return blocks;
48
+ if (i + 2 + length > registers.length)
49
+ throw truncated(baseAddress + i + 2 + length);
50
+ blocks.push({ id, address: baseAddress + i, length, registers: registers.slice(i, i + 2 + length) });
51
+ i += 2 + length;
52
+ }
53
+ }
54
+ const truncated = (address) => new Error(`map_truncated: the map goes on past the registers given; read up to address ${address}`);
55
+ /**
56
+ * Reads a model from its block. Refuses `model_unknown` when no definition
57
+ * has its id, and `model_length_invalid` when its length does not hold its
58
+ * points and whole repeating groups.
59
+ */
60
+ export function readModel(block, definitions = MODELS) {
61
+ const def = modelDefinition(block.id, definitions);
62
+ if (!def)
63
+ throw new Error(`model_unknown: no definition of model ${block.id}`);
64
+ const reader = new Reader(block, def);
65
+ const group = reader.group(def.group, 0, [], block.length + 2);
66
+ if (reader.end !== block.length + 2) {
67
+ throw new Error(`model_length_invalid: model ${block.id} at ${block.address} says ${block.length} registers, its points take ${reader.end - 2}`);
68
+ }
69
+ return { id: def.id, label: def.group.label ?? null, address: block.address, length: block.length, ...group };
70
+ }
71
+ /** Every model of a device from the registers read from its base address. */
72
+ export function readDevice(registers, baseAddress = 40000, definitions = MODELS) {
73
+ const out = { models: [], unknown: [] };
74
+ for (const block of readModelBlocks(registers, baseAddress)) {
75
+ if (modelDefinition(block.id, definitions))
76
+ out.models.push(readModel(block, definitions));
77
+ else
78
+ out.unknown.push(block);
79
+ }
80
+ return out;
81
+ }
82
+ /** A point of a model by its path: `W`, `module[2].DCW`, `Crv[1].Pt[3].V` (repeats counted from 1). */
83
+ export function pointOf(model, path) {
84
+ let group = model;
85
+ const parts = path.split('.');
86
+ for (const part of parts.slice(0, -1)) {
87
+ const m = /^([^[\]]+)(?:\[(\d+)\])?$/.exec(part);
88
+ const list = m ? group.groups[m[1]] : undefined;
89
+ const next = list?.[(m?.[2] ? Number(m[2]) : 1) - 1];
90
+ if (!next)
91
+ return null;
92
+ group = next;
93
+ }
94
+ return group.points[parts[parts.length - 1]] ?? null;
95
+ }
96
+ class Reader {
97
+ block;
98
+ def;
99
+ end = 0;
100
+ constructor(block, def) {
101
+ this.block = block;
102
+ this.def = def;
103
+ }
104
+ /** Reads a group at an offset; `scope` holds the groups around it, the closest last. */
105
+ group(def, offset, scope, modelEnd) {
106
+ const out = { name: def.name, points: {}, groups: {} };
107
+ const chain = [...scope, out];
108
+ let at = offset;
109
+ for (const p of def.points) {
110
+ if (p.type !== 'pad')
111
+ out.points[p.name] = this.point(p, at);
112
+ at += p.size;
113
+ }
114
+ // Scale factors first known once every point of the group is read.
115
+ for (const p of def.points)
116
+ if (p.type !== 'pad' && p.sf !== undefined)
117
+ scale(out.points[p.name], p, chain);
118
+ for (const g of def.groups ?? []) {
119
+ const n = this.count(g, chain, modelEnd - at);
120
+ const list = [];
121
+ for (let k = 0; k < n; k++) {
122
+ const entry = this.group(g, at, chain, modelEnd);
123
+ at = this.end;
124
+ list.push(entry);
125
+ }
126
+ out.groups[g.name] = list;
127
+ }
128
+ this.end = at;
129
+ return out;
130
+ }
131
+ count(def, chain, left) {
132
+ if (def.count === undefined)
133
+ return 1;
134
+ if (typeof def.count === 'string') {
135
+ const holder = find(chain, def.count);
136
+ const n = holder?.raw;
137
+ if (typeof n !== 'number')
138
+ throw new Error(`model_length_invalid: model ${this.def.id} counts ${def.name} by ${def.count}, which it does not implement`);
139
+ return n;
140
+ }
141
+ if (def.count > 0)
142
+ return def.count;
143
+ // 0: as many as the model's length leaves room for.
144
+ const size = groupSize(def);
145
+ if (size === null || size === 0)
146
+ throw new Error(`model_unknown: model ${this.def.id} repeats ${def.name}, whose size depends on its data`);
147
+ if (left % size !== 0)
148
+ throw new Error(`model_length_invalid: model ${this.def.id} at ${this.block.address} leaves ${left} registers for groups of ${size}`);
149
+ return left / size;
150
+ }
151
+ point(p, at) {
152
+ const regs = this.block.registers.slice(at, at + p.size);
153
+ if (regs.length < p.size)
154
+ throw new Error(`model_length_invalid: model ${this.def.id} at ${this.block.address} ends before ${p.name}`);
155
+ const raw = decode(p, regs);
156
+ const symbols = p.symbols ?? [];
157
+ const isEnum = p.type.startsWith('enum');
158
+ const isBits = p.type.startsWith('bitfield');
159
+ return {
160
+ name: p.name,
161
+ type: p.type,
162
+ address: this.block.address + at,
163
+ size: p.size,
164
+ raw,
165
+ value: raw,
166
+ sf: null,
167
+ units: p.units ?? null,
168
+ symbol: isEnum && raw !== null ? symbols.find((s) => s.value === Number(raw))?.name ?? null : null,
169
+ flags: isBits && raw !== null ? symbols.filter((s) => (BigInt(raw) >> BigInt(s.value)) & 1n).map((s) => s.name) : [],
170
+ writable: p.access === 'RW',
171
+ };
172
+ }
173
+ }
174
+ function find(chain, name) {
175
+ for (let i = chain.length - 1; i >= 0; i--) {
176
+ const p = chain[i].points[name];
177
+ if (p)
178
+ return p;
179
+ }
180
+ return null;
181
+ }
182
+ function scale(point, def, chain) {
183
+ let sf;
184
+ if (typeof def.sf === 'number')
185
+ sf = def.sf;
186
+ else {
187
+ const holder = find(chain, def.sf);
188
+ sf = typeof holder?.raw === 'number' ? holder.raw : null;
189
+ }
190
+ point.sf = sf;
191
+ if (point.raw === null)
192
+ return;
193
+ point.value = sf === null ? null : applyScale(point.raw, sf);
194
+ }
195
+ function applyScale(raw, sf) {
196
+ if (typeof raw === 'bigint')
197
+ raw = Number(raw);
198
+ if (typeof raw !== 'number' || sf === 0)
199
+ return raw;
200
+ return sf > 0 ? raw * 10 ** sf : Number((raw * 10 ** sf).toFixed(-sf));
201
+ }
202
+ /** Size of a group in registers, or null when it holds a repeat counted by its data. */
203
+ function groupSize(def) {
204
+ let size = def.points.reduce((s, p) => s + p.size, 0);
205
+ for (const g of def.groups ?? []) {
206
+ if (g.count !== undefined && g.count !== 1)
207
+ return null;
208
+ const inner = groupSize(g);
209
+ if (inner === null)
210
+ return null;
211
+ size += inner;
212
+ }
213
+ return size;
214
+ }
215
+ // ---------------------------------------------------------------------------
216
+ // Types ⇄ registers
217
+ // ---------------------------------------------------------------------------
218
+ const UNIMPLEMENTED = {
219
+ int16: 0x8000n, sunssf: 0x8000n, uint16: 0xffffn, count: 0xffffn, enum16: 0xffffn, bitfield16: 0xffffn, acc16: 0n,
220
+ int32: 0x80000000n, uint32: 0xffffffffn, enum32: 0xffffffffn, bitfield32: 0xffffffffn, acc32: 0n, ipaddr: 0n,
221
+ int64: 0x8000000000000000n, uint64: 0xffffffffffffffffn, bitfield64: 0xffffffffffffffffn, acc64: 0n, ipv6addr: 0n,
222
+ float32: 0x7fc00000n, float64: 0x7ff8000000000000n,
223
+ };
224
+ const bits = (regs) => regs.reduce((acc, r) => (acc << 16n) | BigInt(r & 0xffff), 0n);
225
+ const signed = new Set(['int16', 'int32', 'int64', 'sunssf']);
226
+ function decode(p, regs) {
227
+ const t = p.type;
228
+ if (t === 'string') {
229
+ const bytes = Buffer.from(regs.flatMap((r) => [(r >> 8) & 0xff, r & 0xff]));
230
+ const end = bytes.indexOf(0);
231
+ const text = bytes.subarray(0, end < 0 ? bytes.length : end).toString('utf8');
232
+ return text === '' ? null : text;
233
+ }
234
+ if (t === 'raw16')
235
+ return regs[0];
236
+ if (t === 'eui48') {
237
+ const b = bits(regs) & 0xffffffffffffn;
238
+ if (b === 0xffffffffffffn)
239
+ return null;
240
+ return b.toString(16).padStart(12, '0').match(/../g).join(':').toUpperCase();
241
+ }
242
+ const b = bits(regs);
243
+ if (UNIMPLEMENTED[t] !== undefined && b === UNIMPLEMENTED[t])
244
+ return null;
245
+ if (t === 'float32' || t === 'float64') {
246
+ const buf = Buffer.alloc(8);
247
+ if (t === 'float32') {
248
+ buf.writeUInt32BE(Number(b));
249
+ const f = buf.readFloatBE(0);
250
+ return Number.isNaN(f) ? null : f;
251
+ }
252
+ buf.writeBigUInt64BE(b);
253
+ const f = buf.readDoubleBE(0);
254
+ return Number.isNaN(f) ? null : f;
255
+ }
256
+ if (t === 'ipaddr')
257
+ return [24, 16, 8, 0].map((s) => Number((b >> BigInt(s)) & 0xffn)).join('.');
258
+ if (t === 'ipv6addr')
259
+ return regs.map((r) => r.toString(16)).join(':');
260
+ const width = BigInt(16 * regs.length);
261
+ let n = b;
262
+ if (signed.has(t) && b >> (width - 1n) === 1n)
263
+ n = b - (1n << width);
264
+ return Number.isSafeInteger(Number(n)) ? Number(n) : n;
265
+ }
266
+ /**
267
+ * The registers that set a point of a model read before: the value in the
268
+ * point's units, scaled back by the scale factor the device gave and
269
+ * rounded to the resolution it allows; an enum may be named by its symbol;
270
+ * null writes "not implemented". Refuses `point_unknown`, `point_read_only`,
271
+ * `scale_factor_unimplemented` and `value_out_of_range` (with the range of
272
+ * the type in the point's units).
273
+ */
274
+ export function writePoint(model, path, value, definitions = MODELS) {
275
+ const p = pointOf(model, path);
276
+ const def = p && definitionOf(modelDefinition(model.id, definitions)?.group, path);
277
+ if (!p || !def)
278
+ throw new Error(`point_unknown: no point ${path} in model ${model.id}`);
279
+ if (!p.writable)
280
+ throw new Error(`point_read_only: ${path} may not be written`);
281
+ return { address: p.address, registers: encode(p, def, path, value) };
282
+ }
283
+ function definitionOf(group, path) {
284
+ const parts = path.split('.');
285
+ for (const part of parts.slice(0, -1)) {
286
+ const name = part.replace(/\[\d+\]$/, '');
287
+ group = group?.groups?.find((g) => g.name === name);
288
+ }
289
+ return group?.points.find((p) => p.name === parts[parts.length - 1]) ?? null;
290
+ }
291
+ const RANGES = {
292
+ int16: [-0x8000n, 0x7fffn], uint16: [0n, 0xffffn], count: [0n, 0xffffn], enum16: [0n, 0xffffn], bitfield16: [0n, 0xffffn], acc16: [0n, 0xffffn], raw16: [0n, 0xffffn],
293
+ int32: [-0x80000000n, 0x7fffffffn], uint32: [0n, 0xffffffffn], enum32: [0n, 0xffffffffn], bitfield32: [0n, 0xffffffffn], acc32: [0n, 0xffffffffn],
294
+ int64: [-0x8000000000000000n, 0x7fffffffffffffffn], uint64: [0n, 0xffffffffffffffffn], bitfield64: [0n, 0xffffffffffffffffn], acc64: [0n, 0xffffffffffffffffn],
295
+ sunssf: [-10n, 10n],
296
+ };
297
+ function encode(p, def, path, value) {
298
+ const words = (b) => Array.from({ length: p.size }, (_, i) => Number((b >> BigInt(16 * (p.size - 1 - i))) & 0xffffn));
299
+ if (value === null) {
300
+ if (p.type === 'string' || p.type === 'ipv6addr')
301
+ return words(0n);
302
+ if (p.type === 'eui48')
303
+ return words(0xffffffffffffn);
304
+ const u = UNIMPLEMENTED[p.type];
305
+ if (u === undefined)
306
+ throw new Error(`value_out_of_range: ${path} has no "not implemented" value`);
307
+ return words(u);
308
+ }
309
+ if (p.type === 'string') {
310
+ if (typeof value !== 'string')
311
+ throw new Error(`value_out_of_range: ${path} is a string`);
312
+ const bytes = Buffer.from(value, 'utf8');
313
+ if (bytes.length > p.size * 2)
314
+ throw new Error(`value_out_of_range: ${path} holds ${p.size * 2} bytes, not ${bytes.length}`);
315
+ const padded = Buffer.alloc(p.size * 2);
316
+ bytes.copy(padded);
317
+ return Array.from({ length: p.size }, (_, i) => padded.readUInt16BE(i * 2));
318
+ }
319
+ if (typeof value === 'string') {
320
+ const symbol = p.type.startsWith('enum') ? def.symbols?.find((s) => s.name === value) : undefined;
321
+ if (!symbol)
322
+ throw new Error(`value_out_of_range: ${path} has no symbol ${value}`);
323
+ return encode(p, def, path, symbol.value);
324
+ }
325
+ if (p.type === 'float32' || p.type === 'float64') {
326
+ const buf = Buffer.alloc(8);
327
+ if (p.type === 'float32')
328
+ buf.writeFloatBE(value);
329
+ else
330
+ buf.writeDoubleBE(value);
331
+ return Array.from({ length: p.size }, (_, i) => buf.readUInt16BE(i * 2));
332
+ }
333
+ if (def.sf !== undefined && p.sf === null)
334
+ throw new Error(`scale_factor_unimplemented: ${path} is scaled by ${def.sf}, which the device does not give`);
335
+ const sf = p.sf ?? 0;
336
+ const n = sf < 0 ? value * 10 ** -sf : value / 10 ** sf;
337
+ const range = RANGES[p.type];
338
+ if (!range || !Number.isFinite(n))
339
+ throw new Error(`value_out_of_range: ${path} of type ${p.type} takes no number`);
340
+ const r = BigInt(Math.round(n));
341
+ // The value that means "not implemented" is not a value one sets.
342
+ const width = BigInt(16 * p.size);
343
+ const asBits = r < 0n ? r + (1n << width) : r;
344
+ const u = UNIMPLEMENTED[p.type];
345
+ const lo = u === undefined || u !== (range[0] < 0n ? range[0] + (1n << width) : range[0]) ? range[0] : range[0] + 1n;
346
+ const hi = u === range[1] ? range[1] - 1n : range[1];
347
+ if (r < lo || r > hi || asBits === u) {
348
+ const at = (b) => (sf < 0 ? Number((Number(b) * 10 ** sf).toFixed(-sf)) : Number(b) * 10 ** sf);
349
+ throw new Error(`value_out_of_range: ${path} takes ${at(lo)} to ${at(hi)}${p.units ? ` ${p.units}` : ''}, not ${value}`);
350
+ }
351
+ return words(asBits);
352
+ }
@@ -0,0 +1,2 @@
1
+ import type { ModelDefinition } from './index.js';
2
+ export declare const MODELS: readonly ModelDefinition[];