@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.
- package/README.md +29 -3
- package/dist/cli.js +609 -433
- package/dist/cli.js.map +21 -16
- package/dist/codegen.js +242 -192
- package/dist/codegen.js.map +8 -6
- package/dist/declarations.js +277 -138
- package/dist/declarations.js.map +8 -7
- package/dist/hardware.js +383 -114
- package/dist/hardware.js.map +13 -10
- package/dist/index.js +652 -468
- package/dist/index.js.map +21 -17
- package/dist/project-snapshot.js +17 -19
- package/dist/project-snapshot.js.map +5 -4
- package/package.json +3 -3
- package/src/cli.ts +25 -33
- package/src/codegen/constants.ts +19 -25
- package/src/codegen/declarations.ts +12 -39
- package/src/codegen/generate.ts +118 -179
- package/src/codegen/parser.ts +121 -63
- package/src/codegen/resolution.ts +68 -0
- package/src/device-tree.ts +14 -97
- package/src/files.ts +40 -0
- package/src/hardware/catalog.ts +49 -0
- package/src/hardware/channels.ts +12 -5
- package/src/hardware/eds.ts +229 -45
- package/src/hardware/mapping-types.ts +58 -21
- package/src/hardware/modbus.ts +42 -28
- package/src/hardware/process-image.ts +57 -24
- package/src/hardware/selection.ts +25 -9
- package/src/hardware.ts +56 -77
- package/src/index.ts +4 -7
- package/src/outputs.ts +50 -0
- package/src/project-snapshot.ts +13 -25
- package/src/project.ts +108 -136
package/dist/hardware.js
CHANGED
|
@@ -1,12 +1,50 @@
|
|
|
1
1
|
// packages/typegen/src/hardware.ts
|
|
2
|
-
import {
|
|
2
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
|
+
import { tsplcConfigSchema } from "@tsplc/config/schema";
|
|
5
|
+
|
|
6
|
+
// packages/typegen/src/files.ts
|
|
7
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
var isMissingFile = (error) => error instanceof Error && ("code" in error) && error.code === "ENOENT";
|
|
10
|
+
async function filesUnder(directory, extension, order) {
|
|
11
|
+
const pattern = new RegExp(`\\.${extension}$`, "i");
|
|
12
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
13
|
+
const paths = await Promise.all(entries.sort((a, b) => order(a.name, b.name)).map(async (entry) => {
|
|
14
|
+
const path = join(directory, entry.name);
|
|
15
|
+
if (entry.isDirectory()) {
|
|
16
|
+
return filesUnder(path, extension, order);
|
|
17
|
+
}
|
|
18
|
+
return entry.isFile() && pattern.test(entry.name) ? [path] : [];
|
|
19
|
+
}));
|
|
20
|
+
return paths.flat();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// packages/typegen/src/hardware/catalog.ts
|
|
24
|
+
var deviceChannel = (catalog, binding) => catalog.devices.find((device) => device.id === binding.device)?.channels.find((channel) => channel.id === binding.channel);
|
|
25
|
+
function boundChannel(catalog, symbol, binding) {
|
|
26
|
+
const channel = deviceChannel(catalog, binding);
|
|
27
|
+
if (!channel?.address) {
|
|
28
|
+
throw new Error(`${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`);
|
|
29
|
+
}
|
|
30
|
+
return { ...channel, address: channel.address };
|
|
31
|
+
}
|
|
4
32
|
|
|
5
33
|
// packages/typegen/src/hardware/channels.ts
|
|
6
|
-
import { ioScalarBits } from "@tsplc/iec";
|
|
34
|
+
import { arrayTypeText, ioScalarBits } from "@tsplc/iec";
|
|
7
35
|
|
|
8
36
|
// packages/typegen/src/hardware/process-image.ts
|
|
9
|
-
import {
|
|
37
|
+
import {
|
|
38
|
+
elementaryTypes,
|
|
39
|
+
ioArray,
|
|
40
|
+
ioScalar,
|
|
41
|
+
isIntegerValued,
|
|
42
|
+
isWholeValue,
|
|
43
|
+
sizePrefix,
|
|
44
|
+
sizePrefixes
|
|
45
|
+
} from "@tsplc/iec";
|
|
46
|
+
var scalarLayout = (scalar) => isIntegerValued(scalar) ? `INT${scalar.bits}` : scalar.name;
|
|
47
|
+
var scalarLayoutBits = new Map(elementaryTypes.filter(isWholeValue).map((scalar) => [scalarLayout(scalar), scalar.bits]));
|
|
10
48
|
function ioLayout(type) {
|
|
11
49
|
const array = ioArray(type.trim());
|
|
12
50
|
if (array) {
|
|
@@ -14,11 +52,9 @@ function ioLayout(type) {
|
|
|
14
52
|
return element && element !== "BOOL" ? `${array.length}x${element}` : undefined;
|
|
15
53
|
}
|
|
16
54
|
const scalar = ioScalar(type);
|
|
17
|
-
|
|
18
|
-
return `INT${scalar.bits}`;
|
|
19
|
-
}
|
|
20
|
-
return scalar?.name;
|
|
55
|
+
return scalar && scalarLayout(scalar);
|
|
21
56
|
}
|
|
57
|
+
var layoutBits = (layout) => scalarLayoutBits.get(layout.replace(/^\d+x/, ""));
|
|
22
58
|
var addressSize = (bits) => bits === 64 ? undefined : sizePrefix(bits);
|
|
23
59
|
function directAddress(region, base, offsetBits, bits) {
|
|
24
60
|
const size = addressSize(bits);
|
|
@@ -34,20 +70,24 @@ function directAddress(region, base, offsetBits, bits) {
|
|
|
34
70
|
}
|
|
35
71
|
return `%${region}${size}${byte / (bits / 8)}`;
|
|
36
72
|
}
|
|
37
|
-
|
|
73
|
+
function addressBits(address) {
|
|
74
|
+
const [, region, size, index, bit] = /^%([IQ])([A-Z])(\d+)(?:\.([0-7]))?$/.exec(address) ?? [];
|
|
75
|
+
const bits = size === undefined ? undefined : sizePrefixes.get(size)?.bits;
|
|
76
|
+
if (region !== "I" && region !== "Q" || bits === undefined || addressSize(bits) !== size || bits === 1 !== (bit !== undefined)) {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const offsetBits = bits === 1 ? Number(index) * 8 + Number(bit) : Number(index) * bits;
|
|
80
|
+
return { region, offsetBits, bits };
|
|
81
|
+
}
|
|
82
|
+
var regionOf = (direction) => direction === "input" ? "I" : "Q";
|
|
83
|
+
var isOutputAddress = (address) => address.startsWith("%Q");
|
|
38
84
|
function regionPlacer(regions, { generatedTree }) {
|
|
39
|
-
const taken = regions.flatMap(({ region, size,
|
|
40
|
-
{
|
|
41
|
-
region,
|
|
42
|
-
start: byteOffset(address),
|
|
43
|
-
end: byteOffset(address) + size
|
|
44
|
-
}
|
|
45
|
-
] : []);
|
|
85
|
+
const taken = regions.flatMap(({ region, size, offset }) => offset === undefined ? [] : [{ region, start: offset, end: offset + size }]);
|
|
46
86
|
const cursors = { I: 0, Q: 0 };
|
|
47
87
|
const aligned = (offset) => Math.ceil(offset / 4) * 4;
|
|
48
|
-
return ({ id, region, size,
|
|
49
|
-
if (
|
|
50
|
-
return
|
|
88
|
+
return ({ id, region, size, offset }) => {
|
|
89
|
+
if (offset !== undefined) {
|
|
90
|
+
return offset;
|
|
51
91
|
}
|
|
52
92
|
if (!generatedTree) {
|
|
53
93
|
throw new Error(`${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`);
|
|
@@ -59,11 +99,12 @@ function regionPlacer(regions, { generatedTree }) {
|
|
|
59
99
|
const start = clear(aligned(cursors[region]));
|
|
60
100
|
taken.push({ region, start, end: start + size });
|
|
61
101
|
cursors[region] = start + size;
|
|
62
|
-
return
|
|
102
|
+
return start;
|
|
63
103
|
};
|
|
64
104
|
}
|
|
65
105
|
|
|
66
106
|
// packages/typegen/src/hardware/channels.ts
|
|
107
|
+
var isPayloadByte = (channel) => /^(inputs|outputs)\.Byte\d+$/.test(channel.id);
|
|
67
108
|
function assemblyChannels({
|
|
68
109
|
device,
|
|
69
110
|
direction,
|
|
@@ -73,7 +114,7 @@ function assemblyChannels({
|
|
|
73
114
|
payloadSize
|
|
74
115
|
}) {
|
|
75
116
|
const prefix = `${direction}s`;
|
|
76
|
-
const region = direction
|
|
117
|
+
const region = regionOf(direction);
|
|
77
118
|
const payloadBits = payloadSize * 8;
|
|
78
119
|
const address = (offsetBits, bits) => directAddress(region, base, offsetBits, bits);
|
|
79
120
|
const channels = [];
|
|
@@ -151,7 +192,11 @@ function assemblyChannels({
|
|
|
151
192
|
const span = {
|
|
152
193
|
...channel,
|
|
153
194
|
bits: length * scalarBits,
|
|
154
|
-
type:
|
|
195
|
+
type: arrayTypeText({
|
|
196
|
+
lower: 0,
|
|
197
|
+
upper: length - 1,
|
|
198
|
+
element: member.type
|
|
199
|
+
}),
|
|
155
200
|
address: address(member.offsetBits, scalarBits)
|
|
156
201
|
};
|
|
157
202
|
channels.push(span);
|
|
@@ -190,6 +235,23 @@ var cipTypes = {
|
|
|
190
235
|
211: "DWORD",
|
|
191
236
|
212: "LWORD"
|
|
192
237
|
};
|
|
238
|
+
var connectionFields = {
|
|
239
|
+
transport: 0,
|
|
240
|
+
outputSize: 3,
|
|
241
|
+
outputFormat: 4,
|
|
242
|
+
inputSize: 6,
|
|
243
|
+
inputFormat: 7,
|
|
244
|
+
name: 12,
|
|
245
|
+
path: 14
|
|
246
|
+
};
|
|
247
|
+
var assemblyFields = {
|
|
248
|
+
name: 0,
|
|
249
|
+
path: 1,
|
|
250
|
+
size: 2,
|
|
251
|
+
descriptor: 3,
|
|
252
|
+
firstMember: 6
|
|
253
|
+
};
|
|
254
|
+
var isConnection = (key) => /^Connection\d+$/.test(key);
|
|
193
255
|
function stripComments(text) {
|
|
194
256
|
let clean = "";
|
|
195
257
|
const offsets = [];
|
|
@@ -269,14 +331,15 @@ function edsSections(text) {
|
|
|
269
331
|
if (!section) {
|
|
270
332
|
throw new Error("EDS record outside a section.");
|
|
271
333
|
}
|
|
334
|
+
const start = offsets[match.index];
|
|
335
|
+
const last = offsets[end - 1];
|
|
336
|
+
if (key === undefined || body === undefined || start === undefined || last === undefined) {
|
|
337
|
+
throw new Error("Malformed EDS record or section.");
|
|
338
|
+
}
|
|
272
339
|
if (section.has(key)) {
|
|
273
340
|
throw new Error(`Duplicate EDS record ${key}.`);
|
|
274
341
|
}
|
|
275
|
-
section.set(key, {
|
|
276
|
-
fields: recordFields(body),
|
|
277
|
-
start: offsets[match.index],
|
|
278
|
-
end: offsets[end - 1] + 1
|
|
279
|
-
});
|
|
342
|
+
section.set(key, { fields: recordFields(body), start, end: last + 1 });
|
|
280
343
|
}
|
|
281
344
|
if (clean.slice(end).trim()) {
|
|
282
345
|
throw new Error("Unterminated EDS record.");
|
|
@@ -322,21 +385,29 @@ function logicalSegments(bytes) {
|
|
|
322
385
|
...logicalSegments(data.slice(length))
|
|
323
386
|
];
|
|
324
387
|
}
|
|
325
|
-
function
|
|
326
|
-
|
|
327
|
-
if (
|
|
388
|
+
function pathBytes(path, params) {
|
|
389
|
+
return path.trim().split(/\s+/).filter(Boolean).flatMap((token) => {
|
|
390
|
+
if (/^[0-9a-f]{2}$/i.test(token)) {
|
|
391
|
+
return [parseInt(token, 16)];
|
|
392
|
+
}
|
|
393
|
+
const reference = /^\[(Param\d+)\]$/.exec(token)?.[1];
|
|
394
|
+
const parameter = reference ? params.get(reference) : undefined;
|
|
395
|
+
if (!parameter || parameter.default === undefined) {
|
|
328
396
|
throw new Error(`Unsupported EDS path token ${token}.`);
|
|
329
397
|
}
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
398
|
+
const value = parameter.default;
|
|
399
|
+
return Array.from({ length: parameter.size }, (_, index) => Math.floor(value / 2 ** (index * 8)) % 256);
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
function logicalPath(path, params) {
|
|
403
|
+
const segments = logicalSegments(pathBytes(path, params));
|
|
333
404
|
return {
|
|
334
405
|
instance: segments.filter(({ type }) => type === 36).at(-1)?.value,
|
|
335
406
|
points: segments.filter(({ type }) => type === 44).map(({ value }) => value)
|
|
336
407
|
};
|
|
337
408
|
}
|
|
338
409
|
var optionalNumber = (value) => value?.trim() && Number.isFinite(Number(value)) ? Number(value) : undefined;
|
|
339
|
-
function parseEds(text, file
|
|
410
|
+
function parseEds(text, file) {
|
|
340
411
|
const records = readEdsRecords(text);
|
|
341
412
|
const device = records.Device;
|
|
342
413
|
if (!device?.ProdName?.[0]) {
|
|
@@ -355,6 +426,7 @@ function parseEds(text, file = "device.eds") {
|
|
|
355
426
|
}));
|
|
356
427
|
const params = new Map(parameters.map((parameter) => [parameter.id, parameter]));
|
|
357
428
|
const instances = new Map;
|
|
429
|
+
const recordless = new Map;
|
|
358
430
|
const size = (value) => {
|
|
359
431
|
if (!value) {
|
|
360
432
|
return;
|
|
@@ -373,18 +445,24 @@ function parseEds(text, file = "device.eds") {
|
|
|
373
445
|
maximum: parameter.maximum
|
|
374
446
|
};
|
|
375
447
|
};
|
|
376
|
-
const connections = Object.entries(records["Connection Manager"] ?? {}).filter(([id]) =>
|
|
377
|
-
const path = fields[
|
|
378
|
-
const points = logicalPath(path).points;
|
|
379
|
-
const
|
|
448
|
+
const connections = Object.entries(records["Connection Manager"] ?? {}).filter(([id]) => isConnection(id)).map(([id, fields]) => {
|
|
449
|
+
const path = fields[connectionFields.path] ?? "";
|
|
450
|
+
const points = logicalPath(path, params).points;
|
|
451
|
+
const outputSize = size(fields[connectionFields.outputSize]);
|
|
452
|
+
const inputSize = size(fields[connectionFields.inputSize]);
|
|
453
|
+
const assembly = (reference, point, payload) => {
|
|
380
454
|
if (!reference) {
|
|
381
|
-
|
|
455
|
+
if (!payload || payload.value <= 0 || point === undefined) {
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
recordless.set(point, Math.max(recordless.get(point) ?? 0, payload.maximum ?? payload.value));
|
|
459
|
+
return point;
|
|
382
460
|
}
|
|
383
461
|
const record = records.Assembly?.[reference];
|
|
384
462
|
if (!/^Assem\d+$/.test(reference) || !record) {
|
|
385
463
|
throw new Error(`${file}: unknown connection assembly ${reference}.`);
|
|
386
464
|
}
|
|
387
|
-
const instance = point ?? logicalPath(record[
|
|
465
|
+
const instance = point ?? logicalPath(record[assemblyFields.path] ?? "", params).instance;
|
|
388
466
|
if (instance === undefined) {
|
|
389
467
|
throw new Error(`${file}: no runtime instance for ${reference}.`);
|
|
390
468
|
}
|
|
@@ -397,19 +475,19 @@ function parseEds(text, file = "device.eds") {
|
|
|
397
475
|
};
|
|
398
476
|
return {
|
|
399
477
|
id,
|
|
400
|
-
name: fields[
|
|
401
|
-
owner: /^0x[\da-f]{8}$/i.test(fields[
|
|
478
|
+
name: fields[connectionFields.name] || id,
|
|
479
|
+
owner: /^0x[\da-f]{8}$/i.test(fields[connectionFields.transport] ?? "") && (Number(fields[connectionFields.transport]) >>> 24 & 15) === 4,
|
|
402
480
|
path,
|
|
403
|
-
outputAssembly: assembly(fields[
|
|
404
|
-
inputAssembly: assembly(fields[
|
|
405
|
-
outputSize
|
|
406
|
-
inputSize
|
|
481
|
+
outputAssembly: assembly(fields[connectionFields.outputFormat], points.at(-2), outputSize),
|
|
482
|
+
inputAssembly: assembly(fields[connectionFields.inputFormat], points.at(-1), inputSize),
|
|
483
|
+
outputSize,
|
|
484
|
+
inputSize
|
|
407
485
|
};
|
|
408
486
|
});
|
|
409
487
|
const assemblies = Object.entries(records.Assembly ?? {}).filter(([id]) => /^Assem\d+$/.test(id)).map(([id, fields]) => {
|
|
410
488
|
const members = [];
|
|
411
489
|
let offsetBits = 0;
|
|
412
|
-
for (let index =
|
|
490
|
+
for (let index = assemblyFields.firstMember;index < fields.length; index += 2) {
|
|
413
491
|
if (!fields[index] && !fields[index + 1]) {
|
|
414
492
|
continue;
|
|
415
493
|
}
|
|
@@ -432,13 +510,31 @@ function parseEds(text, file = "device.eds") {
|
|
|
432
510
|
});
|
|
433
511
|
offsetBits += bits;
|
|
434
512
|
}
|
|
435
|
-
const
|
|
513
|
+
const declared = fields[assemblyFields.size];
|
|
514
|
+
const size = declared ? integer(declared, `${id} size`, { minimum: 0 }) : Math.ceil(offsetBits / 8);
|
|
436
515
|
if (offsetBits > size * 8) {
|
|
437
516
|
throw new Error(`${file}: ${id} members exceed its ${size} byte payload.`);
|
|
438
517
|
}
|
|
439
|
-
const instance = logicalPath(fields[
|
|
440
|
-
return {
|
|
518
|
+
const instance = logicalPath(fields[assemblyFields.path] ?? "", params).instance ?? instances.get(id);
|
|
519
|
+
return {
|
|
520
|
+
id,
|
|
521
|
+
instance,
|
|
522
|
+
name: fields[assemblyFields.name] || id,
|
|
523
|
+
size,
|
|
524
|
+
members
|
|
525
|
+
};
|
|
441
526
|
});
|
|
527
|
+
for (const [instance, payloadSize] of recordless) {
|
|
528
|
+
if (!assemblies.some((assembly) => assembly.instance === instance)) {
|
|
529
|
+
assemblies.push({
|
|
530
|
+
id: `Instance${instance}`,
|
|
531
|
+
instance,
|
|
532
|
+
name: `Assembly ${instance}`,
|
|
533
|
+
size: payloadSize,
|
|
534
|
+
members: []
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
}
|
|
442
538
|
return {
|
|
443
539
|
file,
|
|
444
540
|
name: device.ProdName[0],
|
|
@@ -449,29 +545,109 @@ function parseEds(text, file = "device.eds") {
|
|
|
449
545
|
connections
|
|
450
546
|
};
|
|
451
547
|
}
|
|
548
|
+
var quoted = (value) => `"${value.replaceAll('"', '""')}"`;
|
|
549
|
+
function normalizeEds(text, selection) {
|
|
550
|
+
const sections = edsSections(text);
|
|
551
|
+
const connections = [...sections.get("Connection Manager") ?? []].filter(([key]) => isConnection(key));
|
|
552
|
+
const selected = connections.find(([key]) => key === selection.connection)?.[1];
|
|
553
|
+
if (!selected) {
|
|
554
|
+
throw new Error(`EDS has no ${selection.connection}.`);
|
|
555
|
+
}
|
|
556
|
+
const fields = [...selected.fields];
|
|
557
|
+
const resized = new Map;
|
|
558
|
+
for (const [sizeField, formatField, size] of [
|
|
559
|
+
[
|
|
560
|
+
connectionFields.outputSize,
|
|
561
|
+
connectionFields.outputFormat,
|
|
562
|
+
selection.outputSize
|
|
563
|
+
],
|
|
564
|
+
[
|
|
565
|
+
connectionFields.inputSize,
|
|
566
|
+
connectionFields.inputFormat,
|
|
567
|
+
selection.inputSize
|
|
568
|
+
]
|
|
569
|
+
]) {
|
|
570
|
+
const assembly = fields[formatField];
|
|
571
|
+
if (!assembly) {
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
if (size === undefined) {
|
|
575
|
+
throw new Error(`Select a payload size for ${assembly}.`);
|
|
576
|
+
}
|
|
577
|
+
fields[sizeField] = String(size);
|
|
578
|
+
resized.set(assembly, size);
|
|
579
|
+
}
|
|
580
|
+
const edits = connections.map(([, record]) => ({
|
|
581
|
+
start: record.start,
|
|
582
|
+
end: record.end,
|
|
583
|
+
text: record === selected ? `Connection1 = ${fields.map((value, index) => index >= connectionFields.name ? quoted(value) : value).join(",")};` : ""
|
|
584
|
+
}));
|
|
585
|
+
for (const [key, record] of sections.get("Assembly") ?? []) {
|
|
586
|
+
const size = resized.get(key);
|
|
587
|
+
if (size === undefined) {
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
const path = record.fields[assemblyFields.path] ?? "";
|
|
591
|
+
const rawBytes = [
|
|
592
|
+
quoted(record.fields[assemblyFields.name] ?? ""),
|
|
593
|
+
path && quoted(path),
|
|
594
|
+
size,
|
|
595
|
+
record.fields[assemblyFields.descriptor] ?? "",
|
|
596
|
+
"",
|
|
597
|
+
"",
|
|
598
|
+
size * 8,
|
|
599
|
+
""
|
|
600
|
+
];
|
|
601
|
+
edits.push({
|
|
602
|
+
start: record.start,
|
|
603
|
+
end: record.end,
|
|
604
|
+
text: `${key} = ${rawBytes.join(",")};`
|
|
605
|
+
});
|
|
606
|
+
resized.delete(key);
|
|
607
|
+
}
|
|
608
|
+
if (resized.size) {
|
|
609
|
+
throw new Error(`EDS has no ${[...resized.keys()].join(", ")} assembly.`);
|
|
610
|
+
}
|
|
611
|
+
return edits.sort((a, b) => b.start - a.start).reduce((result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end), text);
|
|
612
|
+
}
|
|
452
613
|
|
|
453
614
|
// packages/typegen/src/hardware/modbus.ts
|
|
615
|
+
var modbusServerName = (device) => `${device}_Modbus`;
|
|
454
616
|
var registerBytes = { Q: 4, I: 8 };
|
|
455
617
|
function placeModbusRegisters(device, registers, place) {
|
|
456
618
|
const entries = Object.entries(registers);
|
|
457
619
|
if (!entries.length) {
|
|
458
620
|
return [];
|
|
459
621
|
}
|
|
460
|
-
const outputBase =
|
|
461
|
-
|
|
622
|
+
const outputBase = place({
|
|
623
|
+
id: device,
|
|
624
|
+
region: "Q",
|
|
625
|
+
size: entries.length * registerBytes.Q
|
|
626
|
+
});
|
|
627
|
+
const inputBase = place({
|
|
628
|
+
id: device,
|
|
629
|
+
region: "I",
|
|
630
|
+
size: entries.length * registerBytes.I
|
|
631
|
+
});
|
|
462
632
|
return entries.map(([name, offset], index) => {
|
|
463
|
-
const channel = (field, direction, offsetBits, bits, type, description) =>
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
633
|
+
const channel = (field, direction, offsetBits, bits, type, description) => {
|
|
634
|
+
const address = directAddress(regionOf(direction), direction === "input" ? inputBase + index * registerBytes.I : outputBase + index * registerBytes.Q, offsetBits, bits);
|
|
635
|
+
if (!address) {
|
|
636
|
+
throw new Error(`${device}: Modbus register ${name} ${field} has no direct address.`);
|
|
637
|
+
}
|
|
638
|
+
return {
|
|
639
|
+
device,
|
|
640
|
+
id: `modbus.${name}.${field}`,
|
|
641
|
+
name: `${name} ${field}`,
|
|
642
|
+
direction,
|
|
643
|
+
offsetBits,
|
|
644
|
+
bits,
|
|
645
|
+
type,
|
|
646
|
+
address,
|
|
647
|
+
unit: "",
|
|
648
|
+
description
|
|
649
|
+
};
|
|
650
|
+
};
|
|
475
651
|
const value = channel("value", "output", 0, 16, "WORD", "Value to write");
|
|
476
652
|
const write = channel("write", "output", 16, 1, "BOOL", "Writes the value when it rises");
|
|
477
653
|
const status = channel("status", "input", 0, 8, "BYTE", "The last answer: 0 accepted, otherwise the exception code");
|
|
@@ -510,6 +686,14 @@ function selectConnection(id, settings, descriptor) {
|
|
|
510
686
|
const choices = compatible.map((item) => `${item.id} "${item.name}" (in ${item.inputAssembly ?? "-"}, out ${item.outputAssembly ?? "-"})`).join(", ");
|
|
511
687
|
throw new Error(`${id}: select connection; ${settings.file} offers ${choices}.`);
|
|
512
688
|
}
|
|
689
|
+
function configuredByte(id, direction, address) {
|
|
690
|
+
const region = regionOf(direction);
|
|
691
|
+
const location = addressBits(address);
|
|
692
|
+
if (location?.region !== region || location.bits !== 8) {
|
|
693
|
+
throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
|
|
694
|
+
}
|
|
695
|
+
return location.offsetBits / 8;
|
|
696
|
+
}
|
|
513
697
|
function selectAssemblies(id, settings, descriptor, connection) {
|
|
514
698
|
return ["input", "output"].flatMap((direction) => {
|
|
515
699
|
const selection = direction === "input" ? settings.inputs : settings.outputs;
|
|
@@ -524,10 +708,8 @@ function selectAssemblies(id, settings, descriptor, connection) {
|
|
|
524
708
|
if (!assembly) {
|
|
525
709
|
throw new Error(`${id}: assembly ${instance} is not present in ${settings.file}.`);
|
|
526
710
|
}
|
|
527
|
-
const region = direction
|
|
528
|
-
|
|
529
|
-
throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
|
|
530
|
-
}
|
|
711
|
+
const region = regionOf(direction);
|
|
712
|
+
const offset = selection?.address === undefined ? undefined : configuredByte(id, direction, selection.address);
|
|
531
713
|
const declaredSize = direction === "input" ? connection?.inputSize : connection?.outputSize;
|
|
532
714
|
const payloadSize = selection?.size ?? declaredSize?.value ?? assembly.size;
|
|
533
715
|
if (!Number.isSafeInteger(payloadSize) || payloadSize <= 0 || payloadSize > assembly.size || declaredSize?.minimum !== undefined && payloadSize < declaredSize.minimum || declaredSize?.maximum !== undefined && payloadSize > declaredSize.maximum || selection?.size !== undefined && declaredSize && !declaredSize.parameter && payloadSize !== declaredSize.value) {
|
|
@@ -541,29 +723,117 @@ function selectAssemblies(id, settings, descriptor, connection) {
|
|
|
541
723
|
instance,
|
|
542
724
|
assembly,
|
|
543
725
|
size: payloadSize,
|
|
544
|
-
|
|
726
|
+
offset
|
|
545
727
|
}
|
|
546
728
|
];
|
|
547
729
|
});
|
|
548
730
|
}
|
|
549
731
|
|
|
550
732
|
// packages/typegen/src/hardware.ts
|
|
551
|
-
import { ioScalarBits as
|
|
733
|
+
import { ioScalarBits as ioScalarBits2 } from "@tsplc/iec";
|
|
552
734
|
|
|
735
|
+
// packages/typegen/src/device-tree.ts
|
|
736
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
737
|
+
import { iecName } from "@tsplc/config/build";
|
|
738
|
+
async function deviceTree(config, catalog) {
|
|
739
|
+
const settings = config.codesys?.deviceTree;
|
|
740
|
+
if (!settings) {
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
const devices = await Promise.all(catalog.devices.map(async (device) => {
|
|
744
|
+
if (!iecName.safeParse(device.id).success) {
|
|
745
|
+
throw new Error(`${device.id}: a device tree adapter needs an IEC identifier name.`);
|
|
746
|
+
}
|
|
747
|
+
const connection = device.connection;
|
|
748
|
+
if (!connection) {
|
|
749
|
+
throw new Error(`${device.id}: select the connection to configure.`);
|
|
750
|
+
}
|
|
751
|
+
const region = (direction) => {
|
|
752
|
+
const assembly = device.assemblies.find((item) => item.direction === direction);
|
|
753
|
+
return assembly && { address: assembly.address, size: assembly.size };
|
|
754
|
+
};
|
|
755
|
+
const inputs = region("input");
|
|
756
|
+
const outputs = region("output");
|
|
757
|
+
const comments = Object.entries(config.io).flatMap(([key, binding]) => {
|
|
758
|
+
if (!("device" in binding) || binding.device !== device.id) {
|
|
759
|
+
return [];
|
|
760
|
+
}
|
|
761
|
+
const channel = boundChannel(catalog, key, binding);
|
|
762
|
+
if (channel.assembly === undefined) {
|
|
763
|
+
return [];
|
|
764
|
+
}
|
|
765
|
+
if (channel.bits === 1) {
|
|
766
|
+
return [{ address: channel.address, text: key }];
|
|
767
|
+
}
|
|
768
|
+
const location = addressBits(channel.address);
|
|
769
|
+
const address = location && directAddress(location.region, 0, location.offsetBits, 8);
|
|
770
|
+
if (!address) {
|
|
771
|
+
throw new Error(`${key}: channel ${binding.device}.${binding.channel} does not start on a byte.`);
|
|
772
|
+
}
|
|
773
|
+
const bytes = channel.bits / 8;
|
|
774
|
+
return [{ address, text: bytes > 1 ? `${key} (${bytes} bytes)` : key }];
|
|
775
|
+
});
|
|
776
|
+
const network = config.devices[device.id]?.network;
|
|
777
|
+
if (device.modbus && !network?.address) {
|
|
778
|
+
throw new Error(`${device.id}: Modbus registers need its network address.`);
|
|
779
|
+
}
|
|
780
|
+
return {
|
|
781
|
+
name: device.id,
|
|
782
|
+
eds: normalizeEds(await readFile2(device.descriptor, "utf8"), {
|
|
783
|
+
connection: connection.id,
|
|
784
|
+
inputSize: inputs?.size,
|
|
785
|
+
outputSize: outputs?.size
|
|
786
|
+
}),
|
|
787
|
+
...network?.address && { address: network.address },
|
|
788
|
+
...network?.rpi && {
|
|
789
|
+
rpiMicroseconds: Number(BigInt(network.rpi.nanoseconds) / 1000n)
|
|
790
|
+
},
|
|
791
|
+
...inputs && { inputs },
|
|
792
|
+
...outputs && { outputs },
|
|
793
|
+
...device.modbus && { modbus: device.modbus },
|
|
794
|
+
comments
|
|
795
|
+
};
|
|
796
|
+
}));
|
|
797
|
+
const [first, ...rest] = devices;
|
|
798
|
+
if (!first) {
|
|
799
|
+
throw new Error("A generated device tree needs at least one device.");
|
|
800
|
+
}
|
|
801
|
+
return { ethernet: settings.ethernet ?? {}, devices: [first, ...rest] };
|
|
802
|
+
}
|
|
553
803
|
// packages/typegen/src/hardware/mapping-types.ts
|
|
554
|
-
import {
|
|
804
|
+
import { relative, sep } from "node:path";
|
|
805
|
+
import { sizePrefixes as sizePrefixes2 } from "@tsplc/iec";
|
|
806
|
+
var region = '${"I" | "Q"}';
|
|
807
|
+
var bitAddress = `\`%${region}X\${number}.\${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}\``;
|
|
808
|
+
var byteSizes = [...sizePrefixes2].filter(([prefix, type]) => type.bits > 1 && addressSize(type.bits) === prefix).map(([prefix]) => JSON.stringify(prefix)).join(" | ");
|
|
809
|
+
var addressBinding = (address) => `{ address: ${address}; type?: string }`;
|
|
555
810
|
var directBinding = (layout) => {
|
|
556
|
-
const
|
|
557
|
-
const integer = /^INT(\d+)$/.exec(scalar);
|
|
558
|
-
const bits = integer ? Number(integer[1]) : ioScalarBits2(scalar);
|
|
811
|
+
const bits = layoutBits(layout);
|
|
559
812
|
const size = bits === undefined ? undefined : addressSize(bits);
|
|
560
813
|
if (!size) {
|
|
561
814
|
return;
|
|
562
815
|
}
|
|
563
|
-
return size === "X" ?
|
|
816
|
+
return addressBinding(size === "X" ? bitAddress : `\`%${region}${size}\${number}\``);
|
|
817
|
+
};
|
|
818
|
+
var portableCatalog = (catalog, root) => {
|
|
819
|
+
const portable = (file) => relative(root, file).split(sep).join("/");
|
|
820
|
+
return {
|
|
821
|
+
descriptors: catalog.descriptors.map((descriptor) => ({
|
|
822
|
+
...descriptor,
|
|
823
|
+
file: portable(descriptor.file)
|
|
824
|
+
})),
|
|
825
|
+
devices: catalog.devices.map((device) => ({
|
|
826
|
+
...device,
|
|
827
|
+
descriptor: portable(device.descriptor)
|
|
828
|
+
}))
|
|
829
|
+
};
|
|
564
830
|
};
|
|
565
|
-
function generateHardwareTypes(catalog,
|
|
566
|
-
|
|
831
|
+
function generateHardwareTypes(catalog, {
|
|
832
|
+
root,
|
|
833
|
+
targets,
|
|
834
|
+
ioTypes
|
|
835
|
+
}) {
|
|
836
|
+
const selectors = targets?.publication.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
|
|
567
837
|
const publicationTypes = `// Generated by tsPLC. Run tsplc typegen after changing EDS files, device selections or PLC storage.
|
|
568
838
|
export type PublicationSelector = ${selectors || "never"};
|
|
569
839
|
export type PlcPublication = { readonly production: readonly PublicationSelector[]; readonly development: readonly PublicationSelector[] };
|
|
@@ -576,11 +846,11 @@ export type PlcPublication = { readonly production: readonly PublicationSelector
|
|
|
576
846
|
binding: channel(device.id, item.id, item.direction === "input" && item.type === "BOOL" ? "; inverted?: boolean; shared?: boolean" : ""),
|
|
577
847
|
layout: ioLayout(item.type)
|
|
578
848
|
})));
|
|
579
|
-
const direct =
|
|
849
|
+
const direct = addressBinding(`\`%${region}\${${byteSizes}}\${number}\` | ${bitAddress}`);
|
|
580
850
|
const anyBinding = [...channels.map((item) => item.binding), direct].join(`
|
|
581
851
|
| `);
|
|
582
|
-
const mapping = targets ? [...new Set(targets.map((target) => target.layout))].sort().map((layout) => {
|
|
583
|
-
const keys = targets.filter((target) => target.layout === layout).map((target) => `\`${target.key}\``);
|
|
852
|
+
const mapping = targets ? [...new Set(targets.io.map((target) => target.layout))].sort().map((layout) => {
|
|
853
|
+
const keys = targets.io.filter((target) => target.layout === layout).map((target) => `\`${target.key}\``);
|
|
584
854
|
const bindings = [
|
|
585
855
|
...channels.filter((item) => item.layout === layout).map((item) => item.binding),
|
|
586
856
|
directBinding(layout)
|
|
@@ -591,45 +861,37 @@ export type PlcPublication = { readonly production: readonly PublicationSelector
|
|
|
591
861
|
}).join(" & ") || "Readonly<Record<string, never>>" : "Readonly<Record<string, HardwareIoBinding>>";
|
|
592
862
|
return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};
|
|
593
863
|
export type HardwareIoMapping = ${mapping};
|
|
594
|
-
export const hardware = ${JSON.stringify(catalog, null, 2)} as const;
|
|
864
|
+
export const hardware = ${JSON.stringify(portableCatalog(catalog, root), null, 2)} as const;
|
|
595
865
|
`;
|
|
596
866
|
}
|
|
597
867
|
|
|
598
868
|
// packages/typegen/src/hardware.ts
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
}
|
|
604
|
-
throw cause;
|
|
605
|
-
});
|
|
606
|
-
const files = [];
|
|
607
|
-
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
608
|
-
const path = resolve(directory, entry.name);
|
|
609
|
-
if (entry.isDirectory()) {
|
|
610
|
-
files.push(...await edsFiles(path));
|
|
611
|
-
} else if (entry.isFile() && /\.eds$/i.test(entry.name)) {
|
|
612
|
-
files.push(path);
|
|
613
|
-
}
|
|
869
|
+
var defaultEds = tsplcConfigSchema.shape.eds.parse(undefined);
|
|
870
|
+
var edsFiles = (config, directory) => filesUnder(directory, "eds", (a, b) => a.localeCompare(b)).catch((error) => {
|
|
871
|
+
if (config.eds === defaultEds && isMissingFile(error)) {
|
|
872
|
+
return [];
|
|
614
873
|
}
|
|
615
|
-
|
|
616
|
-
}
|
|
874
|
+
throw error;
|
|
875
|
+
});
|
|
617
876
|
async function readDescriptors(config, root) {
|
|
618
877
|
const files = new Set;
|
|
619
878
|
for (const directory of [config.eds].flat()) {
|
|
620
|
-
for (const file of await edsFiles(resolve(root, directory))) {
|
|
879
|
+
for (const file of await edsFiles(config, resolve(root, directory))) {
|
|
621
880
|
files.add(file);
|
|
622
881
|
}
|
|
623
882
|
}
|
|
624
883
|
for (const device of Object.values(config.devices)) {
|
|
625
884
|
files.add(resolve(root, device.file));
|
|
626
885
|
}
|
|
627
|
-
return Promise.all([...files].map(async (file) => parseEds(await
|
|
886
|
+
return new Map(await Promise.all([...files].map(async (file) => [file, parseEds(await readFile3(file, "utf8"), file)])));
|
|
628
887
|
}
|
|
629
888
|
async function loadHardware(config, root) {
|
|
630
889
|
const descriptors = await readDescriptors(config, root);
|
|
631
890
|
const selected = Object.entries(config.devices).map(([id, settings]) => {
|
|
632
|
-
const descriptor = descriptors.
|
|
891
|
+
const descriptor = descriptors.get(resolve(root, settings.file));
|
|
892
|
+
if (!descriptor) {
|
|
893
|
+
throw new Error(`${id}: ${settings.file} was not read.`);
|
|
894
|
+
}
|
|
633
895
|
const connection = selectConnection(id, settings, descriptor);
|
|
634
896
|
const selections = selectAssemblies(id, settings, descriptor, connection);
|
|
635
897
|
return { id, settings, descriptor, connection, selections };
|
|
@@ -637,10 +899,14 @@ async function loadHardware(config, root) {
|
|
|
637
899
|
const place = regionPlacer(selected.flatMap((device) => device.selections), { generatedTree: config.codesys?.deviceTree !== undefined });
|
|
638
900
|
const placed = selected.map((device) => ({
|
|
639
901
|
...device,
|
|
640
|
-
assemblies: device.selections.map((selection) =>
|
|
641
|
-
|
|
642
|
-
address
|
|
643
|
-
|
|
902
|
+
assemblies: device.selections.map((selection) => {
|
|
903
|
+
const offset = place(selection);
|
|
904
|
+
const address = directAddress(selection.region, offset, 0, 8);
|
|
905
|
+
if (!address) {
|
|
906
|
+
throw new Error(`${device.id}: byte ${offset} has no direct address.`);
|
|
907
|
+
}
|
|
908
|
+
return { ...selection, offset, address };
|
|
909
|
+
})
|
|
644
910
|
}));
|
|
645
911
|
const devices = placed.map(({ id, settings, descriptor, connection, assemblies }) => {
|
|
646
912
|
const registers = placeModbusRegisters(id, settings.modbus?.registers ?? {}, place);
|
|
@@ -662,12 +928,12 @@ async function loadHardware(config, root) {
|
|
|
662
928
|
})),
|
|
663
929
|
channels: [
|
|
664
930
|
...registers.flatMap((register) => register.channels),
|
|
665
|
-
...assemblies.flatMap(({ direction, instance, assembly, size,
|
|
931
|
+
...assemblies.flatMap(({ direction, instance, assembly, size, offset }) => assemblyChannels({
|
|
666
932
|
device: id,
|
|
667
933
|
direction,
|
|
668
934
|
instance,
|
|
669
935
|
members: assembly.members,
|
|
670
|
-
base:
|
|
936
|
+
base: offset,
|
|
671
937
|
payloadSize: size
|
|
672
938
|
}))
|
|
673
939
|
],
|
|
@@ -680,18 +946,14 @@ async function loadHardware(config, root) {
|
|
|
680
946
|
}
|
|
681
947
|
};
|
|
682
948
|
});
|
|
683
|
-
return { descriptors, devices };
|
|
949
|
+
return { descriptors: [...descriptors.values()], devices };
|
|
684
950
|
}
|
|
685
951
|
function resolveIo(config, catalog) {
|
|
686
952
|
return Object.fromEntries(Object.entries(config.io).map(([symbol, binding]) => {
|
|
687
953
|
if ("address" in binding) {
|
|
688
954
|
return [symbol, binding];
|
|
689
955
|
}
|
|
690
|
-
const
|
|
691
|
-
const channel = device?.channels.find((c) => c.id === binding.channel);
|
|
692
|
-
if (!channel?.address) {
|
|
693
|
-
throw new Error(`${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`);
|
|
694
|
-
}
|
|
956
|
+
const channel = boundChannel(catalog, symbol, binding);
|
|
695
957
|
return [
|
|
696
958
|
symbol,
|
|
697
959
|
{
|
|
@@ -704,14 +966,21 @@ function resolveIo(config, catalog) {
|
|
|
704
966
|
}));
|
|
705
967
|
}
|
|
706
968
|
export {
|
|
969
|
+
addressBits,
|
|
970
|
+
deviceChannel,
|
|
971
|
+
deviceTree,
|
|
707
972
|
generateHardwareTypes,
|
|
708
973
|
ioLayout,
|
|
709
|
-
|
|
974
|
+
ioScalarBits2 as ioScalarBits,
|
|
975
|
+
isOutputAddress,
|
|
976
|
+
isPayloadByte,
|
|
710
977
|
loadHardware,
|
|
978
|
+
modbusServerName,
|
|
711
979
|
parseEds,
|
|
712
980
|
readEdsRecords,
|
|
981
|
+
regionOf,
|
|
713
982
|
resolveIo
|
|
714
983
|
};
|
|
715
984
|
|
|
716
|
-
//# debugId=
|
|
985
|
+
//# debugId=699B61F1D78FD42464756E2164756E21
|
|
717
986
|
//# sourceMappingURL=hardware.js.map
|