@tsplc/typegen 0.2.17 → 0.2.18

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/src/hardware.ts CHANGED
@@ -1,858 +1,209 @@
1
1
  import { readdir, readFile } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
- import type { HardwareDevice, ResolvedTsplcConfig } from "@tsplc/config";
4
- import { iecTypeBits } from "./codegen/constants.ts";
3
+ import type { ResolvedTsplcConfig } from "@tsplc/config";
4
+ import {
5
+ type EdsConnection,
6
+ type HardwareDescriptor,
7
+ parseEds,
8
+ } from "./hardware/eds.ts";
9
+ import { type IoChannel, assemblyChannels } from "./hardware/channels.ts";
10
+ import {
11
+ type ModbusRegister,
12
+ placeModbusRegisters,
13
+ } from "./hardware/modbus.ts";
14
+ import { byteOffset, regionPlacer } from "./hardware/process-image.ts";
15
+ import { selectAssemblies, selectConnection } from "./hardware/selection.ts";
16
+
17
+ export {
18
+ type EdsAssembly,
19
+ type EdsConnection,
20
+ type EdsMember,
21
+ type EdsParameter,
22
+ type EdsSize,
23
+ type HardwareDescriptor,
24
+ parseEds,
25
+ readEdsRecords,
26
+ } from "./hardware/eds.ts";
27
+ export type { IoChannel } from "./hardware/channels.ts";
28
+ export type { ModbusRegister } from "./hardware/modbus.ts";
29
+ export { ioScalarBits } from "@tsplc/iec";
30
+ export { ioLayout } from "./hardware/process-image.ts";
31
+ export {
32
+ type IoTarget,
33
+ type ProjectTargets,
34
+ generateHardwareTypes,
35
+ } from "./hardware/mapping-types.ts";
5
36
 
6
- export interface EdsParameter {
7
- id: string;
8
- name: string;
9
- type: string;
10
- size: number;
11
- unit: string;
12
- description: string;
13
- minimum?: number;
14
- maximum?: number;
15
- default?: number;
16
- }
17
- export interface EdsMember {
18
- parameter?: string;
19
- name: string;
20
- offsetBits: number;
21
- bits: number;
22
- type: string;
23
- unit: string;
24
- description: string;
25
- }
26
- export interface EdsAssembly {
27
- id: string;
28
- instance?: number;
29
- name: string;
30
- size: number;
31
- members: EdsMember[];
32
- }
33
- export interface EdsConnection {
34
- id: string;
35
- name: string;
36
- /** Exclusive owner: the scanner both produces and controls the connection's data. */
37
- owner: boolean;
38
- outputAssembly?: number;
39
- inputAssembly?: number;
40
- path: string;
41
- inputSize?: EdsSize;
42
- outputSize?: EdsSize;
43
- }
44
- export interface EdsSize {
45
- value: number;
46
- parameter?: string;
47
- minimum?: number;
48
- maximum?: number;
49
- }
50
- export interface HardwareDescriptor {
51
- file: string;
52
- name: string;
53
- vendor: string;
54
- productCode: string;
55
- parameters: EdsParameter[];
56
- assemblies: EdsAssembly[];
57
- connections: EdsConnection[];
58
- }
59
- export interface IoChannel {
60
- device: string;
61
- id: string;
62
- name: string;
63
- direction: "input" | "output";
64
- /** Absent on a Modbus channel, which belongs to no EtherNet/IP assembly. */
65
- assembly?: number;
66
- offsetBits: number;
67
- bits: number;
68
- type: string;
69
- address?: string;
70
- parent?: string;
71
- unit: string;
72
- description: string;
73
- }
74
37
  export interface SelectedAssembly {
75
- direction: "input" | "output";
76
- instance: number;
77
- name: string;
78
- address: string;
79
- size: number;
80
- capacity: number;
38
+ direction: "input" | "output";
39
+ instance: number;
40
+ name: string;
41
+ address: string;
42
+ size: number;
43
+ capacity: number;
81
44
  }
