@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/src/codegen/parser.ts
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { basename } from "node:path";
|
|
3
|
+
import { defaultStringLength } from "@tsplc/iec";
|
|
1
4
|
import {
|
|
2
5
|
blockCommentEnd,
|
|
3
6
|
directAddressEnd,
|
|
7
|
+
identifierPart,
|
|
4
8
|
identifierPattern,
|
|
9
|
+
identifierStart,
|
|
5
10
|
lineCommentEnd,
|
|
6
11
|
qualifiers,
|
|
12
|
+
stringEnd,
|
|
7
13
|
} from "@tsplc/iec/st";
|
|
8
14
|
|
|
9
15
|
export interface Source {
|
|
@@ -64,76 +70,104 @@ export interface GlobalList {
|
|
|
64
70
|
interface Token {
|
|
65
71
|
text: string;
|
|
66
72
|
offset: number;
|
|
73
|
+
end: number;
|
|
67
74
|
kind: "code" | "comment" | "attribute";
|
|
68
75
|
}
|
|
69
76
|
|
|
77
|
+
/** Offset just past a `{…}` pragma whose body starts at `offset`, or `null` when it never closes. */
|
|
78
|
+
const pragmaEnd = (text: string, offset: number): number | null => {
|
|
79
|
+
const next = text.slice(offset).search(/[}'"]/);
|
|
80
|
+
if (next < 0) {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
const at = offset + next;
|
|
84
|
+
if (text[at] === "}") {
|
|
85
|
+
return at + 1;
|
|
86
|
+
}
|
|
87
|
+
const end = stringEnd(text, at);
|
|
88
|
+
return end === null ? null : pragmaEnd(text, end);
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const codeToken = new RegExp(
|
|
92
|
+
String.raw`^(?:\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|${identifierStart}${identifierPart}*|:=|\.\.|[[\]():;,.+\-*/#])`,
|
|
93
|
+
"i",
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
/** The token at or after `start`, past whitespace, or undefined at the end of the text. */
|
|
97
|
+
function tokenAt(source: Source, start: number): Token | undefined {
|
|
98
|
+
const { text } = source;
|
|
99
|
+
const offset = start + text.slice(start).search(/\S|$/);
|
|
100
|
+
if (offset === text.length) {
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
const rest = text.slice(offset);
|
|
104
|
+
if (rest.startsWith("(*")) {
|
|
105
|
+
const end = blockCommentEnd(text, offset);
|
|
106
|
+
if (end === null) {
|
|
107
|
+
throw new Error(`${source.name}: unterminated comment`);
|
|
108
|
+
}
|
|
109
|
+
const comment = text.slice(offset + 2, end - 2).trim();
|
|
110
|
+
return { text: comment, offset, end, kind: "comment" };
|
|
111
|
+
}
|
|
112
|
+
if (rest.startsWith("//")) {
|
|
113
|
+
const end = lineCommentEnd(text, offset);
|
|
114
|
+
const comment = text.slice(offset + 2, end).trim();
|
|
115
|
+
return { text: comment, offset, end, kind: "comment" };
|
|
116
|
+
}
|
|
117
|
+
const code = (kind: "code" | "attribute", end: number): Token => ({
|
|
118
|
+
text: text.slice(offset, end),
|
|
119
|
+
offset,
|
|
120
|
+
end,
|
|
121
|
+
kind,
|
|
122
|
+
});
|
|
123
|
+
const attributeEnd = rest.startsWith("{")
|
|
124
|
+
? pragmaEnd(text, offset + 1)
|
|
125
|
+
: null;
|
|
126
|
+
if (attributeEnd !== null) {
|
|
127
|
+
return code("attribute", attributeEnd);
|
|
128
|
+
}
|
|
129
|
+
const addressEnd = directAddressEnd(text, offset);
|
|
130
|
+
if (addressEnd !== null) {
|
|
131
|
+
return code("code", addressEnd);
|
|
132
|
+
}
|
|
133
|
+
const literalEnd =
|
|
134
|
+
rest.startsWith("'") || rest.startsWith('"')
|
|
135
|
+
? stringEnd(text, offset)
|
|
136
|
+
: null;
|
|
137
|
+
if (literalEnd !== null) {
|
|
138
|
+
return code("code", literalEnd);
|
|
139
|
+
}
|
|
140
|
+
const word = codeToken.exec(rest);
|
|
141
|
+
if (!word) {
|
|
142
|
+
throw new Error(
|
|
143
|
+
`${source.name}:${text.slice(0, offset).split("\n").length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`,
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
return code("code", offset + word[0].length);
|
|
147
|
+
}
|
|
148
|
+
|
|
70
149
|
function tokenize(source: Source): Token[] {
|
|
71
150
|
const tokens: Token[] = [];
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
continue;
|
|
79
|
-
}
|
|
80
|
-
if (rest.startsWith("(*")) {
|
|
81
|
-
const end = blockCommentEnd(source.text, offset);
|
|
82
|
-
if (end === null) {
|
|
83
|
-
throw new Error(`${source.name}: unterminated comment`);
|
|
84
|
-
}
|
|
85
|
-
tokens.push({
|
|
86
|
-
text: source.text.slice(offset + 2, end - 2).trim(),
|
|
87
|
-
offset,
|
|
88
|
-
kind: "comment",
|
|
89
|
-
});
|
|
90
|
-
offset = end;
|
|
91
|
-
continue;
|
|
92
|
-
}
|
|
93
|
-
if (rest.startsWith("//")) {
|
|
94
|
-
const end = lineCommentEnd(source.text, offset);
|
|
95
|
-
tokens.push({
|
|
96
|
-
text: source.text.slice(offset + 2, end).trim(),
|
|
97
|
-
offset,
|
|
98
|
-
kind: "comment",
|
|
99
|
-
});
|
|
100
|
-
offset = end;
|
|
101
|
-
continue;
|
|
102
|
-
}
|
|
103
|
-
const attribute =
|
|
104
|
-
/^\{(?:[^}'"]|'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*")*\}/.exec(
|
|
105
|
-
rest,
|
|
106
|
-
);
|
|
107
|
-
if (attribute) {
|
|
108
|
-
tokens.push({ text: attribute[0], offset, kind: "attribute" });
|
|
109
|
-
offset += attribute[0].length;
|
|
110
|
-
continue;
|
|
111
|
-
}
|
|
112
|
-
const addressEnd = directAddressEnd(source.text, offset);
|
|
113
|
-
if (addressEnd !== null) {
|
|
114
|
-
tokens.push({
|
|
115
|
-
text: source.text.slice(offset, addressEnd),
|
|
116
|
-
offset,
|
|
117
|
-
kind: "code",
|
|
118
|
-
});
|
|
119
|
-
offset = addressEnd;
|
|
120
|
-
continue;
|
|
121
|
-
}
|
|
122
|
-
const code =
|
|
123
|
-
/^(?:'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*"|\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|:=|\.\.|[[\]():;,.+\-*/#])/i.exec(
|
|
124
|
-
rest,
|
|
125
|
-
);
|
|
126
|
-
if (!code) {
|
|
127
|
-
throw new Error(
|
|
128
|
-
`${source.name}:${source.text.slice(0, offset).split("\n").length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`,
|
|
129
|
-
);
|
|
130
|
-
}
|
|
131
|
-
tokens.push({ text: code[0], offset, kind: "code" });
|
|
132
|
-
offset += code[0].length;
|
|
151
|
+
for (
|
|
152
|
+
let token = tokenAt(source, 0);
|
|
153
|
+
token;
|
|
154
|
+
token = tokenAt(source, token.end)
|
|
155
|
+
) {
|
|
156
|
+
tokens.push(token);
|
|
133
157
|
}
|
|
134
158
|
return tokens;
|
|
135
159
|
}
|
|
136
160
|
|
|
161
|
+
const codeTokenAt = (source: Source, offset: number): Token | undefined => {
|
|
162
|
+
const token = tokenAt(source, offset);
|
|
163
|
+
return token && token.kind !== "code"
|
|
164
|
+
? codeTokenAt(source, token.end)
|
|
165
|
+
: token;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
/** The first code token of a source, past comments and pragmas. */
|
|
169
|
+
export const firstCodeToken = (source: Source) => codeTokenAt(source, 0)?.text;
|
|
170
|
+
|
|
137
171
|
class Parser {
|
|
138
172
|
private position = 0;
|
|
139
173
|
private readonly tokens: Token[];
|
|
@@ -247,7 +281,11 @@ class Parser {
|
|
|
247
281
|
if (upper === "STRING" || upper === "WSTRING") {
|
|
248
282
|
const opening = this.peek();
|
|
249
283
|
if (opening !== "(" && opening !== "[") {
|
|
250
|
-
return {
|
|
284
|
+
return {
|
|
285
|
+
kind: "string",
|
|
286
|
+
name: upper,
|
|
287
|
+
length: String(defaultStringLength),
|
|
288
|
+
};
|
|
251
289
|
}
|
|
252
290
|
this.take();
|
|
253
291
|
const closing = opening === "(" ? ")" : "]";
|
|
@@ -417,10 +455,30 @@ const symbolAccess = (attribute: string): SymbolAccess[] => {
|
|
|
417
455
|
: [];
|
|
418
456
|
};
|
|
419
457
|
|
|
420
|
-
|
|
458
|
+
function parseDeclarations(source: Source): Declaration[] {
|
|
421
459
|
return new Parser(source).declarations();
|
|
422
460
|
}
|
|
423
461
|
|
|
424
462
|
export function parseGlobals(source: Source, name: string): GlobalList {
|
|
425
463
|
return new Parser(source).globals(name);
|
|
426
464
|
}
|
|
465
|
+
|
|
466
|
+
const readSource = async (name: string): Promise<Source> => ({
|
|
467
|
+
name,
|
|
468
|
+
text: await readFile(name, "utf8"),
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
/** The TYPE declarations of `types` and the global lists of `globals`, each list named after its file. */
|
|
472
|
+
export async function parseSources(files: {
|
|
473
|
+
types: readonly string[];
|
|
474
|
+
globals: readonly string[];
|
|
475
|
+
}): Promise<{ types: Declaration[]; globals: GlobalList[] }> {
|
|
476
|
+
return {
|
|
477
|
+
types: (await Promise.all(files.types.map(readSource))).flatMap(
|
|
478
|
+
parseDeclarations,
|
|
479
|
+
),
|
|
480
|
+
globals: (await Promise.all(files.globals.map(readSource))).map((source) =>
|
|
481
|
+
parseGlobals(source, basename(source.name).replace(/\.st$/i, "")),
|
|
482
|
+
),
|
|
483
|
+
};
|
|
484
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { elementaryType } from "@tsplc/iec";
|
|
2
|
+
import { constantResolver, integerExpression } from "./constants";
|
|
3
|
+
import type { Declaration, GlobalList, TypeReference } from "./parser";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* What parsed TYPE declarations mean once their names are looked up: the declaration a
|
|
7
|
+
* name refers to, the type an alias stands for, array bounds and enum member values, with
|
|
8
|
+
* integers evaluated against the CONSTANT global lists.
|
|
9
|
+
*/
|
|
10
|
+
export function resolveDeclarations({
|
|
11
|
+
types,
|
|
12
|
+
globals,
|
|
13
|
+
}: {
|
|
14
|
+
types: readonly Declaration[];
|
|
15
|
+
globals: readonly GlobalList[];
|
|
16
|
+
}) {
|
|
17
|
+
const declarations = new Map(
|
|
18
|
+
types.map((declaration) => [declaration.name.toUpperCase(), declaration]),
|
|
19
|
+
);
|
|
20
|
+
const constant = constantResolver(globals.filter((list) => list.constant));
|
|
21
|
+
const integer = (expression: string) =>
|
|
22
|
+
integerExpression(expression, (name) => constant(name, null));
|
|
23
|
+
const declaration = (name: string): Declaration => {
|
|
24
|
+
const found = declarations.get(name.toUpperCase());
|
|
25
|
+
if (!found) {
|
|
26
|
+
throw new Error(`unknown IEC type ${name}`);
|
|
27
|
+
}
|
|
28
|
+
return found;
|
|
29
|
+
};
|
|
30
|
+
const aliasTarget = (reference: TypeReference): TypeReference => {
|
|
31
|
+
if (
|
|
32
|
+
reference.kind !== "named" ||
|
|
33
|
+
elementaryType(reference.name.toUpperCase())
|
|
34
|
+
) {
|
|
35
|
+
return reference;
|
|
36
|
+
}
|
|
37
|
+
const named = declaration(reference.name);
|
|
38
|
+
return named.kind === "alias" ? aliasTarget(named.type) : reference;
|
|
39
|
+
};
|
|
40
|
+
const bounds = (array: Extract<TypeReference, { kind: "array" }>) =>
|
|
41
|
+
array.dimensions.map(({ lower, upper }) => {
|
|
42
|
+
const start = integer(lower);
|
|
43
|
+
const end = integer(upper);
|
|
44
|
+
if (end < start || !Number.isSafeInteger(end - start + 1)) {
|
|
45
|
+
throw new Error(`invalid array bounds ${lower}..${upper}`);
|
|
46
|
+
}
|
|
47
|
+
return { start, end };
|
|
48
|
+
});
|
|
49
|
+
/** A member without a value follows the one before it; a value may name an earlier member. */
|
|
50
|
+
const enumMembers = (enumeration: Extract<Declaration, { kind: "enum" }>) => {
|
|
51
|
+
const members: { name: string; value: number }[] = [];
|
|
52
|
+
for (const member of enumeration.members) {
|
|
53
|
+
const value =
|
|
54
|
+
member.value === undefined
|
|
55
|
+
? (members.at(-1)?.value ?? -1) + 1
|
|
56
|
+
: integerExpression(
|
|
57
|
+
member.value,
|
|
58
|
+
(name) =>
|
|
59
|
+
members.find(
|
|
60
|
+
(item) => item.name.toUpperCase() === name.toUpperCase(),
|
|
61
|
+
)?.value ?? constant(name, null),
|
|
62
|
+
);
|
|
63
|
+
members.push({ name: member.name, value });
|
|
64
|
+
}
|
|
65
|
+
return members;
|
|
66
|
+
};
|
|
67
|
+
return { constant, integer, declaration, aliasTarget, bounds, enumMembers };
|
|
68
|
+
}
|
package/src/device-tree.ts
CHANGED
|
@@ -1,92 +1,9 @@
|
|
|
1
|
-
// biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
|
|
2
1
|
import { readFile } from "node:fs/promises";
|
|
3
2
|
import type { DeviceTree, ResolvedTsplcConfig } from "@tsplc/config";
|
|
4
3
|
import { iecName } from "@tsplc/config/build";
|
|
5
|
-
import type
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
const quoted = (value: string) => `"${value.replaceAll('"', '""')}"`;
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Reduce an EDS to the selected connection with raw byte assemblies of the selected
|
|
13
|
-
* payload sizes. CODESYS's EDS import then creates one BYTE channel per payload
|
|
14
|
-
* byte, so each channel sits at its assembly offset. Member layouts would instead
|
|
15
|
-
* become typed channels that CODESYS packs independently, and it maps only the
|
|
16
|
-
* first byte of a multi-byte member such as a reader's result data.
|
|
17
|
-
*/
|
|
18
|
-
export function normalizeEds(
|
|
19
|
-
text: string,
|
|
20
|
-
selection: { connection: string; inputSize?: number; outputSize?: number },
|
|
21
|
-
): string {
|
|
22
|
-
const sections = edsSections(text);
|
|
23
|
-
const connections = [...(sections.get("Connection Manager") ?? [])].filter(
|
|
24
|
-
([key]) => /^Connection\d+$/.test(key),
|
|
25
|
-
);
|
|
26
|
-
const selected = connections.find(
|
|
27
|
-
([key]) => key === selection.connection,
|
|
28
|
-
)?.[1];
|
|
29
|
-
if (!selected) {
|
|
30
|
-
throw new Error(`EDS has no ${selection.connection}.`);
|
|
31
|
-
}
|
|
32
|
-
const fields = [...selected.fields];
|
|
33
|
-
const resized = new Map<string, number>();
|
|
34
|
-
for (const [sizeField, formatField, size] of [
|
|
35
|
-
[3, 4, selection.outputSize],
|
|
36
|
-
[6, 7, selection.inputSize],
|
|
37
|
-
] as const) {
|
|
38
|
-
const assembly = fields[formatField];
|
|
39
|
-
if (!assembly) {
|
|
40
|
-
continue;
|
|
41
|
-
}
|
|
42
|
-
if (size === undefined) {
|
|
43
|
-
throw new Error(`Select a payload size for ${assembly}.`);
|
|
44
|
-
}
|
|
45
|
-
fields[sizeField] = String(size);
|
|
46
|
-
resized.set(assembly, size);
|
|
47
|
-
}
|
|
48
|
-
const edits = connections.map(([, record]) => ({
|
|
49
|
-
start: record.start,
|
|
50
|
-
end: record.end,
|
|
51
|
-
text:
|
|
52
|
-
record === selected
|
|
53
|
-
? `Connection1 = ${fields.map((value, index) => (index >= 12 ? quoted(value) : value)).join(",")};`
|
|
54
|
-
: "",
|
|
55
|
-
}));
|
|
56
|
-
for (const [key, record] of sections.get("Assembly") ?? []) {
|
|
57
|
-
const size = resized.get(key);
|
|
58
|
-
if (size === undefined) {
|
|
59
|
-
continue;
|
|
60
|
-
}
|
|
61
|
-
const [name = "", path = "", , descriptor = ""] = record.fields;
|
|
62
|
-
const rawBytes = [
|
|
63
|
-
quoted(name),
|
|
64
|
-
path && quoted(path),
|
|
65
|
-
size,
|
|
66
|
-
descriptor,
|
|
67
|
-
"",
|
|
68
|
-
"",
|
|
69
|
-
size * 8,
|
|
70
|
-
"",
|
|
71
|
-
];
|
|
72
|
-
edits.push({
|
|
73
|
-
start: record.start,
|
|
74
|
-
end: record.end,
|
|
75
|
-
text: `${key} = ${rawBytes.join(",")};`,
|
|
76
|
-
});
|
|
77
|
-
resized.delete(key);
|
|
78
|
-
}
|
|
79
|
-
if (resized.size) {
|
|
80
|
-
throw new Error(`EDS has no ${[...resized.keys()].join(", ")} assembly.`);
|
|
81
|
-
}
|
|
82
|
-
return edits
|
|
83
|
-
.sort((a, b) => b.start - a.start)
|
|
84
|
-
.reduce(
|
|
85
|
-
(result, edit) =>
|
|
86
|
-
result.slice(0, edit.start) + edit.text + result.slice(edit.end),
|
|
87
|
-
text,
|
|
88
|
-
);
|
|
89
|
-
}
|
|
4
|
+
import { boundChannel, type HardwareCatalog } from "./hardware/catalog";
|
|
5
|
+
import { normalizeEds } from "./hardware/eds";
|
|
6
|
+
import { addressBits, directAddress } from "./hardware/process-image";
|
|
90
7
|
|
|
91
8
|
/**
|
|
92
9
|
* The build request for `codesys.deviceTree`: one scanner adapter per configured
|
|
@@ -127,23 +44,23 @@ export async function deviceTree(
|
|
|
127
44
|
if (!("device" in binding) || binding.device !== device.id) {
|
|
128
45
|
return [];
|
|
129
46
|
}
|
|
130
|
-
const channel =
|
|
131
|
-
(item) => item.id === binding.channel,
|
|
132
|
-
)!;
|
|
47
|
+
const channel = boundChannel(catalog, key, binding);
|
|
133
48
|
if (channel.assembly === undefined) {
|
|
134
49
|
return [];
|
|
135
50
|
}
|
|
136
51
|
if (channel.bits === 1) {
|
|
137
|
-
return [{ address: channel.address
|
|
52
|
+
return [{ address: channel.address, text: key }];
|
|
53
|
+
}
|
|
54
|
+
const location = addressBits(channel.address);
|
|
55
|
+
const address =
|
|
56
|
+
location && directAddress(location.region, 0, location.offsetBits, 8);
|
|
57
|
+
if (!address) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
`${key}: channel ${binding.device}.${binding.channel} does not start on a byte.`,
|
|
60
|
+
);
|
|
138
61
|
}
|
|
139
|
-
const area = channel.direction === "input" ? inputs! : outputs!;
|
|
140
62
|
const bytes = channel.bits / 8;
|
|
141
|
-
return [
|
|
142
|
-
{
|
|
143
|
-
address: `${area.address.slice(0, 3)}${byteOffset(area.address) + channel.offsetBits / 8}`,
|
|
144
|
-
text: bytes > 1 ? `${key} (${bytes} bytes)` : key,
|
|
145
|
-
},
|
|
146
|
-
];
|
|
63
|
+
return [{ address, text: bytes > 1 ? `${key} (${bytes} bytes)` : key }];
|
|
147
64
|
});
|
|
148
65
|
const network = config.devices[device.id]?.network;
|
|
149
66
|
if (device.modbus && !network?.address) {
|
package/src/files.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
export const isMissingFile = (error: unknown) =>
|
|
5
|
+
error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
6
|
+
|
|
7
|
+
/** The text of the file at `path`, or null when there is none. */
|
|
8
|
+
export const readIfPresent = (path: string) =>
|
|
9
|
+
readFile(path, "utf8").catch((error: unknown) => {
|
|
10
|
+
if (isMissingFile(error)) {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
throw error;
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
/** Every file under `directory` whose name ends in `.extension`, any case, each directory's entries in `order`. */
|
|
17
|
+
export async function filesUnder(
|
|
18
|
+
directory: string,
|
|
19
|
+
extension: string,
|
|
20
|
+
order: (a: string, b: string) => number,
|
|
21
|
+
): Promise<string[]> {
|
|
22
|
+
const pattern = new RegExp(`\\.${extension}$`, "i");
|
|
23
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
24
|
+
const paths = await Promise.all(
|
|
25
|
+
entries
|
|
26
|
+
.sort((a, b) => order(a.name, b.name))
|
|
27
|
+
.map(async (entry) => {
|
|
28
|
+
const path = join(directory, entry.name);
|
|
29
|
+
if (entry.isDirectory()) {
|
|
30
|
+
return filesUnder(path, extension, order);
|
|
31
|
+
}
|
|
32
|
+
return entry.isFile() && pattern.test(entry.name) ? [path] : [];
|
|
33
|
+
}),
|
|
34
|
+
);
|
|
35
|
+
return paths.flat();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Every Structured Text source under `directory`, in name order. */
|
|
39
|
+
export const stFiles = (directory: string) =>
|
|
40
|
+
filesUnder(directory, "st", (a, b) => (a < b ? -1 : 1));
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { IoChannel } from "./channels";
|
|
2
|
+
import type { EdsConnection, HardwareDescriptor } from "./eds";
|
|
3
|
+
import type { ModbusRegister } from "./modbus";
|
|
4
|
+
|
|
5
|
+
export interface SelectedAssembly {
|
|
6
|
+
direction: "input" | "output";
|
|
7
|
+
instance: number;
|
|
8
|
+
name: string;
|
|
9
|
+
address: string;
|
|
10
|
+
size: number;
|
|
11
|
+
capacity: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface HardwareCatalog {
|
|
15
|
+
descriptors: HardwareDescriptor[];
|
|
16
|
+
devices: {
|
|
17
|
+
id: string;
|
|
18
|
+
descriptor: string;
|
|
19
|
+
connection?: Pick<EdsConnection, "id" | "name" | "path">;
|
|
20
|
+
assemblies: SelectedAssembly[];
|
|
21
|
+
channels: IoChannel[];
|
|
22
|
+
statusSymbols: Record<string, string>;
|
|
23
|
+
modbus?: { port: number; registers: ModbusRegister[] };
|
|
24
|
+
}[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The catalog channel a device binding names. */
|
|
28
|
+
export const deviceChannel = (
|
|
29
|
+
catalog: HardwareCatalog,
|
|
30
|
+
binding: { device: string; channel: string },
|
|
31
|
+
) =>
|
|
32
|
+
catalog.devices
|
|
33
|
+
.find((device) => device.id === binding.device)
|
|
34
|
+
?.channels.find((channel) => channel.id === binding.channel);
|
|
35
|
+
|
|
36
|
+
/** The addressed channel the `io` entry `symbol` binds to. */
|
|
37
|
+
export function boundChannel(
|
|
38
|
+
catalog: HardwareCatalog,
|
|
39
|
+
symbol: string,
|
|
40
|
+
binding: { device: string; channel: string },
|
|
41
|
+
): IoChannel & { address: string } {
|
|
42
|
+
const channel = deviceChannel(catalog, binding);
|
|
43
|
+
if (!channel?.address) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
`${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`,
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
return { ...channel, address: channel.address };
|
|
49
|
+
}
|
package/src/hardware/channels.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { ioScalarBits } from "@tsplc/iec";
|
|
1
|
+
import { arrayTypeText, ioScalarBits } from "@tsplc/iec";
|
|
2
2
|
import type { EdsMember } from "./eds";
|
|
3
|
-
import { directAddress } from "./process-image";
|
|
3
|
+
import { directAddress, regionOf } from "./process-image";
|
|
4
4
|
|
|
5
5
|
export interface IoChannel {
|
|
6
6
|
device: string;
|
|
@@ -29,6 +29,10 @@ export interface AssemblyPlacement {
|
|
|
29
29
|
payloadSize: number;
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
/** Whether a channel is one of the payload bytes `assemblyChannels` lists, rather than a bit or a named member. */
|
|
33
|
+
export const isPayloadByte = (channel: Pick<IoChannel, "id">) =>
|
|
34
|
+
/^(inputs|outputs)\.Byte\d+$/.test(channel.id);
|
|
35
|
+
|
|
32
36
|
/**
|
|
33
37
|
* Every payload byte and bit, then each named member the payload carries. A member
|
|
34
38
|
* spanning several scalars is an array channel with a channel per element.
|
|
@@ -42,7 +46,7 @@ export function assemblyChannels({
|
|
|
42
46
|
payloadSize,
|
|
43
47
|
}: AssemblyPlacement): IoChannel[] {
|
|
44
48
|
const prefix = `${direction}s`;
|
|
45
|
-
const region = direction
|
|
49
|
+
const region = regionOf(direction);
|
|
46
50
|
const payloadBits = payloadSize * 8;
|
|
47
51
|
const address = (offsetBits: number, bits: number) =>
|
|
48
52
|
directAddress(region, base, offsetBits, bits);
|
|
@@ -79,7 +83,6 @@ export function assemblyChannels({
|
|
|
79
83
|
});
|
|
80
84
|
}
|
|
81
85
|
}
|
|
82
|
-
// Repeated parameter names are indexed in assembly order.
|
|
83
86
|
const named = members
|
|
84
87
|
.filter((member) => member.parameter)
|
|
85
88
|
.map((member) => ({ member, name: member.name.replace(/[^\w]/g, "_") }));
|
|
@@ -134,7 +137,11 @@ export function assemblyChannels({
|
|
|
134
137
|
const span: IoChannel = {
|
|
135
138
|
...channel,
|
|
136
139
|
bits: length * scalarBits,
|
|
137
|
-
type:
|
|
140
|
+
type: arrayTypeText({
|
|
141
|
+
lower: 0,
|
|
142
|
+
upper: length - 1,
|
|
143
|
+
element: member.type,
|
|
144
|
+
}),
|
|
138
145
|
// The whole span binds to a logical FixedArray at its first element's address.
|
|
139
146
|
address: address(member.offsetBits, scalarBits),
|
|
140
147
|
};
|