@tsplc/typegen 0.5.13 → 0.5.15

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.
@@ -1,4 +1,3 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
1
  export interface EdsParameter {
3
2
  id: string;
4
3
  name: string;
@@ -71,8 +70,30 @@ const cipTypes: Record<number, string> = {
71
70
  212: "LWORD",
72
71
  };
73
72
 
73
+ /** Field positions in a `[Connection Manager]` record; fields from the name on are strings. */
74
+ const connectionFields = {
75
+ transport: 0,
76
+ outputSize: 3,
77
+ outputFormat: 4,
78
+ inputSize: 6,
79
+ inputFormat: 7,
80
+ name: 12,
81
+ path: 14,
82
+ } as const;
83
+
84
+ /** Field positions in an `[Assembly]` record; members follow as pairs of bits and parameter. */
85
+ const assemblyFields = {
86
+ name: 0,
87
+ path: 1,
88
+ size: 2,
89
+ descriptor: 3,
90
+ firstMember: 6,
91
+ } as const;
92
+
93
+ const isConnection = (key: string) => /^Connection\d+$/.test(key);
94
+
74
95
  /** A record's fields, and where the record (key through semicolon) sits in the EDS text. */
75
- export interface EdsRecord {
96
+ interface EdsRecord {
76
97
  fields: string[];
77
98
  start: number;
78
99
  end: number;
@@ -141,7 +162,7 @@ function recordFields(body: string): string[] {
141
162
  * EDS records are comma separated, terminated by semicolons, with $ comments.
142
163
  * Sections and their records keep file order.
143
164
  */
144
- export function edsSections(text: string): Map<string, Map<string, EdsRecord>> {
165
+ function edsSections(text: string): Map<string, Map<string, EdsRecord>> {
145
166
  const { clean, offsets } = stripComments(text);
146
167
  const sections = new Map<string, Map<string, EdsRecord>>();
147
168
  let section: Map<string, EdsRecord> | undefined;
@@ -166,15 +187,20 @@ export function edsSections(text: string): Map<string, Map<string, EdsRecord>> {
166
187
  if (!section) {
167
188
  throw new Error("EDS record outside a section.");
168
189
  }
169
- // The pattern's record branch always captures a key and a (possibly empty) body.
170
- if (section.has(key!)) {
190
+ const start = offsets[match.index];
191
+ const last = offsets[end - 1];
192
+ if (
193
+ key === undefined ||
194
+ body === undefined ||
195
+ start === undefined ||
196
+ last === undefined
197
+ ) {
198
+ throw new Error("Malformed EDS record or section.");
199
+ }
200
+ if (section.has(key)) {
171
201
  throw new Error(`Duplicate EDS record ${key}.`);
172
202
  }
173
- section.set(key!, {
174
- fields: recordFields(body!),
175
- start: offsets[match.index]!,
176
- end: offsets[end - 1]! + 1,
177
- });
203
+ section.set(key, { fields: recordFields(body), start, end: last + 1 });
178
204
  }
179
205
  if (clean.slice(end).trim()) {
180
206
  throw new Error("Unterminated EDS record.");
@@ -182,7 +208,6 @@ export function edsSections(text: string): Map<string, Map<string, EdsRecord>> {
182
208
  return sections;
183
209
  }
184
210
 
185
- /** Each section's records, keyed by record name, as field lists. */
186
211
  export function readEdsRecords(
187
212
  text: string,
188
213
  ): Record<string, Record<string, string[]>> {
@@ -241,21 +266,42 @@ function logicalSegments(bytes: number[]): { type: number; value: number }[] {
241
266
  ];
242
267
  }
243
268
 
269
+ /**
270
+ * A path's bytes. A `[ParamN]` token stands for that parameter's default value, little-endian
271
+ * over its data size, as a device whose assemblies are configurable writes its connection path.
272
+ */
273
+ function pathBytes(
274
+ path: string,
275
+ params: ReadonlyMap<string, EdsParameter>,
276
+ ): number[] {
277
+ return path
278
+ .trim()
279
+ .split(/\s+/)
280
+ .filter(Boolean)
281
+ .flatMap((token) => {
282
+ if (/^[0-9a-f]{2}$/i.test(token)) {
283
+ return [parseInt(token, 16)];
284
+ }
285
+ const reference = /^\[(Param\d+)\]$/.exec(token)?.[1];
286
+ const parameter = reference ? params.get(reference) : undefined;
287
+ if (!parameter || parameter.default === undefined) {
288
+ throw new Error(`Unsupported EDS path token ${token}.`);
289
+ }
290
+ const value = parameter.default;
291
+ return Array.from(
292
+ { length: parameter.size },
293
+ (_, index) => Math.floor(value / 2 ** (index * 8)) % 256,
294
+ );
295
+ });
296
+ }
297
+
244
298
  // EPATH logical segments encode class, instance, attribute and connection-point
245
299
  // IDs. Record names such as Assem1 are format references, not runtime instances.
246
- function logicalPath(path: string): { instance?: number; points: number[] } {
247
- const bytes = path.trim()
248
- ? path
249
- .trim()
250
- .split(/\s+/)
251
- .map((token) => {
252
- if (!/^[0-9a-f]{2}$/i.test(token)) {
253
- throw new Error(`Unsupported EDS path token ${token}.`);
254
- }
255
- return parseInt(token, 16);
256
- })
257
- : [];
258
- const segments = logicalSegments(bytes);
300
+ function logicalPath(
301
+ path: string,
302
+ params: ReadonlyMap<string, EdsParameter>,
303
+ ): { instance?: number; points: number[] } {
304
+ const segments = logicalSegments(pathBytes(path, params));
259
305
  return {
260
306
  instance: segments.filter(({ type }) => type === 0x24).at(-1)?.value,
261
307
  points: segments
@@ -266,10 +312,7 @@ function logicalPath(path: string): { instance?: number; points: number[] } {
266
312
  const optionalNumber = (value: string | undefined) =>
267
313
  value?.trim() && Number.isFinite(Number(value)) ? Number(value) : undefined;
268
314
 
269
- export function parseEds(
270
- text: string,
271
- file = "device.eds",
272
- ): HardwareDescriptor {
315
+ export function parseEds(text: string, file: string): HardwareDescriptor {
273
316
  const records = readEdsRecords(text);
274
317
  const device = records.Device;
275
318
  if (!device?.ProdName?.[0]) {
@@ -294,6 +337,8 @@ export function parseEds(
294
337
  parameters.map((parameter) => [parameter.id, parameter]),
295
338
  );
296
339
  const instances = new Map<string, number>();
340
+ /** Instances a connection carries without an assembly record, with the largest payload it may transfer. */
341
+ const recordless = new Map<number, number>();
297
342
  const size = (value: string | undefined): EdsSize | undefined => {
298
343
  if (!value) {
299
344
  return;
@@ -315,22 +360,39 @@ export function parseEds(
315
360
  };
316
361
  };
317
362
  const connections = Object.entries(records["Connection Manager"] ?? {})
318
- .filter(([id]) => /^Connection\d+$/.test(id))
363
+ .filter(([id]) => isConnection(id))
319
364
  .map(([id, fields]): EdsConnection => {
320
- const path = fields[14] ?? "";
321
- const points = logicalPath(path).points;
365
+ const path = fields[connectionFields.path] ?? "";
366
+ const points = logicalPath(path, params).points;
367
+ const outputSize = size(fields[connectionFields.outputSize]);
368
+ const inputSize = size(fields[connectionFields.inputSize]);
322
369
  const assembly = (
323
370
  reference: string | undefined,
324
371
  point: number | undefined,
372
+ payload: EdsSize | undefined,
325
373
  ): number | undefined => {
374
+ // Without an assembly record to name it, the path's connection point is the instance of a
375
+ // direction that carries data; an empty one points at a placeholder such as heartbeat 254.
326
376
  if (!reference) {
327
- return;
377
+ if (!payload || payload.value <= 0 || point === undefined) {
378
+ return;
379
+ }
380
+ recordless.set(
381
+ point,
382
+ Math.max(
383
+ recordless.get(point) ?? 0,
384
+ payload.maximum ?? payload.value,
385
+ ),
386
+ );
387
+ return point;
328
388
  }
329
389
  const record = records.Assembly?.[reference];
330
390
  if (!/^Assem\d+$/.test(reference) || !record) {
331
391
  throw new Error(`${file}: unknown connection assembly ${reference}.`);
332
392
  }
333
- const instance = point ?? logicalPath(record[1] ?? "").instance;
393
+ const instance =
394
+ point ??
395
+ logicalPath(record[assemblyFields.path] ?? "", params).instance;
334
396
  if (instance === undefined) {
335
397
  throw new Error(`${file}: no runtime instance for ${reference}.`);
336
398
  }
@@ -345,16 +407,24 @@ export function parseEds(
345
407
  };
346
408
  return {
347
409
  id,
348
- name: fields[12] || id,
410
+ name: fields[connectionFields.name] || id,
349
411
  // Trigger and transport bits 24-27 give the connection type; 4 is exclusive owner.
350
412
  owner:
351
- /^0x[\da-f]{8}$/i.test(fields[0] ?? "") &&
352
- ((Number(fields[0]) >>> 24) & 0xf) === 4,
413
+ /^0x[\da-f]{8}$/i.test(fields[connectionFields.transport] ?? "") &&
414
+ ((Number(fields[connectionFields.transport]) >>> 24) & 0xf) === 4,
353
415
  path,
354
- outputAssembly: assembly(fields[4], points.at(-2)),
355
- inputAssembly: assembly(fields[7], points.at(-1)),
356
- outputSize: size(fields[3]),
357
- inputSize: size(fields[6]),
416
+ outputAssembly: assembly(
417
+ fields[connectionFields.outputFormat],
418
+ points.at(-2),
419
+ outputSize,
420
+ ),
421
+ inputAssembly: assembly(
422
+ fields[connectionFields.inputFormat],
423
+ points.at(-1),
424
+ inputSize,
425
+ ),
426
+ outputSize,
427
+ inputSize,
358
428
  };
359
429
  });
360
430
  const assemblies = Object.entries(records.Assembly ?? {})
@@ -362,7 +432,11 @@ export function parseEds(
362
432
  .map(([id, fields]): EdsAssembly => {
363
433
  const members: EdsMember[] = [];
364
434
  let offsetBits = 0;
365
- for (let index = 6; index < fields.length; index += 2) {
435
+ for (
436
+ let index = assemblyFields.firstMember;
437
+ index < fields.length;
438
+ index += 2
439
+ ) {
366
440
  if (!fields[index] && !fields[index + 1]) {
367
441
  continue;
368
442
  }
@@ -387,8 +461,9 @@ export function parseEds(
387
461
  });
388
462
  offsetBits += bits;
389
463
  }
390
- const size = fields[2]
391
- ? integer(fields[2], `${id} size`, { minimum: 0 })
464
+ const declared = fields[assemblyFields.size];
465
+ const size = declared
466
+ ? integer(declared, `${id} size`, { minimum: 0 })
392
467
  : Math.ceil(offsetBits / 8);
393
468
  if (offsetBits > size * 8) {
394
469
  throw new Error(
@@ -396,9 +471,27 @@ export function parseEds(
396
471
  );
397
472
  }
398
473
  const instance =
399
- logicalPath(fields[1] ?? "").instance ?? instances.get(id);
400
- return { id, instance, name: fields[0] || id, size, members };
474
+ logicalPath(fields[assemblyFields.path] ?? "", params).instance ??
475
+ instances.get(id);
476
+ return {
477
+ id,
478
+ instance,
479
+ name: fields[assemblyFields.name] || id,
480
+ size,
481
+ members,
482
+ };
401
483
  });
484
+ for (const [instance, payloadSize] of recordless) {
485
+ if (!assemblies.some((assembly) => assembly.instance === instance)) {
486
+ assemblies.push({
487
+ id: `Instance${instance}`,
488
+ instance,
489
+ name: `Assembly ${instance}`,
490
+ size: payloadSize,
491
+ members: [],
492
+ });
493
+ }
494
+ }
402
495
  return {
403
496
  file,
404
497
  name: device.ProdName[0],
@@ -409,3 +502,94 @@ export function parseEds(
409
502
  connections,
410
503
  };
411
504
  }
505
+
506
+ const quoted = (value: string) => `"${value.replaceAll('"', '""')}"`;
507
+
508
+ /**
509
+ * Reduce an EDS to the selected connection with raw byte assemblies of the selected
510
+ * payload sizes. CODESYS's EDS import then creates one BYTE channel per payload
511
+ * byte, so each channel sits at its assembly offset. Member layouts would instead
512
+ * become typed channels that CODESYS packs independently, and it maps only the
513
+ * first byte of a multi-byte member such as a reader's result data.
514
+ */
515
+ export function normalizeEds(
516
+ text: string,
517
+ selection: { connection: string; inputSize?: number; outputSize?: number },
518
+ ): string {
519
+ const sections = edsSections(text);
520
+ const connections = [...(sections.get("Connection Manager") ?? [])].filter(
521
+ ([key]) => isConnection(key),
522
+ );
523
+ const selected = connections.find(
524
+ ([key]) => key === selection.connection,
525
+ )?.[1];
526
+ if (!selected) {
527
+ throw new Error(`EDS has no ${selection.connection}.`);
528
+ }
529
+ const fields = [...selected.fields];
530
+ const resized = new Map<string, number>();
531
+ for (const [sizeField, formatField, size] of [
532
+ [
533
+ connectionFields.outputSize,
534
+ connectionFields.outputFormat,
535
+ selection.outputSize,
536
+ ],
537
+ [
538
+ connectionFields.inputSize,
539
+ connectionFields.inputFormat,
540
+ selection.inputSize,
541
+ ],
542
+ ] as const) {
543
+ const assembly = fields[formatField];
544
+ if (!assembly) {
545
+ continue;
546
+ }
547
+ if (size === undefined) {
548
+ throw new Error(`Select a payload size for ${assembly}.`);
549
+ }
550
+ fields[sizeField] = String(size);
551
+ resized.set(assembly, size);
552
+ }
553
+ const edits = connections.map(([, record]) => ({
554
+ start: record.start,
555
+ end: record.end,
556
+ text:
557
+ record === selected
558
+ ? `Connection1 = ${fields.map((value, index) => (index >= connectionFields.name ? quoted(value) : value)).join(",")};`
559
+ : "",
560
+ }));
561
+ for (const [key, record] of sections.get("Assembly") ?? []) {
562
+ const size = resized.get(key);
563
+ if (size === undefined) {
564
+ continue;
565
+ }
566
+ const path = record.fields[assemblyFields.path] ?? "";
567
+ // One padding member spans the whole payload.
568
+ const rawBytes = [
569
+ quoted(record.fields[assemblyFields.name] ?? ""),
570
+ path && quoted(path),
571
+ size,
572
+ record.fields[assemblyFields.descriptor] ?? "",
573
+ "",
574
+ "",
575
+ size * 8,
576
+ "",
577
+ ];
578
+ edits.push({
579
+ start: record.start,
580
+ end: record.end,
581
+ text: `${key} = ${rawBytes.join(",")};`,
582
+ });
583
+ resized.delete(key);
584
+ }
585
+ if (resized.size) {
586
+ throw new Error(`EDS has no ${[...resized.keys()].join(", ")} assembly.`);
587
+ }
588
+ return edits
589
+ .sort((a, b) => b.start - a.start)
590
+ .reduce(
591
+ (result, edit) =>
592
+ result.slice(0, edit.start) + edit.text + result.slice(edit.end),
593
+ text,
594
+ );
595
+ }
@@ -1,7 +1,8 @@
1
- // biome-ignore-all lint/suspicious/noTemplateCurlyInString: These strings describe Docker or generated TypeScript interpolation, not JavaScript interpolation here.
2
- import { ioScalarBits } from "@tsplc/iec";
3
- import type { HardwareCatalog } from "../hardware";
4
- import { addressSize, ioLayout } from "./process-image";
1
+ // biome-ignore-all lint/suspicious/noTemplateCurlyInString: These strings are generated TypeScript template literal types, not JavaScript interpolation.
2
+ import { relative, sep } from "node:path";
3
+ import { sizePrefixes } from "@tsplc/iec";
4
+ import type { HardwareCatalog } from "./catalog";
5
+ import { addressSize, ioLayout, layoutBits } from "./process-image";
5
6
 
6
7
  /** A bindable `io` key with its layout; array indexes appear as the literal `${number}`. */
7
8
  export interface IoTarget {
@@ -14,18 +15,44 @@ export interface ProjectTargets {
14
15
  publication: readonly string[];
15
16
  }
16
17
 
17
- // Integer layouts are INTn and the others are named for their type.
18
+ const region = '${"I" | "Q"}';
19
+ const bitAddress = `\`%${region}X\${number}.\${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}\``;
20
+ const byteSizes = [...sizePrefixes]
21
+ .filter(
22
+ ([prefix, type]) => type.bits > 1 && addressSize(type.bits) === prefix,
23
+ )
24
+ .map(([prefix]) => JSON.stringify(prefix))
25
+ .join(" | ");
26
+ const addressBinding = (address: string) =>
27
+ `{ address: ${address}; type?: string }`;
28
+
18
29
  const directBinding = (layout: string): string | undefined => {
19
- const scalar = layout.replace(/^\d+x/, "");
20
- const integer = /^INT(\d+)$/.exec(scalar);
21
- const bits = integer ? Number(integer[1]) : ioScalarBits(scalar);
30
+ const bits = layoutBits(layout);
22
31
  const size = bits === undefined ? undefined : addressSize(bits);
23
32
  if (!size) {
24
33
  return undefined;
25
34
  }
26
- return size === "X"
27
- ? '{ address: `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }'
28
- : `{ address: \`%\${"I" | "Q"}${size}\${number}\`; type?: string }`;
35
+ return addressBinding(
36
+ size === "X" ? bitAddress : `\`%${region}${size}\${number}\``,
37
+ );
38
+ };
39
+
40
+ /** The catalog with its descriptor paths relative to the project, as the generated file carries it. */
41
+ const portableCatalog = (
42
+ catalog: HardwareCatalog,
43
+ root: string,
44
+ ): HardwareCatalog => {
45
+ const portable = (file: string) => relative(root, file).split(sep).join("/");
46
+ return {
47
+ descriptors: catalog.descriptors.map((descriptor) => ({
48
+ ...descriptor,
49
+ file: portable(descriptor.file),
50
+ })),
51
+ devices: catalog.devices.map((device) => ({
52
+ ...device,
53
+ descriptor: portable(device.descriptor),
54
+ })),
55
+ };
29
56
  };
30
57
 
31
58
  /**
@@ -35,13 +62,22 @@ const directBinding = (layout: string): string | undefined => {
35
62
  */
36
63
  export function generateHardwareTypes(
37
64
  catalog: HardwareCatalog,
38
- targets?: readonly IoTarget[],
39
- publication?: readonly string[],
40
- ioTypes = true,
65
+ {
66
+ root,
67
+ targets,
68
+ ioTypes,
69
+ }: {
70
+ /** The project root, which the generated catalog's descriptor paths are relative to. */
71
+ root: string;
72
+ targets: ProjectTargets | null;
73
+ /** Also emit the I/O binding types and the device catalog, not just the publication selectors. */
74
+ ioTypes: boolean;
75
+ },
41
76
  ): string {
42
77
  const selectors =
43
- publication?.map((selector) => JSON.stringify(selector)).join(" | ") ??
44
- "string";
78
+ targets?.publication
79
+ .map((selector) => JSON.stringify(selector))
80
+ .join(" | ") ?? "string";
45
81
  const publicationTypes = `// Generated by tsPLC. Run tsplc typegen after changing EDS files, device selections or PLC storage.\nexport type PublicationSelector = ${selectors || "never"};\nexport type PlcPublication = { readonly production: readonly PublicationSelector[]; readonly development: readonly PublicationSelector[] };\n`;
46
82
  if (!ioTypes) {
47
83
  return publicationTypes;
@@ -63,16 +99,17 @@ export function generateHardwareTypes(
63
99
  layout: ioLayout(item.type),
64
100
  })),
65
101
  );
66
- const direct =
67
- '{ address: `%${"I" | "Q"}${"B" | "W" | "D"}${number}` | `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }';
102
+ const direct = addressBinding(
103
+ `\`%${region}\${${byteSizes}}\${number}\` | ${bitAddress}`,
104
+ );
68
105
  const anyBinding = [...channels.map((item) => item.binding), direct].join(
69
106
  "\n | ",
70
107
  );
71
108
  const mapping = targets
72
- ? [...new Set(targets.map((target) => target.layout))]
109
+ ? [...new Set(targets.io.map((target) => target.layout))]
73
110
  .sort()
74
111
  .map((layout) => {
75
- const keys = targets
112
+ const keys = targets.io
76
113
  .filter((target) => target.layout === layout)
77
114
  .map((target) => `\`${target.key}\``);
78
115
  const bindings = [
@@ -85,5 +122,5 @@ export function generateHardwareTypes(
85
122
  })
86
123
  .join(" & ") || "Readonly<Record<string, never>>"
87
124
  : "Readonly<Record<string, HardwareIoBinding>>";
88
- return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};\nexport type HardwareIoMapping = ${mapping};\nexport const hardware = ${JSON.stringify(catalog, null, 2)} as const;\n`;
125
+ return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};\nexport type HardwareIoMapping = ${mapping};\nexport const hardware = ${JSON.stringify(portableCatalog(catalog, root), null, 2)} as const;\n`;
89
126
  }
@@ -1,9 +1,8 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
1
  import type { IoChannel } from "./channels";
3
2
  import {
4
- byteOffset,
5
3
  directAddress,
6
4
  type ProcessImageRegion,
5
+ regionOf,
7
6
  } from "./process-image";
8
7
 
9
8
  export interface ModbusRegister {
@@ -15,6 +14,9 @@ export interface ModbusRegister {
15
14
  requests: string;
16
15
  }
17
16
 
17
+ /** The Modbus TCP server a generated device tree adds for a device's registers; `packages/build/python/hardware.py` names it the same way. */
18
+ export const modbusServerName = (device: string) => `${device}_Modbus`;
19
+
18
20
  /** Process-image bytes per register: its value and write trigger out, the client's status and answer count in. */
19
21
  const registerBytes = { Q: 4, I: 8 };
20
22
 
@@ -26,18 +28,22 @@ const registerBytes = { Q: 4, I: 8 };
26
28
  export function placeModbusRegisters(
27
29
  device: string,
28
30
  registers: Record<string, number>,
29
- place: (region: ProcessImageRegion) => string,
31
+ place: (region: ProcessImageRegion) => number,
30
32
  ): { register: ModbusRegister; channels: IoChannel[] }[] {
31
33
  const entries = Object.entries(registers);
32
34
  if (!entries.length) {
33
35
  return [];
34
36
  }
35
- const outputBase = byteOffset(
36
- place({ id: device, region: "Q", size: entries.length * registerBytes.Q }),
37
- );
38
- const inputBase = byteOffset(
39
- place({ id: device, region: "I", size: entries.length * registerBytes.I }),
40
- );
37
+ const outputBase = place({
38
+ id: device,
39
+ region: "Q",
40
+ size: entries.length * registerBytes.Q,
41
+ });
42
+ const inputBase = place({
43
+ id: device,
44
+ region: "I",
45
+ size: entries.length * registerBytes.I,
46
+ });
41
47
  return entries.map(([name, offset], index) => {
42
48
  const channel = (
43
49
  field: string,
@@ -46,25 +52,34 @@ export function placeModbusRegisters(
46
52
  bits: number,
47
53
  type: string,
48
54
  description: string,
49
- ): IoChannel => ({
50
- device,
51
- id: `modbus.${name}.${field}`,
52
- name: `${name} ${field}`,
53
- direction,
54
- offsetBits,
55
- bits,
56
- type,
57
- address: directAddress(
58
- direction === "input" ? "I" : "Q",
55
+ ): IoChannel & { address: string } => {
56
+ const address = directAddress(
57
+ regionOf(direction),
59
58
  direction === "input"
60
59
  ? inputBase + index * registerBytes.I
61
60
  : outputBase + index * registerBytes.Q,
62
61
  offsetBits,
63
62
  bits,
64
- ),
65
- unit: "",
66
- description,
67
- });
63
+ );
64
+ // Regions start on double words, so every field is directly addressable.
65
+ if (!address) {
66
+ throw new Error(
67
+ `${device}: Modbus register ${name} ${field} has no direct address.`,
68
+ );
69
+ }
70
+ return {
71
+ device,
72
+ id: `modbus.${name}.${field}`,
73
+ name: `${name} ${field}`,
74
+ direction,
75
+ offsetBits,
76
+ bits,
77
+ type,
78
+ address,
79
+ unit: "",
80
+ description,
81
+ };
82
+ };
68
83
  const value = channel("value", "output", 0, 16, "WORD", "Value to write");
69
84
  const write = channel(
70
85
  "write",
@@ -91,14 +106,13 @@ export function placeModbusRegisters(
91
106
  "Requests the device answered",
92
107
  );
93
108
  return {
94
- // Registers start on double words, so every field is directly addressable.
95
109
  register: {
96
110
  name,
97
111
  offset,
98
- value: value.address!,
99
- write: write.address!,
100
- status: status.address!,
101
- requests: requests.address!,
112
+ value: value.address,
113
+ write: write.address,
114
+ status: status.address,
115
+ requests: requests.address,
102
116
  },
103
117
  channels: [value, write, status, requests],
104
118
  };