82
45
  export interface HardwareCatalog {
83
- descriptors: HardwareDescriptor[];
84
- devices: {
85
- id: string;
86
- descriptor: string;
87
- connection?: Pick<EdsConnection, "id" | "name" | "path">;
88
- assemblies: SelectedAssembly[];
89
- channels: IoChannel[];
90
- statusSymbols: Record<string, string>;
91
- modbus?: { port: number; registers: ModbusRegister[] };
92
- }[];
93
- }
94
- export interface ModbusRegister {
95
- name: string;
96
- offset: number;
97
- value: string;
98
- write: string;
99
- status: string;
100
- requests: string;
101
- }
102
-
103
- const cipTypes: Record<number, string> = {
104
- 0xc1: "BOOL",
105
- 0xc2: "SINT",
106
- 0xc3: "INT",
107
- 0xc4: "DINT",
108
- 0xc5: "LINT",
109
- 0xc6: "USINT",
110
- 0xc7: "UINT",
111
- 0xc8: "UDINT",
112
- 0xc9: "ULINT",
113
- 0xca: "REAL",
114
- 0xcb: "LREAL",
115
- 0xd1: "BYTE",
116
- 0xd2: "WORD",
117
- 0xd3: "DWORD",
118
- 0xd4: "LWORD",
119
- };
120
-
121
- /** EDS records are comma separated, terminated by semicolons, with $ comments. */
122
- export function readEdsRecords(text: string): Record<string, Record<string, string[]>> {
123
- let clean = "",
124
- quote = false,
125
- comment = false;
126
- for (let i = 0; i < text.length; i++) {
127
- const c = text[i]!;
128
- if (comment) {
129
- if (c === "\n") {
130
- comment = false;
131
- clean += c;
132
- }
133
- continue;
134
- }
135
- if (c === '"') {
136
- if (quote && text[i + 1] === '"') {
137
- clean += '""';
138
- i++;
139
- continue;
140
- }
141
- quote = !quote;
142
- }
143
- if (c === "$" && !quote) {
144
- comment = true;
145
- continue;
146
- }
147
- clean += c;
148
- }
149
- if (quote) throw new Error("Unterminated EDS string.");
150
- const result: Record<string, Record<string, string[]>> = {};
151
- let section: Record<string, string[]> | undefined;
152
- const tokens = /\[([^\]\r\n]+)\]|([A-Za-z_][\w]*)\s*=\s*((?:"(?:[^"]|"")*"|[^;])*)\s*;/g;
153
- let end = 0;
154
- for (const match of clean.matchAll(tokens)) {
155
- if (clean.slice(end, match.index).trim()) throw new Error("Malformed EDS record or section.");
156
- end = match.index! + match[0].length;
157
- if (match[1]) {
158
- const key = match[1].trim();
159
- if (result[key]) throw new Error(`Duplicate EDS section ${key}.`);
160
- section = result[key] = {};
161
- continue;
162
- }
163
- if (!section) throw new Error("EDS record outside a section.");
164
- const key = match[2]!;
165
- if (section[key]) throw new Error(`Duplicate EDS record ${key}.`);
166
- const fields: string[] = [];
167
- let field = "",
168
- quoted = false;
169
- const body = match[3]!;
170
- for (let i = 0; i < body.length; i++) {
171
- const c = body[i]!;
172
- if (c === '"') {
173
- if (quoted && body[i + 1] === '"') {
174
- field += '"';
175
- i++;
176
- } else quoted = !quoted;
177
- } else if (c === "," && !quoted) {
178
- fields.push(field.trim());
179
- field = "";
180
- } else field += c;
181
- }
182
- fields.push(field.trim());
183
- section[key] = fields;
184
- }
185
- if (clean.slice(end).trim()) throw new Error("Unterminated EDS record.");
186
- return result;
187
- }
188
- function integer(value: string | undefined, label: string, allowZero = true): number {
189
- if (!value || !/^(?:\d+|0x[\da-f]+)$/i.test(value))
190
- throw new Error(`Invalid EDS ${label}: ${value ?? "missing"}.`);
191
- const n = Number(value);
192
- if (!Number.isSafeInteger(n) || n < (allowZero ? 0 : 1) || n > 16_777_216)
193
- throw new Error(`Unsupported EDS ${label}: ${value}.`);
194
- return n;
195
- }
196
- // EPATH logical segments encode class, instance, attribute and connection-point
197
- // IDs. Record names such as Assem1 are format references, not runtime instances.
198
- function logicalPath(path: string): { instance?: number; points: number[] } {
199
- const bytes = path.trim()
200
- ? path
201
- .trim()
202
- .split(/\s+/)
203
- .map((token) => {
204
- if (!/^[0-9a-f]{2}$/i.test(token))
205
- throw new Error(`Unsupported EDS path token ${token}.`);
206
- return parseInt(token, 16);
207
- })
208
- : [];
209
- const result: { instance?: number; points: number[] } = { points: [] };
210
- for (let offset = 0; offset < bytes.length;) {
211
- const segment = bytes[offset++]!;
212
- const width = segment & 3;
213
- if ((segment & 0xe0) !== 0x20 || width > 2)
214
- throw new Error(`Unsupported EDS logical path segment ${segment.toString(16)}.`);
215
- if (width && bytes[offset++] !== 0) throw new Error("Invalid EDS logical path padding.");
216
- const length = 1 << width;
217
- if (offset + length > bytes.length) throw new Error("Truncated EDS logical path.");
218
- let value = 0;
219
- for (let index = 0; index < length; index++) value += bytes[offset++]! * 2 ** (index * 8);
220
- if ((segment & 0xfc) === 0x24) result.instance = value;
221
- if ((segment & 0xfc) === 0x2c) result.points.push(value);
222
- }
223
- return result;
224
- }
225
- const optionalNumber = (value: string | undefined) =>
226
- value?.trim() && Number.isFinite(Number(value)) ? Number(value) : undefined;
227
-
228
- export function parseEds(text: string, file = "device.eds"): HardwareDescriptor {
229
- const records = readEdsRecords(text),
230
- device = records.Device;
231
- if (!device?.ProdName?.[0]) throw new Error(`${file}: missing EDS Device.ProdName.`);
232
- const parameters = Object.entries(records.Params ?? {})
233
- .filter(([id]) => /^Param\d+$/.test(id))
234
- .map(([id, fields]): EdsParameter => ({
235
- id,
236
- name: fields[6] || id,
237
- type: cipTypes[Number(fields[4])] ?? "opaque",
238
- size: integer(fields[5], `${id} data size`, false),
239
- unit: fields[7] ?? "",
240
- description: fields[8] ?? "",
241
- minimum: optionalNumber(fields[9]),
242
- maximum: optionalNumber(fields[10]),
243
- default: optionalNumber(fields[11]),
244
- }));
245
- const params = new Map(parameters.map((parameter) => [parameter.id, parameter]));
246
- const instances = new Map<string, number>();
247
- const size = (value: string | undefined): EdsSize | undefined => {
248
- if (!value) return;
249
- if (!value.startsWith("Param")) return { value: integer(value, "connection size") };
250
- const parameter = params.get(value);
251
- if (!parameter || parameter.default === undefined)
252
- throw new Error(`${file}: connection size ${value} has no numeric default.`);
253
- return {
254
- value: parameter.default,
255
- parameter: value,
256
- minimum: parameter.minimum,
257
- maximum: parameter.maximum,
258
- };
259
- };
260
- const connections = Object.entries(records["Connection Manager"] ?? {})
261
- .filter(([id]) => /^Connection\d+$/.test(id))
262
- .map(([id, fields]): EdsConnection => {
263
- const path = fields[14] ?? "",
264
- points = logicalPath(path).points;
265
- const assembly = (
266
- reference: string | undefined,
267
- point: number | undefined,
268
- ): number | undefined => {
269
- if (!reference) return;
270
- if (!/^Assem\d+$/.test(reference) || !records.Assembly?.[reference])
271
- throw new Error(`${file}: unknown connection assembly ${reference}.`);
272
- const instance = point ?? logicalPath(records.Assembly[reference]![1] ?? "").instance;
273
- if (instance === undefined)
274
- throw new Error(`${file}: no runtime instance for ${reference}.`);
275
- const previous = instances.get(reference);
276
- if (previous !== undefined && previous !== instance)
277
- throw new Error(`${file}: ${reference} has conflicting runtime instances.`);
278
- instances.set(reference, instance);
279
- return instance;
280
- };
281
- return {
282
- id,
283
- name: fields[12] || id,
284
- // Trigger and transport bits 24-27 give the connection type; 4 is exclusive owner.
285
- owner: /^0x[\da-f]{8}$/i.test(fields[0] ?? "") && ((Number(fields[0]) >>> 24) & 0xf) === 4,
286
- path,
287
- outputAssembly: assembly(fields[4], points.at(-2)),
288
- inputAssembly: assembly(fields[7], points.at(-1)),
289
- outputSize: size(fields[3]),
290
- inputSize: size(fields[6]),
291
- };
292
- });
293
- const assemblies = Object.entries(records.Assembly ?? {})
294
- .filter(([id]) => /^Assem\d+$/.test(id))
295
- .map(([id, fields]): EdsAssembly => {
296
- const members: EdsMember[] = [];
297
- let offsetBits = 0;
298
- for (let index = 6; index < fields.length; index += 2) {
299
- if (!fields[index] && !fields[index + 1]) continue;
300
- const bits = integer(fields[index], `${id} member bits`, false),
301
- reference = fields[index + 1];
302
- const parameter = reference ? params.get(reference) : undefined;
303
- if (reference && !parameter)
304
- throw new Error(`${file}: ${id} references unknown parameter ${reference}.`);
305
- members.push({
306
- ...(reference ? { parameter: reference } : {}),
307
- name: parameter?.name ?? "Padding",
308
- offsetBits,
309
- bits,
310
- type: parameter?.type ?? "padding",
311
- unit: parameter?.unit ?? "",
312
- description: parameter?.description ?? "",
313
- });
314
- offsetBits += bits;
315
- }
316
- const size = fields[2] ? integer(fields[2], `${id} size`) : Math.ceil(offsetBits / 8);
317
- if (offsetBits > size * 8)
318
- throw new Error(`${file}: ${id} members exceed its ${size} byte payload.`);
319
- const instance = logicalPath(fields[1] ?? "").instance ?? instances.get(id);
320
- return { id, instance, name: fields[0] || id, size, members };
321
- });
322
- return {
323
- file,
324
- name: device.ProdName[0],
325
- vendor: device.VendName?.[0] ?? "",
326
- productCode: device.ProdCode?.[0] ?? "",
327
- parameters,
328
- assemblies,
329
- connections,
330
- };
46
+ descriptors: HardwareDescriptor[];
47
+ devices: {
48
+ id: string;
49
+ descriptor: string;
50
+ connection?: Pick<EdsConnection, "id" | "name" | "path">;
51
+ assemblies: SelectedAssembly[];
52
+ channels: IoChannel[];
53
+ statusSymbols: Record<string, string>;
54
+ modbus?: { port: number; registers: ModbusRegister[] };
55
+ }[];
331
56
  }
