@tsplc/typegen 0.2.21 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/cli.js +241 -208
- package/dist/cli.js.map +12 -12
- package/dist/codegen.js +26 -17
- package/dist/codegen.js.map +4 -4
- package/dist/hardware.js +171 -171
- package/dist/hardware.js.map +8 -8
- package/dist/index.js +243 -213
- package/dist/index.js.map +13 -13
- package/dist/project-snapshot.js +46 -0
- package/dist/project-snapshot.js.map +10 -0
- package/package.json +20 -4
- package/src/cli.ts +1 -1
- package/src/codegen/generate.ts +10 -7
- package/src/codegen/parser.ts +21 -10
- package/src/device-tree.ts +2 -1
- package/src/hardware/channels.ts +1 -1
- package/src/hardware/eds.ts +29 -26
- package/src/hardware/mapping-types.ts +2 -1
- package/src/hardware/modbus.ts +2 -1
- package/src/hardware.ts +7 -6
- package/src/index.ts +13 -13
- package/src/project-snapshot.ts +63 -0
- package/src/project.ts +49 -22
package/dist/index.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
+
// packages/typegen/src/index.ts
|
|
2
|
+
import { ioScalarBits as ioScalarBits4 } from "@tsplc/iec";
|
|
3
|
+
|
|
1
4
|
// packages/typegen/src/codegen/generate.ts
|
|
2
5
|
import { readdir, readFile } from "node:fs/promises";
|
|
3
6
|
import { basename, join } from "node:path";
|
|
7
|
+
import { elementaryTypesByName } from "@tsplc/iec";
|
|
8
|
+
import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
|
|
4
9
|
|
|
5
10
|
// packages/typegen/src/codegen/constants.ts
|
|
6
11
|
import {
|
|
@@ -126,10 +131,6 @@ function constantResolver(lists) {
|
|
|
126
131
|
return constant;
|
|
127
132
|
}
|
|
128
133
|
|
|
129
|
-
// packages/typegen/src/codegen/generate.ts
|
|
130
|
-
import { elementaryTypesByName } from "@tsplc/iec";
|
|
131
|
-
import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
|
|
132
|
-
|
|
133
134
|
// packages/typegen/src/codegen/parser.ts
|
|
134
135
|
import {
|
|
135
136
|
blockCommentEnd,
|
|
@@ -393,6 +394,23 @@ class Parser {
|
|
|
393
394
|
}
|
|
394
395
|
globals(name) {
|
|
395
396
|
const description = this.documentation();
|
|
397
|
+
const sections = [];
|
|
398
|
+
do {
|
|
399
|
+
sections.push(this.globalSection());
|
|
400
|
+
} while (this.peek());
|
|
401
|
+
const constant = sections.every((section) => section.constant);
|
|
402
|
+
if (!constant && sections.some((section) => section.constant)) {
|
|
403
|
+
this.error("a list mixes CONSTANT and writable VAR_GLOBAL sections");
|
|
404
|
+
}
|
|
405
|
+
return {
|
|
406
|
+
name,
|
|
407
|
+
description,
|
|
408
|
+
source: this.source.name,
|
|
409
|
+
constant,
|
|
410
|
+
members: sections.flatMap((section) => section.members)
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
globalSection() {
|
|
396
414
|
this.expect("VAR_GLOBAL");
|
|
397
415
|
const written = new Set;
|
|
398
416
|
while (qualifiers.has(this.peek())) {
|
|
@@ -404,16 +422,7 @@ class Parser {
|
|
|
404
422
|
}
|
|
405
423
|
const members = this.members("END_VAR");
|
|
406
424
|
this.accept(";");
|
|
407
|
-
|
|
408
|
-
this.error("only one VAR_GLOBAL block per file is supported");
|
|
409
|
-
}
|
|
410
|
-
return {
|
|
411
|
-
name,
|
|
412
|
-
description,
|
|
413
|
-
source: this.source.name,
|
|
414
|
-
constant: written.has("CONSTANT"),
|
|
415
|
-
members
|
|
416
|
-
};
|
|
425
|
+
return { constant: written.has("CONSTANT"), members };
|
|
417
426
|
}
|
|
418
427
|
}
|
|
419
428
|
function parseDeclarations(source) {
|
|
@@ -577,7 +586,8 @@ function emit(declarations, globals, {
|
|
|
577
586
|
const visited = new Set;
|
|
578
587
|
function visitReference(type) {
|
|
579
588
|
if (type.kind === "array") {
|
|
580
|
-
|
|
589
|
+
visitReference(type.element);
|
|
590
|
+
return;
|
|
581
591
|
}
|
|
582
592
|
if (type.kind === "named" && !scalars[type.name.toUpperCase()]) {
|
|
583
593
|
visit(declaration(type.name));
|
|
@@ -592,7 +602,9 @@ function emit(declarations, globals, {
|
|
|
592
602
|
}
|
|
593
603
|
visiting.add(type.name);
|
|
594
604
|
if (type.kind === "struct") {
|
|
595
|
-
type.members.forEach((member) =>
|
|
605
|
+
type.members.forEach((member) => {
|
|
606
|
+
visitReference(member.type);
|
|
607
|
+
});
|
|
596
608
|
}
|
|
597
609
|
if (type.kind === "alias") {
|
|
598
610
|
visitReference(type.type);
|
|
@@ -722,9 +734,9 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
|
|
|
722
734
|
return output.join(`
|
|
723
735
|
`);
|
|
724
736
|
}
|
|
725
|
-
// packages/typegen/src/
|
|
726
|
-
import {
|
|
727
|
-
import {
|
|
737
|
+
// packages/typegen/src/device-tree.ts
|
|
738
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
739
|
+
import { iecName } from "@tsplc/config/build";
|
|
728
740
|
|
|
729
741
|
// packages/typegen/src/hardware/eds.ts
|
|
730
742
|
var cipTypes = {
|
|
@@ -1004,9 +1016,6 @@ function parseEds(text, file = "device.eds") {
|
|
|
1004
1016
|
};
|
|
1005
1017
|
}
|
|
1006
1018
|
|
|
1007
|
-
// packages/typegen/src/hardware/channels.ts
|
|
1008
|
-
import { ioScalarBits } from "@tsplc/iec";
|
|
1009
|
-
|
|
1010
1019
|
// packages/typegen/src/hardware/process-image.ts
|
|
1011
1020
|
import { ioArray, ioScalar, sizePrefix } from "@tsplc/iec";
|
|
1012
1021
|
function ioLayout(type) {
|
|
@@ -1065,7 +1074,180 @@ function regionPlacer(regions, { generatedTree }) {
|
|
|
1065
1074
|
};
|
|
1066
1075
|
}
|
|
1067
1076
|
|
|
1077
|
+
// packages/typegen/src/device-tree.ts
|
|
1078
|
+
var quoted = (value) => `"${value.replaceAll('"', '""')}"`;
|
|
1079
|
+
function normalizeEds(text, selection) {
|
|
1080
|
+
const sections = edsSections(text);
|
|
1081
|
+
const connections = [...sections.get("Connection Manager") ?? []].filter(([key]) => /^Connection\d+$/.test(key));
|
|
1082
|
+
const selected = connections.find(([key]) => key === selection.connection)?.[1];
|
|
1083
|
+
if (!selected) {
|
|
1084
|
+
throw new Error(`EDS has no ${selection.connection}.`);
|
|
1085
|
+
}
|
|
1086
|
+
const fields = [...selected.fields];
|
|
1087
|
+
const resized = new Map;
|
|
1088
|
+
for (const [sizeField, formatField, size] of [
|
|
1089
|
+
[3, 4, selection.outputSize],
|
|
1090
|
+
[6, 7, selection.inputSize]
|
|
1091
|
+
]) {
|
|
1092
|
+
const assembly = fields[formatField];
|
|
1093
|
+
if (!assembly) {
|
|
1094
|
+
continue;
|
|
1095
|
+
}
|
|
1096
|
+
if (size === undefined) {
|
|
1097
|
+
throw new Error(`Select a payload size for ${assembly}.`);
|
|
1098
|
+
}
|
|
1099
|
+
fields[sizeField] = String(size);
|
|
1100
|
+
resized.set(assembly, size);
|
|
1101
|
+
}
|
|
1102
|
+
const edits = connections.map(([, record]) => ({
|
|
1103
|
+
start: record.start,
|
|
1104
|
+
end: record.end,
|
|
1105
|
+
text: record === selected ? `Connection1 = ${fields.map((value, index) => index >= 12 ? quoted(value) : value).join(",")};` : ""
|
|
1106
|
+
}));
|
|
1107
|
+
for (const [key, record] of sections.get("Assembly") ?? []) {
|
|
1108
|
+
const size = resized.get(key);
|
|
1109
|
+
if (size === undefined) {
|
|
1110
|
+
continue;
|
|
1111
|
+
}
|
|
1112
|
+
const [name = "", path = "", , descriptor = ""] = record.fields;
|
|
1113
|
+
const rawBytes = [
|
|
1114
|
+
quoted(name),
|
|
1115
|
+
path && quoted(path),
|
|
1116
|
+
size,
|
|
1117
|
+
descriptor,
|
|
1118
|
+
"",
|
|
1119
|
+
"",
|
|
1120
|
+
size * 8,
|
|
1121
|
+
""
|
|
1122
|
+
];
|
|
1123
|
+
edits.push({
|
|
1124
|
+
start: record.start,
|
|
1125
|
+
end: record.end,
|
|
1126
|
+
text: `${key} = ${rawBytes.join(",")};`
|
|
1127
|
+
});
|
|
1128
|
+
resized.delete(key);
|
|
1129
|
+
}
|
|
1130
|
+
if (resized.size) {
|
|
1131
|
+
throw new Error(`EDS has no ${[...resized.keys()].join(", ")} assembly.`);
|
|
1132
|
+
}
|
|
1133
|
+
return edits.sort((a, b) => b.start - a.start).reduce((result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end), text);
|
|
1134
|
+
}
|
|
1135
|
+
async function deviceTree(config, catalog) {
|
|
1136
|
+
const settings = config.codesys?.deviceTree;
|
|
1137
|
+
if (!settings) {
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
const devices = await Promise.all(catalog.devices.map(async (device) => {
|
|
1141
|
+
if (!iecName.safeParse(device.id).success) {
|
|
1142
|
+
throw new Error(`${device.id}: a device tree adapter needs an IEC identifier name.`);
|
|
1143
|
+
}
|
|
1144
|
+
const connection = device.connection;
|
|
1145
|
+
if (!connection) {
|
|
1146
|
+
throw new Error(`${device.id}: select the connection to configure.`);
|
|
1147
|
+
}
|
|
1148
|
+
const region = (direction) => {
|
|
1149
|
+
const assembly = device.assemblies.find((item) => item.direction === direction);
|
|
1150
|
+
return assembly && { address: assembly.address, size: assembly.size };
|
|
1151
|
+
};
|
|
1152
|
+
const inputs = region("input");
|
|
1153
|
+
const outputs = region("output");
|
|
1154
|
+
const comments = Object.entries(config.io).flatMap(([key, binding]) => {
|
|
1155
|
+
if (!("device" in binding) || binding.device !== device.id) {
|
|
1156
|
+
return [];
|
|
1157
|
+
}
|
|
1158
|
+
const channel = device.channels.find((item) => item.id === binding.channel);
|
|
1159
|
+
if (channel.assembly === undefined) {
|
|
1160
|
+
return [];
|
|
1161
|
+
}
|
|
1162
|
+
if (channel.bits === 1) {
|
|
1163
|
+
return [{ address: channel.address, text: key }];
|
|
1164
|
+
}
|
|
1165
|
+
const area = channel.direction === "input" ? inputs : outputs;
|
|
1166
|
+
const bytes = channel.bits / 8;
|
|
1167
|
+
return [
|
|
1168
|
+
{
|
|
1169
|
+
address: `${area.address.slice(0, 3)}${byteOffset(area.address) + channel.offsetBits / 8}`,
|
|
1170
|
+
text: bytes > 1 ? `${key} (${bytes} bytes)` : key
|
|
1171
|
+
}
|
|
1172
|
+
];
|
|
1173
|
+
});
|
|
1174
|
+
const network = config.devices[device.id]?.network;
|
|
1175
|
+
if (device.modbus && !network?.address) {
|
|
1176
|
+
throw new Error(`${device.id}: Modbus registers need its network address.`);
|
|
1177
|
+
}
|
|
1178
|
+
return {
|
|
1179
|
+
name: device.id,
|
|
1180
|
+
eds: normalizeEds(await readFile2(device.descriptor, "utf8"), {
|
|
1181
|
+
connection: connection.id,
|
|
1182
|
+
inputSize: inputs?.size,
|
|
1183
|
+
outputSize: outputs?.size
|
|
1184
|
+
}),
|
|
1185
|
+
...network?.address && { address: network.address },
|
|
1186
|
+
...network?.rpi && {
|
|
1187
|
+
rpiMicroseconds: Number(BigInt(network.rpi.nanoseconds) / 1000n)
|
|
1188
|
+
},
|
|
1189
|
+
...inputs && { inputs },
|
|
1190
|
+
...outputs && { outputs },
|
|
1191
|
+
...device.modbus && { modbus: device.modbus },
|
|
1192
|
+
comments
|
|
1193
|
+
};
|
|
1194
|
+
}));
|
|
1195
|
+
const [first, ...rest] = devices;
|
|
1196
|
+
if (!first) {
|
|
1197
|
+
throw new Error("A generated device tree needs at least one device.");
|
|
1198
|
+
}
|
|
1199
|
+
return { ethernet: settings.ethernet ?? {}, devices: [first, ...rest] };
|
|
1200
|
+
}
|
|
1201
|
+
// packages/typegen/src/hardware/mapping-types.ts
|
|
1202
|
+
import { ioScalarBits } from "@tsplc/iec";
|
|
1203
|
+
var directBinding = (layout) => {
|
|
1204
|
+
const scalar = layout.replace(/^\d+x/, "");
|
|
1205
|
+
const integer = /^INT(\d+)$/.exec(scalar);
|
|
1206
|
+
const bits = integer ? Number(integer[1]) : ioScalarBits(scalar);
|
|
1207
|
+
const size = bits === undefined ? undefined : addressSize(bits);
|
|
1208
|
+
if (!size) {
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
return size === "X" ? '{ address: `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }' : `{ address: \`%\${"I" | "Q"}${size}\${number}\`; type?: string }`;
|
|
1212
|
+
};
|
|
1213
|
+
function generateHardwareTypes(catalog, targets, publication, ioTypes = true) {
|
|
1214
|
+
const selectors = publication?.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
|
|
1215
|
+
const publicationTypes = `// Generated by tsPLC. Run tsplc typegen after changing EDS files, device selections or PLC storage.
|
|
1216
|
+
export type PublicationSelector = ${selectors || "never"};
|
|
1217
|
+
export type PlcPublication = { readonly production: readonly PublicationSelector[]; readonly development: readonly PublicationSelector[] };
|
|
1218
|
+
`;
|
|
1219
|
+
if (!ioTypes) {
|
|
1220
|
+
return publicationTypes;
|
|
1221
|
+
}
|
|
1222
|
+
const channel = (device, id, options) => `{ device: ${JSON.stringify(device)}; channel: ${JSON.stringify(id)}${options} }`;
|
|
1223
|
+
const channels = catalog.devices.flatMap((device) => device.channels.filter((item) => item.address).map((item) => ({
|
|
1224
|
+
binding: channel(device.id, item.id, item.direction === "input" && item.type === "BOOL" ? "; inverted?: boolean; shared?: boolean" : ""),
|
|
1225
|
+
layout: ioLayout(item.type)
|
|
1226
|
+
})));
|
|
1227
|
+
const direct = '{ address: `%${"I" | "Q"}${"B" | "W" | "D"}${number}` | `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }';
|
|
1228
|
+
const anyBinding = [...channels.map((item) => item.binding), direct].join(`
|
|
1229
|
+
| `);
|
|
1230
|
+
const mapping = targets ? [...new Set(targets.map((target) => target.layout))].sort().map((layout) => {
|
|
1231
|
+
const keys = targets.filter((target) => target.layout === layout).map((target) => `\`${target.key}\``);
|
|
1232
|
+
const bindings = [
|
|
1233
|
+
...channels.filter((item) => item.layout === layout).map((item) => item.binding),
|
|
1234
|
+
directBinding(layout)
|
|
1235
|
+
].filter(Boolean);
|
|
1236
|
+
return `{
|
|
1237
|
+
readonly [K in ${keys.join(" | ")}]?: ${bindings.join(" | ") || "never"};
|
|
1238
|
+
}`;
|
|
1239
|
+
}).join(" & ") || "Readonly<Record<string, never>>" : "Readonly<Record<string, HardwareIoBinding>>";
|
|
1240
|
+
return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};
|
|
1241
|
+
export type HardwareIoMapping = ${mapping};
|
|
1242
|
+
export const hardware = ${JSON.stringify(catalog, null, 2)} as const;
|
|
1243
|
+
`;
|
|
1244
|
+
}
|
|
1245
|
+
// packages/typegen/src/hardware.ts
|
|
1246
|
+
import { readdir as readdir2, readFile as readFile3 } from "node:fs/promises";
|
|
1247
|
+
import { resolve } from "node:path";
|
|
1248
|
+
|
|
1068
1249
|
// packages/typegen/src/hardware/channels.ts
|
|
1250
|
+
import { ioScalarBits as ioScalarBits2 } from "@tsplc/iec";
|
|
1069
1251
|
function assemblyChannels({
|
|
1070
1252
|
device,
|
|
1071
1253
|
direction,
|
|
@@ -1128,7 +1310,7 @@ function assemblyChannels({
|
|
|
1128
1310
|
const count = counts.get(name) ?? 0;
|
|
1129
1311
|
counts.set(name, count + 1);
|
|
1130
1312
|
const key = `${prefix}.${name}${repeated.has(name) ? `[${count}]` : ""}`;
|
|
1131
|
-
const scalarBits =
|
|
1313
|
+
const scalarBits = ioScalarBits2(member.type);
|
|
1132
1314
|
const channel = {
|
|
1133
1315
|
device,
|
|
1134
1316
|
id: key,
|
|
@@ -1273,53 +1455,6 @@ function selectAssemblies(id, settings, descriptor, connection) {
|
|
|
1273
1455
|
|
|
1274
1456
|
// packages/typegen/src/hardware.ts
|
|
1275
1457
|
import { ioScalarBits as ioScalarBits3 } from "@tsplc/iec";
|
|
1276
|
-
|
|
1277
|
-
// packages/typegen/src/hardware/mapping-types.ts
|
|
1278
|
-
import { ioScalarBits as ioScalarBits2 } from "@tsplc/iec";
|
|
1279
|
-
var directBinding = (layout) => {
|
|
1280
|
-
const scalar = layout.replace(/^\d+x/, "");
|
|
1281
|
-
const integer = /^INT(\d+)$/.exec(scalar);
|
|
1282
|
-
const bits = integer ? Number(integer[1]) : ioScalarBits2(scalar);
|
|
1283
|
-
const size = bits === undefined ? undefined : addressSize(bits);
|
|
1284
|
-
if (!size) {
|
|
1285
|
-
return;
|
|
1286
|
-
}
|
|
1287
|
-
return size === "X" ? '{ address: `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }' : `{ address: \`%\${"I" | "Q"}${size}\${number}\`; type?: string }`;
|
|
1288
|
-
};
|
|
1289
|
-
function generateHardwareTypes(catalog, targets, publication, ioTypes = true) {
|
|
1290
|
-
const selectors = publication?.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
|
|
1291
|
-
const publicationTypes = `// Generated by tsPLC. Run tsplc typegen after changing EDS files, device selections or PLC storage.
|
|
1292
|
-
export type PublicationSelector = ${selectors || "never"};
|
|
1293
|
-
export type PlcPublication = { readonly production: readonly PublicationSelector[]; readonly development: readonly PublicationSelector[] };
|
|
1294
|
-
`;
|
|
1295
|
-
if (!ioTypes) {
|
|
1296
|
-
return publicationTypes;
|
|
1297
|
-
}
|
|
1298
|
-
const channel = (device, id, options) => `{ device: ${JSON.stringify(device)}; channel: ${JSON.stringify(id)}${options} }`;
|
|
1299
|
-
const channels = catalog.devices.flatMap((device) => device.channels.filter((item) => item.address).map((item) => ({
|
|
1300
|
-
binding: channel(device.id, item.id, item.direction === "input" && item.type === "BOOL" ? "; inverted?: boolean; shared?: boolean" : ""),
|
|
1301
|
-
layout: ioLayout(item.type)
|
|
1302
|
-
})));
|
|
1303
|
-
const direct = '{ address: `%${"I" | "Q"}${"B" | "W" | "D"}${number}` | `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }';
|
|
1304
|
-
const anyBinding = [...channels.map((item) => item.binding), direct].join(`
|
|
1305
|
-
| `);
|
|
1306
|
-
const mapping = targets ? [...new Set(targets.map((target) => target.layout))].sort().map((layout) => {
|
|
1307
|
-
const keys = targets.filter((target) => target.layout === layout).map((target) => `\`${target.key}\``);
|
|
1308
|
-
const bindings = [
|
|
1309
|
-
...channels.filter((item) => item.layout === layout).map((item) => item.binding),
|
|
1310
|
-
directBinding(layout)
|
|
1311
|
-
].filter(Boolean);
|
|
1312
|
-
return `{
|
|
1313
|
-
readonly [K in ${keys.join(" | ")}]?: ${bindings.join(" | ") || "never"};
|
|
1314
|
-
}`;
|
|
1315
|
-
}).join(" & ") || "Readonly<Record<string, never>>" : "Readonly<Record<string, HardwareIoBinding>>";
|
|
1316
|
-
return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};
|
|
1317
|
-
export type HardwareIoMapping = ${mapping};
|
|
1318
|
-
export const hardware = ${JSON.stringify(catalog, null, 2)} as const;
|
|
1319
|
-
`;
|
|
1320
|
-
}
|
|
1321
|
-
|
|
1322
|
-
// packages/typegen/src/hardware.ts
|
|
1323
1458
|
async function edsFiles(directory) {
|
|
1324
1459
|
const entries = await readdir2(directory, { withFileTypes: true }).catch((cause) => {
|
|
1325
1460
|
if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") {
|
|
@@ -1348,7 +1483,7 @@ async function readDescriptors(config, root) {
|
|
|
1348
1483
|
for (const device of Object.values(config.devices)) {
|
|
1349
1484
|
files.add(resolve(root, device.file));
|
|
1350
1485
|
}
|
|
1351
|
-
return Promise.all([...files].map(async (file) => parseEds(await
|
|
1486
|
+
return Promise.all([...files].map(async (file) => parseEds(await readFile3(file, "utf8"), file)));
|
|
1352
1487
|
}
|
|
1353
1488
|
async function loadHardware(config, root) {
|
|
1354
1489
|
const descriptors = await readDescriptors(config, root);
|
|
@@ -1427,149 +1562,43 @@ function resolveIo(config, catalog) {
|
|
|
1427
1562
|
];
|
|
1428
1563
|
}));
|
|
1429
1564
|
}
|
|
1430
|
-
|
|
1431
|
-
// packages/typegen/src/index.ts
|
|
1432
|
-
import { ioScalarBits as ioScalarBits4 } from "@tsplc/iec";
|
|
1433
|
-
|
|
1434
|
-
// packages/typegen/src/device-tree.ts
|
|
1435
|
-
import { readFile as readFile3 } from "node:fs/promises";
|
|
1436
|
-
import { iecName } from "@tsplc/config/build";
|
|
1437
|
-
var quoted = (value) => `"${value.replaceAll('"', '""')}"`;
|
|
1438
|
-
function normalizeEds(text, selection) {
|
|
1439
|
-
const sections = edsSections(text);
|
|
1440
|
-
const connections = [...sections.get("Connection Manager") ?? []].filter(([key]) => /^Connection\d+$/.test(key));
|
|
1441
|
-
const selected = connections.find(([key]) => key === selection.connection)?.[1];
|
|
1442
|
-
if (!selected) {
|
|
1443
|
-
throw new Error(`EDS has no ${selection.connection}.`);
|
|
1444
|
-
}
|
|
1445
|
-
const fields = [...selected.fields];
|
|
1446
|
-
const resized = new Map;
|
|
1447
|
-
for (const [sizeField, formatField, size] of [
|
|
1448
|
-
[3, 4, selection.outputSize],
|
|
1449
|
-
[6, 7, selection.inputSize]
|
|
1450
|
-
]) {
|
|
1451
|
-
const assembly = fields[formatField];
|
|
1452
|
-
if (!assembly) {
|
|
1453
|
-
continue;
|
|
1454
|
-
}
|
|
1455
|
-
if (size === undefined) {
|
|
1456
|
-
throw new Error(`Select a payload size for ${assembly}.`);
|
|
1457
|
-
}
|
|
1458
|
-
fields[sizeField] = String(size);
|
|
1459
|
-
resized.set(assembly, size);
|
|
1460
|
-
}
|
|
1461
|
-
const edits = connections.map(([, record]) => ({
|
|
1462
|
-
start: record.start,
|
|
1463
|
-
end: record.end,
|
|
1464
|
-
text: record === selected ? `Connection1 = ${fields.map((value, index) => index >= 12 ? quoted(value) : value).join(",")};` : ""
|
|
1465
|
-
}));
|
|
1466
|
-
for (const [key, record] of sections.get("Assembly") ?? []) {
|
|
1467
|
-
const size = resized.get(key);
|
|
1468
|
-
if (size === undefined) {
|
|
1469
|
-
continue;
|
|
1470
|
-
}
|
|
1471
|
-
const [name = "", path = "", , descriptor = ""] = record.fields;
|
|
1472
|
-
const rawBytes = [
|
|
1473
|
-
quoted(name),
|
|
1474
|
-
path && quoted(path),
|
|
1475
|
-
size,
|
|
1476
|
-
descriptor,
|
|
1477
|
-
"",
|
|
1478
|
-
"",
|
|
1479
|
-
size * 8,
|
|
1480
|
-
""
|
|
1481
|
-
];
|
|
1482
|
-
edits.push({
|
|
1483
|
-
start: record.start,
|
|
1484
|
-
end: record.end,
|
|
1485
|
-
text: `${key} = ${rawBytes.join(",")};`
|
|
1486
|
-
});
|
|
1487
|
-
resized.delete(key);
|
|
1488
|
-
}
|
|
1489
|
-
if (resized.size) {
|
|
1490
|
-
throw new Error(`EDS has no ${[...resized.keys()].join(", ")} assembly.`);
|
|
1491
|
-
}
|
|
1492
|
-
return edits.sort((a, b) => b.start - a.start).reduce((result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end), text);
|
|
1493
|
-
}
|
|
1494
|
-
async function deviceTree(config, catalog) {
|
|
1495
|
-
const settings = config.codesys?.deviceTree;
|
|
1496
|
-
if (!settings) {
|
|
1497
|
-
return;
|
|
1498
|
-
}
|
|
1499
|
-
const devices = await Promise.all(catalog.devices.map(async (device) => {
|
|
1500
|
-
if (!iecName.safeParse(device.id).success) {
|
|
1501
|
-
throw new Error(`${device.id}: a device tree adapter needs an IEC identifier name.`);
|
|
1502
|
-
}
|
|
1503
|
-
const connection = device.connection;
|
|
1504
|
-
if (!connection) {
|
|
1505
|
-
throw new Error(`${device.id}: select the connection to configure.`);
|
|
1506
|
-
}
|
|
1507
|
-
const region = (direction) => {
|
|
1508
|
-
const assembly = device.assemblies.find((item) => item.direction === direction);
|
|
1509
|
-
return assembly && { address: assembly.address, size: assembly.size };
|
|
1510
|
-
};
|
|
1511
|
-
const inputs = region("input");
|
|
1512
|
-
const outputs = region("output");
|
|
1513
|
-
const comments = Object.entries(config.io).flatMap(([key, binding]) => {
|
|
1514
|
-
if (!("device" in binding) || binding.device !== device.id) {
|
|
1515
|
-
return [];
|
|
1516
|
-
}
|
|
1517
|
-
const channel = device.channels.find((item) => item.id === binding.channel);
|
|
1518
|
-
if (channel.assembly === undefined) {
|
|
1519
|
-
return [];
|
|
1520
|
-
}
|
|
1521
|
-
if (channel.bits === 1) {
|
|
1522
|
-
return [{ address: channel.address, text: key }];
|
|
1523
|
-
}
|
|
1524
|
-
const area = channel.direction === "input" ? inputs : outputs;
|
|
1525
|
-
const bytes = channel.bits / 8;
|
|
1526
|
-
return [
|
|
1527
|
-
{
|
|
1528
|
-
address: `${area.address.slice(0, 3)}${byteOffset(area.address) + channel.offsetBits / 8}`,
|
|
1529
|
-
text: bytes > 1 ? `${key} (${bytes} bytes)` : key
|
|
1530
|
-
}
|
|
1531
|
-
];
|
|
1532
|
-
});
|
|
1533
|
-
const network = config.devices[device.id]?.network;
|
|
1534
|
-
if (device.modbus && !network?.address) {
|
|
1535
|
-
throw new Error(`${device.id}: Modbus registers need its network address.`);
|
|
1536
|
-
}
|
|
1537
|
-
return {
|
|
1538
|
-
name: device.id,
|
|
1539
|
-
eds: normalizeEds(await readFile3(device.descriptor, "utf8"), {
|
|
1540
|
-
connection: connection.id,
|
|
1541
|
-
inputSize: inputs?.size,
|
|
1542
|
-
outputSize: outputs?.size
|
|
1543
|
-
}),
|
|
1544
|
-
...network?.address && { address: network.address },
|
|
1545
|
-
...network?.rpi && {
|
|
1546
|
-
rpiMicroseconds: Number(BigInt(network.rpi.nanoseconds) / 1000n)
|
|
1547
|
-
},
|
|
1548
|
-
...inputs && { inputs },
|
|
1549
|
-
...outputs && { outputs },
|
|
1550
|
-
...device.modbus && { modbus: device.modbus },
|
|
1551
|
-
comments
|
|
1552
|
-
};
|
|
1553
|
-
}));
|
|
1554
|
-
const [first, ...rest] = devices;
|
|
1555
|
-
if (!first) {
|
|
1556
|
-
throw new Error("A generated device tree needs at least one device.");
|
|
1557
|
-
}
|
|
1558
|
-
return { ethernet: settings.ethernet ?? {}, devices: [first, ...rest] };
|
|
1559
|
-
}
|
|
1560
1565
|
// packages/typegen/src/project.ts
|
|
1561
1566
|
import { mkdir, readFile as readFile4, rename, writeFile } from "node:fs/promises";
|
|
1562
1567
|
import { dirname, resolve as resolve2 } from "node:path";
|
|
1563
|
-
import { format } from "prettier";
|
|
1564
1568
|
import {
|
|
1569
|
+
ioSymbolsSchema,
|
|
1565
1570
|
loadTsplcConfig,
|
|
1566
1571
|
publicationSchema,
|
|
1567
1572
|
typegenSchema
|
|
1568
1573
|
} from "@tsplc/config";
|
|
1574
|
+
import {
|
|
1575
|
+
emittedFiles,
|
|
1576
|
+
emittedStDirectory,
|
|
1577
|
+
projectSnapshotFile
|
|
1578
|
+
} from "@tsplc/config/project-files";
|
|
1569
1579
|
import { blockCommentEnd as blockCommentEnd2, lineCommentEnd as lineCommentEnd2 } from "@tsplc/iec/st";
|
|
1570
|
-
|
|
1580
|
+
import { format } from "prettier";
|
|
1571
1581
|
var formatTypeScript = (source) => format(source, { parser: "typescript" });
|
|
1572
|
-
var readPublication = async (root) => publicationSchema.parse(JSON.parse(await readFile4(resolve2(root,
|
|
1582
|
+
var readPublication = async (root) => publicationSchema.parse(JSON.parse(await readFile4(resolve2(root, emittedStDirectory, emittedFiles.publication), "utf8")));
|
|
1583
|
+
var generatedFiles = {
|
|
1584
|
+
hardware: "hardware.ts",
|
|
1585
|
+
contract: "plc.ts",
|
|
1586
|
+
machines: "machines.ts"
|
|
1587
|
+
};
|
|
1588
|
+
async function readIoSymbols(root) {
|
|
1589
|
+
const file = resolve2(root, emittedStDirectory, emittedFiles.ioSymbols);
|
|
1590
|
+
const text = await readFile4(file, "utf8").catch((error) => {
|
|
1591
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
1592
|
+
return "{}";
|
|
1593
|
+
}
|
|
1594
|
+
throw error;
|
|
1595
|
+
});
|
|
1596
|
+
const symbols = ioSymbolsSchema.safeParse(JSON.parse(text));
|
|
1597
|
+
if (!symbols.success) {
|
|
1598
|
+
throw new Error(`Invalid IO symbols in ${file}`, { cause: symbols.error });
|
|
1599
|
+
}
|
|
1600
|
+
return symbols.data;
|
|
1601
|
+
}
|
|
1573
1602
|
async function contractSources(config, root, settings) {
|
|
1574
1603
|
const directories = (setting) => setting ? [setting].flat().map((path) => resolve2(root, path)) : [];
|
|
1575
1604
|
const types = directories(settings.types);
|
|
@@ -1585,7 +1614,7 @@ async function contractSources(config, root, settings) {
|
|
|
1585
1614
|
}
|
|
1586
1615
|
return sources;
|
|
1587
1616
|
}
|
|
1588
|
-
const source = config.compiler ?
|
|
1617
|
+
const source = config.compiler ? emittedStDirectory : config.build?.sourceDir;
|
|
1589
1618
|
if (!source) {
|
|
1590
1619
|
if (config.typegen) {
|
|
1591
1620
|
throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
|
|
@@ -1666,16 +1695,16 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
|
|
|
1666
1695
|
version: 1,
|
|
1667
1696
|
configFile,
|
|
1668
1697
|
config,
|
|
1669
|
-
symbols: config.compiler ?
|
|
1698
|
+
symbols: config.compiler ? await readIoSymbols(root) : Object.fromEntries(Object.keys(io).filter((symbol) => symbol.includes(".")).map((symbol) => [symbol, symbol]))
|
|
1670
1699
|
};
|
|
1671
1700
|
const outputs = [
|
|
1672
1701
|
{
|
|
1673
|
-
path: resolve2(root, settings.dir,
|
|
1702
|
+
path: resolve2(root, settings.dir, generatedFiles.hardware),
|
|
1674
1703
|
content: await formatTypeScript(generateHardwareTypes(catalog, options.targets?.io, options.targets?.publication, settings.ioTypes))
|
|
1675
1704
|
},
|
|
1676
1705
|
{
|
|
1677
|
-
path: resolve2(root,
|
|
1678
|
-
content: JSON.stringify(project, null, 2)
|
|
1706
|
+
path: resolve2(root, projectSnapshotFile),
|
|
1707
|
+
content: `${JSON.stringify(project, null, 2)}
|
|
1679
1708
|
`
|
|
1680
1709
|
}
|
|
1681
1710
|
];
|
|
@@ -1683,7 +1712,7 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
|
|
|
1683
1712
|
if (sources) {
|
|
1684
1713
|
const inferred = !!config.compiler && !sources.explicit;
|
|
1685
1714
|
outputs.push({
|
|
1686
|
-
path: resolve2(root, settings.dir,
|
|
1715
|
+
path: resolve2(root, settings.dir, generatedFiles.contract),
|
|
1687
1716
|
content: await formatTypeScript(await generateTypes({
|
|
1688
1717
|
types: sources.types,
|
|
1689
1718
|
globals: sources.globals,
|
|
@@ -1697,12 +1726,12 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
|
|
|
1697
1726
|
checkHmiTargets(config.hmi.controls, (await readPublication(root)).production);
|
|
1698
1727
|
}
|
|
1699
1728
|
if (config.compiler && !options.hardwareOnly) {
|
|
1700
|
-
const machine = await readFile4(resolve2(root,
|
|
1729
|
+
const machine = await readFile4(resolve2(root, emittedStDirectory, emittedFiles.machines), "utf8").catch(() => {
|
|
1701
1730
|
return;
|
|
1702
1731
|
});
|
|
1703
1732
|
if (machine) {
|
|
1704
1733
|
outputs.push({
|
|
1705
|
-
path: resolve2(root, settings.dir,
|
|
1734
|
+
path: resolve2(root, settings.dir, generatedFiles.machines),
|
|
1706
1735
|
content: await formatTypeScript(machine)
|
|
1707
1736
|
});
|
|
1708
1737
|
}
|
|
@@ -1715,6 +1744,7 @@ export {
|
|
|
1715
1744
|
generateHardwareTypes,
|
|
1716
1745
|
generateProject,
|
|
1717
1746
|
generateTypes,
|
|
1747
|
+
generatedFiles,
|
|
1718
1748
|
ioLayout,
|
|
1719
1749
|
ioScalarBits4 as ioScalarBits,
|
|
1720
1750
|
loadHardware,
|
|
@@ -1724,5 +1754,5 @@ export {
|
|
|
1724
1754
|
resolveIo
|
|
1725
1755
|
};
|
|
1726
1756
|
|
|
1727
|
-
//# debugId=
|
|
1757
|
+
//# debugId=A7223794E72BA3C664756E2164756E21
|
|
1728
1758
|
//# sourceMappingURL=index.js.map
|