332
57
 
333
58
  async function edsFiles(directory: string): Promise<string[]> {
334
- const entries = await readdir(directory, { withFileTypes: true }).catch((cause: unknown) => {
335
- if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") return [];
336
- throw cause;
337
- });
338
- const files: string[] = [];
339
- for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
340
- const path = resolve(directory, entry.name);
341
- if (entry.isDirectory()) files.push(...(await edsFiles(path)));
342
- else if (entry.isFile() && /\.eds$/i.test(entry.name)) files.push(path);
343
- }
344
- return files;
345
- }
346
-
347
- /**
348
- * An explicit connection must carry the selected assemblies. Otherwise the one
349
- * matching connection, or the one exclusive owner that carries both directions, is
350
- * implied; any other choice is listed for the config to name.
351
- */
352
- function selectConnection(
353
- id: string,
354
- settings: HardwareDevice,
355
- descriptor: HardwareDescriptor,
356
- ): EdsConnection | undefined {
357
- const compatible = descriptor.connections.filter(
358
- (connection) =>
359
- (settings.inputs?.assembly === undefined ||
360
- connection.inputAssembly === settings.inputs.assembly) &&
361
- (settings.outputs?.assembly === undefined ||
362
- connection.outputAssembly === settings.outputs.assembly),
363
- );
364
- if (settings.connection) {
365
- const connection = compatible.find((item) => item.id === settings.connection);
366
- if (!connection)
367
- throw new Error(
368
- `${id}: connection ${settings.connection} does not match the selected assemblies.`,
369
- );
370
- return connection;
371
- }
372
- if (compatible.length <= 1) return compatible[0];
373
- const owners = compatible.filter(
374
- (item) => item.owner && item.inputAssembly !== undefined && item.outputAssembly !== undefined,
375
- );
376
- if (owners.length === 1) return owners[0];
377
- const choices = compatible
378
- .map(
379
- (item) =>
380
- `${item.id} "${item.name}" (in ${item.inputAssembly ?? "-"}, out ${item.outputAssembly ?? "-"})`,
381
- )
382
- .join(", ");
383
- throw new Error(`${id}: select connection; ${settings.file} offers ${choices}.`);
384
- }
385
-
386
- /**
387
- * Bases for assemblies without an address: each region continues after the
388
- * previous device, aligned to a double word and clear of explicit placements.
389
- */
390
- function placeAssemblies<
391
- T extends { id: string; region: "I" | "Q"; size: number; address?: string },
392
- >(regions: T[], generated: boolean): (T & { address: string })[] {
393
- const placed = regions.flatMap(({ region, size, address }) =>
394
- address
395
- ? [{ region, start: Number(address.slice(3)), end: Number(address.slice(3)) + size }]
396
- : [],
397
- );
398
- const cursors = { I: 0, Q: 0 };
399
- return regions.map((selection) => {
400
- const { id, region, size, address } = selection;
401
- if (address) return { ...selection, address };
402
- if (!generated)
403
- throw new Error(
404
- `${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`,
405
- );
406
- const aligned = (offset: number) => Math.ceil(offset / 4) * 4;
407
- let start = aligned(cursors[region]);
408
- for (let blocked = true; blocked;) {
409
- const overlap = placed.find(
410
- (item) => item.region === region && item.start < start + size && start < item.end,
411
- );
412
- blocked = overlap !== undefined;
413
- if (overlap) start = aligned(overlap.end);
414
- }
415
- placed.push({ region, start, end: start + size });
416
- cursors[region] = start + size;
417
- return { ...selection, address: `%${region}B${start}` };
418
- });
419
- }
420
-
421
- const addressWidths: Record<number, string> = { 1: "X", 8: "B", 16: "W", 32: "D" };
422
-
423
- /** Bits, bytes, words and dwords are directly addressable when aligned to their own width. */
424
- function directAddress(
425
- region: "I" | "Q",
426
- base: number,
427
- offsetBits: number,
428
- bits: number,
429
- ): string | undefined {
430
- const width = addressWidths[bits];
431
- if (!width) return undefined;
432
- const byte = base + Math.floor(offsetBits / 8);
433
- if (bits === 1) return `%${region}X${byte}.${offsetBits % 8}`;
434
- if ((base * 8 + offsetBits) % bits) return undefined;
435
- return `%${region}${width}${byte / (bits / 8)}`;
436
- }
437
-
438
- /** A register's channels: its value and write trigger, then the Modbus client's status and answer count. */
439
- function modbusChannels(
440
- device: string,
441
- name: string,
442
- outputBase: number,
443
- inputBase: number,
444
- ): IoChannel[] {
445
- const channel = (
446
- field: string,
447
- direction: "input" | "output",
448
- offsetBits: number,
449
- bits: number,
450
- type: string,
451
- description: string,
452
- ): IoChannel => ({
453
- device,
454
- id: `modbus.${name}.${field}`,
455
- name: `${name} ${field}`,
456
- direction,
457
- offsetBits,
458
- bits,
459
- type,
460
- address: directAddress(
461
- direction === "input" ? "I" : "Q",
462
- direction === "input" ? inputBase : outputBase,
463
- offsetBits,
464
- bits,
465
- ),
466
- unit: "",
467
- description,
468
- });
469
- return [
470
- channel("value", "output", 0, 16, "WORD", "Value to write"),
471
- channel("write", "output", 16, 1, "BOOL", "Writes the value when it rises"),
472
- channel(
473
- "status",
474
- "input",
475
- 0,
476
- 8,
477
- "BYTE",
478
- "The last answer: 0 accepted, otherwise the exception code",
479
- ),
480
- channel("requests", "input", 32, 32, "UDINT", "Requests the device answered"),
481
- ];
482
- }
483
-
484
- function assemblyChannels(
485
- device: string,
486
- direction: "input" | "output",
487
- instance: number,
488
- members: EdsMember[],
489
- base: number,
490
- payloadSize: number,
491
- ): IoChannel[] {
492
- const prefix = `${direction}s`,
493
- region = direction === "input" ? "I" : "Q",
494
- payloadBits = payloadSize * 8;
495
- const address = (offsetBits: number, bits: number) =>
496
- directAddress(region, base, offsetBits, bits);
497
- const channels: IoChannel[] = [];
498
- for (let i = 0; i < payloadSize; i++) {
499
- const key = `${prefix}.Byte${i}`;
500
- channels.push({
501
- device,
502
- id: key,
503
- name: `Byte ${i}`,
504
- direction,
505
- assembly: instance,
506
- offsetBits: i * 8,
507
- bits: 8,
508
- type: "BYTE",
509
- address: address(i * 8, 8),
510
- unit: "",
511
- description: "Assembly payload byte",
512
- });
513
- for (let bit = 0; bit < 8; bit++)
514
- channels.push({
515
- device,
516
- id: `${key}.Bit${bit}`,
517
- parent: key,
518
- name: `Bit ${bit}`,
519
- direction,
520
- assembly: instance,
521
- offsetBits: i * 8 + bit,
522
- bits: 1,
523
- type: "BOOL",
524
- address: address(i * 8 + bit, 1),
525
- unit: "",
526
- description: "Assembly payload bit",
527
- });
528
- }
529
- // Repeated parameter names are indexed in assembly order.
530
- const named = members
531
- .filter((member) => member.parameter)
532
- .map((member) => ({ member, name: member.name.replace(/[^\w]/g, "_") }));
533
- const occurrences = new Map<string, number>();
534
- for (const { name } of named) occurrences.set(name, (occurrences.get(name) ?? 0) + 1);
535
- const counts = new Map<string, number>();
536
- for (const { member, name } of named) {
537
- if (member.offsetBits >= payloadBits) continue;
538
- const count = counts.get(name) ?? 0;
539
- counts.set(name, count + 1);
540
- const key = `${prefix}.${name}${occurrences.get(name)! > 1 ? `[${count}]` : ""}`;
541
- const scalarBits = iecTypeBits[member.type];
542
- const channel: IoChannel = {
543
- device,
544
- id: key,
545
- name: member.name,
546
- direction,
547
- assembly: instance,
548
- offsetBits: member.offsetBits,
549
- bits: member.bits,
550
- type: member.type,
551
- address: scalarBits === member.bits ? address(member.offsetBits, member.bits) : undefined,
552
- unit: member.unit,
553
- description: member.description,
554
- };
555
- const span =
556
- scalarBits !== undefined &&
557
- scalarBits >= 8 &&
558
- member.bits > scalarBits &&
559
- member.bits % scalarBits === 0 &&
560
- member.offsetBits % scalarBits === 0;
561
- if (!span) {
562
- if (member.offsetBits + member.bits <= payloadBits) channels.push(channel);
563
- continue;
564
- }
565
- const length = Math.floor(Math.min(member.bits, payloadBits - member.offsetBits) / scalarBits);
566
- channel.type = `ARRAY[0..${length - 1}] OF ${member.type}`;
567
- channel.bits = length * scalarBits;
568
- // The whole span binds to a logical FixedArray at its first element's address.
569
- channel.address = address(member.offsetBits, scalarBits);
570
- channels.push(channel);
571
- for (let index = 0; index < length; index++) {
572
- const offset = member.offsetBits + index * scalarBits;
573
- channels.push({
574
- ...channel,
575
- id: `${key}[${index}]`,
576
- parent: key,
577
- name: `${member.name}[${index}]`,
578
- type: member.type,
579
- bits: scalarBits,
580
- offsetBits: offset,
581
- address: address(offset, scalarBits),
582
- });
583
- }
584
- }
585
- return channels;
59
+ const entries = await readdir(directory, { withFileTypes: true }).catch(
60
+ (cause: unknown) => {
61
+ if (
62
+ cause &&
63
+ typeof cause === "object" &&
64
+ "code" in cause &&
65
+ cause.code === "ENOENT"
66
+ ) {
67
+ return [];
68
+ }
69
+ throw cause;
70
+ },
71
+ );
72
+ const files: string[] = [];
73
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
74
+ const path = resolve(directory, entry.name);
75
+ if (entry.isDirectory()) {
76
+ files.push(...(await edsFiles(path)));
77
+ } else if (entry.isFile() && /\.eds$/i.test(entry.name)) {
78
+ files.push(path);
79
+ }
80
+ }
81
+ return files;
82
+ }
83
+
84
+ /** Every descriptor under the `eds` directories, then each device's own file. */
85
+ async function readDescriptors(
86
+ config: ResolvedTsplcConfig,
87
+ root: string,
88
+ ): Promise<HardwareDescriptor[]> {
89
+ const files = new Set<string>();
90
+ for (const directory of [config.eds].flat()) {
91
+ for (const file of await edsFiles(resolve(root, directory))) {
92
+ files.add(file);
93
+ }
94
+ }
95
+ for (const device of Object.values(config.devices)) {
96
+ files.add(resolve(root, device.file));
97
+ }
98
+ return Promise.all(
99
+ [...files].map(async (file) =>
100
+ parseEds(await readFile(file, "utf8"), file),
101
+ ),
102
+ );
586
103
  }
587
104
 
588
105
  export async function loadHardware(
589
- config: ResolvedTsplcConfig,
590
- root: string,
106
+ config: ResolvedTsplcConfig,
107
+ root: string,
591
108
  ): Promise<HardwareCatalog> {
592
- const files = new Set<string>();
593
- for (const directory of [config.eds].flat())
594
- for (const file of await edsFiles(resolve(root, directory))) files.add(file);
595
- for (const device of Object.values(config.devices)) files.add(resolve(root, device.file));
596
- const descriptors = await Promise.all(
597
- [...files].map(async (file) => parseEds(await readFile(file, "utf8"), file)),
598
- );
599
- const selected = Object.entries(config.devices).map(([id, settings]) => {
600
- const descriptor = descriptors.find((d) => d.file === resolve(root, settings.file))!;
601
- const connection = selectConnection(id, settings, descriptor);
602
- const selections = (["input", "output"] as const).flatMap((direction) => {
603
- const selection = direction === "input" ? settings.inputs : settings.outputs;
604
- const instance =
605
- selection?.assembly ??
606
- (direction === "input" ? connection?.inputAssembly : connection?.outputAssembly);
607
- if (instance === undefined) {
608
- if (selection) throw new Error(`${id}: select its ${direction}s assembly.`);
609
- return [];
610
- }
611
- const assembly = descriptor.assemblies.find((a) => a.instance === instance);
612
- if (!assembly)
613
- throw new Error(`${id}: assembly ${instance} is not present in ${settings.file}.`);
614
- const region = direction === "input" ? ("I" as const) : ("Q" as const);
615
- if (selection?.address && !selection.address.startsWith(`%${region}B`))
616
- throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
617
- const declaredSize = direction === "input" ? connection?.inputSize : connection?.outputSize;
618
- const payloadSize = selection?.size ?? declaredSize?.value ?? assembly.size;
619
- // A parameter-backed size may be overridden within its bounds; a literal size is fixed.
620
- if (
621
- !Number.isSafeInteger(payloadSize) ||
622
- payloadSize <= 0 ||
623
- payloadSize > assembly.size ||
624
- (declaredSize?.minimum !== undefined && payloadSize < declaredSize.minimum) ||
625
- (declaredSize?.maximum !== undefined && payloadSize > declaredSize.maximum) ||
626
- (selection?.size !== undefined &&
627
- declaredSize &&
628
- !declaredSize.parameter &&
629
- payloadSize !== declaredSize.value)
630
- )
631
- throw new Error(
632
- `${id}: ${direction} payload size ${payloadSize} is outside the selected EDS connection's bounds.`,
633
- );
634
- return [
635
- {
636
- id,
637
- direction,
638
- region,
639
- instance,
640
- assembly,
641
- size: payloadSize,
642
- address: selection?.address,
643
- },
644
- ];
645
- });
646
- return { id, settings, descriptor, connection, selections };
647
- });
648
- // After every assembly, so adding a register leaves the existing process image in place.
649
- const modbusBytes = { Q: 4, I: 8 };
650
- const modbusRegions = selected.flatMap(({ id, settings }) => {
651
- const count = Object.keys(settings.modbus?.registers ?? {}).length;
652
- return count
653
- ? (["Q", "I"] as const).map((region) => ({
654
- id,
655
- region,
656
- size: count * modbusBytes[region],
657
- modbus: true as const,
658
- }))
659
- : [];
660
- });
661
- const placed = placeAssemblies<
662
- (typeof selected)[number]["selections"][number] | (typeof modbusRegions)[number]
663
- >(
664
- [...selected.flatMap((device) => device.selections), ...modbusRegions],
665
- config.codesys?.deviceTree !== undefined,
666
- );
667
- const devices = selected.map(({ id, settings, descriptor, connection }) => {
668
- const assemblies: SelectedAssembly[] = [];
669
- const channels: IoChannel[] = [];
670
- const modbusBase = (region: "Q" | "I") =>
671
- Number(
672
- placed
673
- .find((item) => item.id === id && "modbus" in item && item.region === region)!
674
- .address.slice(3),
675
- );
676
- const registers = Object.entries(settings.modbus?.registers ?? {}).map(
677
- ([name, offset], index) => {
678
- const registerChannels = modbusChannels(
679
- id,
680
- name,
681
- modbusBase("Q") + index * modbusBytes.Q,
682
- modbusBase("I") + index * modbusBytes.I,
683
- );
684
- channels.push(...registerChannels);
685
- const [value, write, status, requests] = registerChannels.map(
686
- (channel) => channel.address!,
687
- );
688
- return { name, offset, value: value!, write: write!, status: status!, requests: requests! };
689
- },
690
- );
691
- for (const selection of placed.filter((selection) => selection.id === id)) {
692
- if ("modbus" in selection) continue;
693
- const { direction, instance, assembly, size, address } = selection;
694
- assemblies.push({
695
- direction,
696
- instance,
697
- name: assembly.name,
698
- address,
699
- size,
700
- capacity: assembly.size,
701
- });
702
- channels.push(
703
- ...assemblyChannels(
704
- id,
705
- direction,
706
- instance,
707
- assembly.members,
708
- Number(address.slice(3)),
709
- size,
710
- ),
711
- );
712
- }
713
- return {
714
- id,
715
- descriptor: descriptor.file,
716
- connection: connection && { id: connection.id, name: connection.name, path: connection.path },
717
- assemblies,
718
- channels,
719
- statusSymbols: settings.statusSymbols ?? {},
720
- ...(settings.modbus && { modbus: { port: settings.modbus.port, registers } }),
721
- };
722
- });
723
- return { descriptors, devices };
724
- }
725
- export function resolveIo(config: ResolvedTsplcConfig, catalog: HardwareCatalog) {
726
- return Object.fromEntries(
727
- Object.entries(config.io).map(([symbol, binding]) => {
728
- if ("address" in binding) return [symbol, binding];
729
- const device = catalog.devices.find((d) => d.id === binding.device);
730
- const channel = device?.channels.find((c) => c.id === binding.channel);
731
- if (!channel?.address)
732
- throw new Error(
733
- `${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`,
734
- );
735
- return [
736
- symbol,
737
- {
738
- address: channel.address,
739
- type: channel.type,
740
- ...(binding.inverted && { inverted: true }),
741
- ...(binding.shared && { shared: true }),
742
- },
743
- ];
744
- }),
745
- );
746
- }
747
- /** A bindable `io` key with its layout; array indexes appear as the literal `${number}`. */
748
- export interface IoTarget {
749
- key: string;
750
- layout: string;
751
- }
752
-
753
- export interface ProjectTargets {
754
- io: readonly IoTarget[];
755
- publication: readonly string[];
756
- }
757
-
758
- const timeLayouts = new Map([
759
- ["TIME", "TIME"],
760
- ["DATE", "DATE"],
761
- ["TOD", "TIME_OF_DAY"],
762
- ["TIME_OF_DAY", "TIME_OF_DAY"],
763
- ["DT", "DATE_AND_TIME"],
764
- ["DATE_AND_TIME", "DATE_AND_TIME"],
765
- ]);
766
-
767
- export function ioScalarBits(type: string): number | undefined {
768
- const name = type.trim().toUpperCase();
769
- return timeLayouts.has(name) ? 32 : iecTypeBits[name];
770
- }
771
-
772
- /**
773
- * Binding classes group integers and bit strings by width, BOOL, floats and time types
774
- * by domain, and non-BOOL arrays by element class and length.
775
- */
776
- export function ioLayout(type: string): string | undefined {
777
- const array = /^ARRAY\s*\[\s*(-?\d+)\s*\.\.\s*(-?\d+)\s*\]\s*OF\s+(\w+)$/i.exec(type.trim());
778
- if (array) {
779
- const element = ioLayout(array[3]!);
780
- return element && element !== "BOOL"
781
- ? `${Number(array[2]) - Number(array[1]) + 1}x${element}`
782
- : undefined;
783
- }
784
- const name = type.trim().toUpperCase();
785
- if (name === "BOOL" || name === "REAL" || name === "LREAL") return name;
786
- const bits = ioScalarBits(name);
787
- return timeLayouts.get(name) ?? (bits ? `INT${bits}` : undefined);
788
- }
789
-
790
- // Direct addresses by the width of one element; 64-bit layouts have no direct form.
791
- const directWidths: Record<string, string> = {
792
- BOOL: "X",
793
- INT8: "B",
794
- INT16: "W",
795
- INT32: "D",
796
- REAL: "D",
797
- };
798
- const directBinding = (layout: string): string | undefined => {
799
- const scalar = layout.replace(/^\d+x/, "");
800
- const width = timeLayouts.has(scalar) ? "D" : directWidths[scalar];
801
- if (!width) return undefined;
802
- return width === "X"
803
- ? '{ address: `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }'
804
- : `{ address: \`%\${"I" | "Q"}${width}\${number}\`; type?: string }`;
805
- };
806
-
807
- /**
808
- * With `targets` from a compiled TS project, `HardwareIoMapping` accepts only those
809
- * keys, each with channels or direct addresses of a compatible layout. Without them
810
- * (raw ST projects) any key is accepted and the build checks it.
811
- */
812
- export function generateHardwareTypes(
813
- catalog: HardwareCatalog,
814
- targets?: readonly IoTarget[],
815
- publication?: readonly string[],
816
- ioTypes = true,
817
- ): string {
818
- const selectors =
819
- publication?.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
820
- 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`;
821
- if (!ioTypes) return publicationTypes;
822
- // Spelled per member: intersecting the whole union makes TypeScript distribute it over every channel.
823
- const channel = (device: string, id: string, options: string) =>
824
- `{ device: ${JSON.stringify(device)}; channel: ${JSON.stringify(id)}${options} }`;
825
- const channels = catalog.devices.flatMap((device) =>
826
- device.channels
827
- .filter((item) => item.address)
828
- .map((item) => ({
829
- binding: channel(
830
- device.id,
831
- item.id,
832
- item.direction === "input" && item.type === "BOOL"
833
- ? "; inverted?: boolean; shared?: boolean"
834
- : "",
835
- ),
836
- layout: ioLayout(item.type),
837
- })),
838
- );
839
- const direct =
840
- '{ address: `%${"I" | "Q"}${"B" | "W" | "D"}${number}` | `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }';
841
- const anyBinding = [...channels.map((item) => item.binding), direct].join("\n | ");
842
- const mapping = targets
843
- ? [...new Set(targets.map((target) => target.layout))]
844
- .sort()
845
- .map((layout) => {
846
- const keys = targets
847
- .filter((target) => target.layout === layout)
848
- .map((target) => `\`${target.key}\``);
849
- const bindings = [
850
- ...channels.filter((item) => item.layout === layout).map((item) => item.binding),
851
- directBinding(layout),
852
- ].filter(Boolean);
853
- return `{\n readonly [K in ${keys.join(" | ")}]?: ${bindings.join(" | ") || "never"};\n}`;
854
- })
855
- .join(" & ") || "Readonly<Record<string, never>>"
856
- : "Readonly<Record<string, HardwareIoBinding>>";
857
- return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};\nexport type HardwareIoMapping = ${mapping};\nexport const hardware = ${JSON.stringify(catalog, null, 2)} as const;\n`;
109
+ const descriptors = await readDescriptors(config, root);
110
+ const selected = Object.entries(config.devices).map(([id, settings]) => {
111
+ const descriptor = descriptors.find(
112
+ (d) => d.file === resolve(root, settings.file),
113
+ )!;
114
+ const connection = selectConnection(id, settings, descriptor);
115
+ const selections = selectAssemblies(id, settings, descriptor, connection);
116
+ return { id, settings, descriptor, connection, selections };
117
+ });
118
+ const place = regionPlacer(
119
+ selected.flatMap((device) => device.selections),
120
+ { generatedTree: config.codesys?.deviceTree !== undefined },
121
+ );
122
+ const placed = selected.map((device) => ({
123
+ ...device,
124
+ assemblies: device.selections.map((selection) => ({
125
+ ...selection,
126
+ address: place(selection),
127
+ })),
128
+ }));
129
+ // Registers are placed after every assembly, so adding one leaves the existing process image in place.
130
+ const devices = placed.map(
131
+ ({ id, settings, descriptor, connection, assemblies }) => {
132
+ const registers = placeModbusRegisters(
133
+ id,
134
+ settings.modbus?.registers ?? {},
135
+ place,
136
+ );
137
+ return {
138
+ id,
139
+ descriptor: descriptor.file,
140
+ connection: connection && {
141
+ id: connection.id,
142
+ name: connection.name,
143
+ path: connection.path,
144
+ },
145
+ assemblies: assemblies.map(
146
+ ({ direction, instance, assembly, size, address }) => ({
147
+ direction,
148
+ instance,
149
+ name: assembly.name,
150
+ address,
151
+ size,
152
+ capacity: assembly.size,
153
+ }),
154
+ ),
155
+ channels: [
156
+ ...registers.flatMap((register) => register.channels),
157
+ ...assemblies.flatMap(
158
+ ({ direction, instance, assembly, size, address }) =>
159
+ assemblyChannels({
160
+ device: id,
161
+ direction,
162
+ instance,
163
+ members: assembly.members,
164
+ base: byteOffset(address),
165
+ payloadSize: size,
166
+ }),
167
+ ),
168
+ ],
169
+ statusSymbols: settings.statusSymbols ?? {},
170
+ ...(settings.modbus && {
171
+ modbus: {
172
+ port: settings.modbus.port,
173
+ registers: registers.map(({ register }) => register),
174
+ },
175
+ }),
176
+ };
177
+ },
178
+ );
179
+ return { descriptors, devices };
180
+ }
181
+
182
+ export function resolveIo(
183
+ config: ResolvedTsplcConfig,
184
+ catalog: HardwareCatalog,
185
+ ) {
186
+ return Object.fromEntries(
187
+ Object.entries(config.io).map(([symbol, binding]) => {
188
+ if ("address" in binding) {
189
+ return [symbol, binding];
190
+ }
191
+ const device = catalog.devices.find((d) => d.id === binding.device);
192
+ const channel = device?.channels.find((c) => c.id === binding.channel);
193
+ if (!channel?.address) {
194
+ throw new Error(
195
+ `${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`,
196
+ );
197
+ }
198
+ return [
199
+ symbol,
200
+ {
201
+ address: channel.address,
202
+ type: channel.type,
203
+ ...(binding.inverted && { inverted: true }),
204
+ ...(binding.shared && { shared: true }),
205
+ },
206
+ ];
207
+ }),
208
+ );
858
209
  }