@tsplc/tmp-compiler 0.0.0-stage → 0.6.3
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/LICENSE +21 -0
- package/README.md +41 -2
- package/dist/cli.js +2325 -0
- package/dist/cli.js.map +26 -0
- package/dist/clock.js +11 -0
- package/dist/clock.js.map +11 -0
- package/dist/codesys.js +6563 -0
- package/dist/codesys.js.map +51 -0
- package/dist/collections.js +399 -0
- package/dist/collections.js.map +10 -0
- package/dist/index.js +16198 -0
- package/dist/index.js.map +62 -0
- package/dist/ir.js +3948 -0
- package/dist/ir.js.map +35 -0
- package/dist/retain.js +10 -0
- package/dist/retain.js.map +10 -0
- package/dist/signals.js +115 -0
- package/dist/signals.js.map +10 -0
- package/dist/telemetry.js +121 -0
- package/dist/telemetry.js.map +12 -0
- package/package.json +122 -4
- package/src/codesys/config.ts +50 -0
- package/src/codesys/debug.ts +655 -0
- package/src/codesys/emit.ts +185 -0
- package/src/codesys/endpoints.ts +111 -0
- package/src/codesys/engineering.ts +96 -0
- package/src/codesys/explain/expressions.ts +445 -0
- package/src/codesys/explain/flags.ts +134 -0
- package/src/codesys/explain/parameters.ts +53 -0
- package/src/codesys/explain/rows.ts +182 -0
- package/src/codesys/explain/tables.ts +79 -0
- package/src/codesys/explain/tasks.ts +68 -0
- package/src/codesys/explain/writes.ts +497 -0
- package/src/codesys/explain.ts +149 -0
- package/src/codesys/expressions.ts +100 -0
- package/src/codesys/global-lists.ts +284 -0
- package/src/codesys/global-names.ts +66 -0
- package/src/codesys/http.ts +1090 -0
- package/src/codesys/index.ts +13 -0
- package/src/codesys/instrumentation.ts +574 -0
- package/src/codesys/io-paths.ts +149 -0
- package/src/codesys/loops.ts +101 -0
- package/src/codesys/manifest.ts +684 -0
- package/src/codesys/names.ts +58 -0
- package/src/codesys/numeric.ts +516 -0
- package/src/codesys/plan.ts +688 -0
- package/src/codesys/programs.ts +138 -0
- package/src/codesys/publication.ts +99 -0
- package/src/codesys/required.ts +8 -0
- package/src/codesys/routines.ts +247 -0
- package/src/codesys/scan-clock.ts +103 -0
- package/src/codesys/scheduling.ts +96 -0
- package/src/codesys/service-channels.ts +24 -0
- package/src/codesys/sources.ts +118 -0
- package/src/codesys/st-files.ts +219 -0
- package/src/codesys/statements.ts +409 -0
- package/src/codesys/storage.ts +150 -0
- package/src/codesys/symbols.ts +240 -0
- package/src/codesys/task-access.ts +186 -0
- package/src/codesys/telemetry-settings.ts +19 -0
- package/src/codesys/telemetry.ts +852 -0
- package/src/codesys/types.ts +310 -0
- package/src/codesys/vendor.ts +113 -0
- package/src/frontend/analyzer.ts +779 -0
- package/src/frontend/async.ts +530 -0
- package/src/frontend/blocks.ts +578 -0
- package/src/frontend/configuration.ts +83 -0
- package/src/frontend/const-enums.ts +196 -0
- package/src/frontend/const-functions.ts +204 -0
- package/src/frontend/control-flow.ts +787 -0
- package/src/frontend/cooperative.ts +114 -0
- package/src/frontend/coroutines.ts +1344 -0
- package/src/frontend/dialect-names.ts +104 -0
- package/src/frontend/elaborate/array-searches.ts +224 -0
- package/src/frontend/elaborate/assignments.ts +343 -0
- package/src/frontend/elaborate/calls.ts +1342 -0
- package/src/frontend/elaborate/capture-protocol.ts +237 -0
- package/src/frontend/elaborate/capture.ts +388 -0
- package/src/frontend/elaborate/declarations.ts +124 -0
- package/src/frontend/elaborate/dialect.ts +473 -0
- package/src/frontend/elaborate/expressions.ts +2177 -0
- package/src/frontend/elaborate/filtered-arrays.ts +643 -0
- package/src/frontend/elaborate/frame.ts +145 -0
- package/src/frontend/elaborate/generics.ts +123 -0
- package/src/frontend/elaborate/graph.ts +141 -0
- package/src/frontend/elaborate/imports.ts +105 -0
- package/src/frontend/elaborate/index.ts +851 -0
- package/src/frontend/elaborate/initializers.ts +235 -0
- package/src/frontend/elaborate/iterators.ts +1541 -0
- package/src/frontend/elaborate/layouts.ts +1025 -0
- package/src/frontend/elaborate/model.ts +478 -0
- package/src/frontend/elaborate/names.ts +134 -0
- package/src/frontend/elaborate/reduce.ts +900 -0
- package/src/frontend/elaborate/references.ts +727 -0
- package/src/frontend/elaborate/retention.ts +284 -0
- package/src/frontend/elaborate/specialize.ts +1137 -0
- package/src/frontend/elaborate/statements.ts +1220 -0
- package/src/frontend/elaborate/storage.ts +836 -0
- package/src/frontend/elaborate/time-constructors.ts +34 -0
- package/src/frontend/elaborate/values.ts +200 -0
- package/src/frontend/elaborate/writes.ts +415 -0
- package/src/frontend/expressions.ts +1382 -0
- package/src/frontend/generated-names.ts +95 -0
- package/src/frontend/intrinsics.ts +382 -0
- package/src/frontend/lowering-key.ts +23 -0
- package/src/frontend/module-graph.ts +156 -0
- package/src/frontend/positions.ts +359 -0
- package/src/frontend/promise-chains.ts +872 -0
- package/src/frontend/promises.ts +419 -0
- package/src/frontend/routines.ts +239 -0
- package/src/frontend/sdk.ts +187 -0
- package/src/frontend/services.ts +612 -0
- package/src/frontend/statements.ts +871 -0
- package/src/frontend/tasks.ts +526 -0
- package/src/frontend/telemetry.ts +174 -0
- package/src/frontend/types.ts +1073 -0
- package/src/frontend/typescript.ts +659 -0
- package/src/index.ts +9 -0
- package/src/ir/aggregates.ts +291 -0
- package/src/ir/allocation.ts +96 -0
- package/src/ir/conditions.ts +855 -0
- package/src/ir/core-model.ts +289 -0
- package/src/ir/declarations.ts +281 -0
- package/src/ir/diagnostics.ts +68 -0
- package/src/ir/domains.ts +151 -0
- package/src/ir/fold.ts +279 -0
- package/src/ir/identity.ts +19 -0
- package/src/ir/index.ts +137 -0
- package/src/ir/job-errors.ts +69 -0
- package/src/ir/layouts.ts +211 -0
- package/src/ir/link.ts +302 -0
- package/src/ir/model.ts +394 -0
- package/src/ir/normalization-error.ts +10 -0
- package/src/ir/normalize.ts +52 -0
- package/src/ir/numeric.ts +163 -0
- package/src/ir/operands.ts +160 -0
- package/src/ir/ranges.ts +420 -0
- package/src/ir/routine.ts +1116 -0
- package/src/ir/scalars.ts +453 -0
- package/src/ir/share.ts +790 -0
- package/src/ir/short-circuit.ts +140 -0
- package/src/ir/tables.ts +111 -0
- package/src/ir/temporaries.ts +138 -0
- package/src/ir/types.ts +151 -0
- package/src/project/artifacts.ts +424 -0
- package/src/project/cli.ts +211 -0
- package/src/project/debugger.ts +111 -0
- package/src/project/deployments.ts +387 -0
- package/src/project/flags.ts +14 -0
- package/src/project/git.ts +35 -0
- package/src/project/plant.ts +629 -0
- package/src/project/project-commands.ts +507 -0
- package/src/project/project.ts +559 -0
- package/src/project/release.ts +152 -0
- package/src/project/server-check.ts +54 -0
- package/src/project/server.ts +165 -0
- package/src/project/terminal.ts +45 -0
- package/src/runtime/async.ts +207 -0
- package/src/runtime/launch.ts +59 -0
- package/src/runtime/main.ts +59 -0
- package/src/runtime/missing-file.ts +3 -0
- package/src/runtime/process.ts +177 -0
- package/src/runtime/program.ts +109 -0
- package/src/runtime/retain.ts +108 -0
- package/src/runtime/runtime.ts +324 -0
- package/src/runtime/settings.ts +27 -0
- package/src/runtime/storage.ts +456 -0
- package/src/runtime/symbols.ts +97 -0
- package/src/runtime/telemetry.ts +154 -0
- package/src/runtime/transport.ts +168 -0
- package/stdlib/clock.ts +8 -0
- package/stdlib/collections.ts +534 -0
- package/stdlib/plc-time.ts +2 -0
- package/stdlib/retain.ts +4 -0
- package/stdlib/signals.ts +142 -0
- package/stdlib/telemetry.ts +89 -0
- package/types/async.d.ts +87 -0
- package/types/clock.d.ts +8 -0
- package/types/config.d.ts +2 -0
- package/types/data-types.d.ts +31 -0
- package/types/dialect.d.ts +49 -0
- package/types/globals.d.ts +10 -0
- package/types/index.d.ts +212 -0
- package/types/retain.d.ts +12 -0
- package/types/telemetry.d.ts +47 -0
|
@@ -0,0 +1,1090 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type CoreFunctionBlock,
|
|
3
|
+
type FunctionBlock,
|
|
4
|
+
type GeneratedObject,
|
|
5
|
+
httpErrors,
|
|
6
|
+
jobError,
|
|
7
|
+
type PlcType,
|
|
8
|
+
type Variable,
|
|
9
|
+
} from "@tsplc/compiler/ir";
|
|
10
|
+
import { instrumentationFields } from "@tsplc/debug/manifest";
|
|
11
|
+
import {
|
|
12
|
+
elementaryType,
|
|
13
|
+
elementaryTypes,
|
|
14
|
+
fitsNumber,
|
|
15
|
+
integerRange,
|
|
16
|
+
} from "@tsplc/iec";
|
|
17
|
+
import { maxRecordFields } from "@tsplc/server/contract";
|
|
18
|
+
import { requestHeader } from "@tsplc/server/requests";
|
|
19
|
+
import {
|
|
20
|
+
epochLength,
|
|
21
|
+
plcBufferBytes,
|
|
22
|
+
type ServiceChannel,
|
|
23
|
+
serviceOfPath,
|
|
24
|
+
slotIdLength,
|
|
25
|
+
slotStatus,
|
|
26
|
+
} from "@tsplc/server/wire";
|
|
27
|
+
import type { NativeEndpoint } from "./endpoints";
|
|
28
|
+
import type { CodesysPlan } from "./plan";
|
|
29
|
+
import { required } from "./required";
|
|
30
|
+
import type { EmissionContext, GlobalSymbols } from "./symbols";
|
|
31
|
+
import { type CodesysTypes, stStringLiteral } from "./types";
|
|
32
|
+
|
|
33
|
+
const opcuaServiceCapacity = 16;
|
|
34
|
+
|
|
35
|
+
/** The native client's request and response buffers, in bytes, each with room for its terminating NUL. */
|
|
36
|
+
const wireBytes = 8192;
|
|
37
|
+
/** The most bytes a response's headers may take. */
|
|
38
|
+
const headerBytes = 4096;
|
|
39
|
+
|
|
40
|
+
/*
|
|
41
|
+
* SysSocket Interfaces' SOCKET_SOL, the socket level, and SOCKET_SO_KEEPALIVE, which the project
|
|
42
|
+
* doesn't reference by name.
|
|
43
|
+
*/
|
|
44
|
+
const socketLevel = "16#FFFF";
|
|
45
|
+
const socketKeepAliveOption = "16#8";
|
|
46
|
+
const keepAliveIdleMs = 2000;
|
|
47
|
+
const keepAliveIntervalMs = 1000;
|
|
48
|
+
const keepAliveProbes = 3;
|
|
49
|
+
|
|
50
|
+
/** The procedure a service block calls, as the server names it; its path when that isn't a service path. */
|
|
51
|
+
export const serviceName = (path: string) => serviceOfPath(path) ?? path;
|
|
52
|
+
|
|
53
|
+
/** The most characters an integer prints as in decimal, its sign included. */
|
|
54
|
+
export const decimalLength = (layout: Parameters<typeof integerRange>[0]) =>
|
|
55
|
+
Math.max(...integerRange(layout).map((bound) => String(bound).length));
|
|
56
|
+
|
|
57
|
+
/** The unsigned IEC integer, at least DINT-wide, that ST widens a value of `bits` to. */
|
|
58
|
+
export const unsignedWidening = (bits: number): string => {
|
|
59
|
+
const type = elementaryTypes.find(
|
|
60
|
+
(item) =>
|
|
61
|
+
item.family === "integer" &&
|
|
62
|
+
!item.signed &&
|
|
63
|
+
item.bits >= Math.max(bits, 32),
|
|
64
|
+
);
|
|
65
|
+
if (!type) {
|
|
66
|
+
throw new Error(`No unsigned integer holds ${bits} bits.`);
|
|
67
|
+
}
|
|
68
|
+
return type.name;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* A scalar as JSON: the most bytes it takes, the ST that appends `value` with the encoder methods
|
|
73
|
+
* of `jsonEncoders`, and, when a 32-bit read holds it, the ST that reads it into `value` from
|
|
74
|
+
* `payload`, flagging a malformed one.
|
|
75
|
+
*/
|
|
76
|
+
interface JsonScalar {
|
|
77
|
+
size: number;
|
|
78
|
+
encode: (value: string) => string;
|
|
79
|
+
decode?: (value: string, target: CodesysTypes) => string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The ST that reads a JSON integer into `assign`'s target, flagging one outside `range` as malformed. */
|
|
83
|
+
const readInteger = (range: readonly [bigint, bigint], assign: string) =>
|
|
84
|
+
`ReadInteger(); IF numberValue < ${range[0]} OR numberValue > ${range[1]} THEN malformed:=TRUE; ELSE ${assign} END_IF;`;
|
|
85
|
+
|
|
86
|
+
/** A BOOL, integer, bit string or UTF-8 STRING as JSON. */
|
|
87
|
+
export const jsonScalar = (type: PlcType): JsonScalar | undefined => {
|
|
88
|
+
if (
|
|
89
|
+
type.kind === "string" &&
|
|
90
|
+
type.encoding === "utf8" &&
|
|
91
|
+
type.capacity <= plcBufferBytes
|
|
92
|
+
) {
|
|
93
|
+
return {
|
|
94
|
+
size: type.capacity * 6 + 2,
|
|
95
|
+
encode: (value) => `WriteString(${value});`,
|
|
96
|
+
decode: (value) =>
|
|
97
|
+
`ReadString(); IF ByteLength(token) > ${type.capacity} THEN malformed := TRUE; ELSE ${value} := token; END_IF;`,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
if (type.kind === "bool") {
|
|
101
|
+
return {
|
|
102
|
+
size: 5,
|
|
103
|
+
encode: (value) =>
|
|
104
|
+
`IF ${value} THEN Append('true'); ELSE Append('false'); END_IF;`,
|
|
105
|
+
decode: (value) =>
|
|
106
|
+
`IF MatchLiteral('true') THEN ${value}:=TRUE; ELSIF MatchLiteral('false') THEN ${value}:=FALSE; ELSE malformed:=TRUE;END_IF;`,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
if (type.kind !== "bits" && type.kind !== "integer") {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
const layout = {
|
|
113
|
+
bits: type.bits,
|
|
114
|
+
signed: type.kind === "integer" && type.signed,
|
|
115
|
+
};
|
|
116
|
+
const wide = unsignedWidening(type.bits);
|
|
117
|
+
return {
|
|
118
|
+
size: decimalLength(layout),
|
|
119
|
+
encode: (value) =>
|
|
120
|
+
type.kind === "bits"
|
|
121
|
+
? `Append(${wide}_TO_STRING(TO_${wide}(${value})));`
|
|
122
|
+
: `Append(${type.id}_TO_STRING(${value}));`,
|
|
123
|
+
...(fitsNumber(elementaryType(type.id)) && {
|
|
124
|
+
decode: (value: string, target: CodesysTypes) =>
|
|
125
|
+
readInteger(
|
|
126
|
+
integerRange(layout),
|
|
127
|
+
`${value}:=TO_${target.name(type.id)}(numberValue);`,
|
|
128
|
+
),
|
|
129
|
+
}),
|
|
130
|
+
};
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
/** A scalar a service record carries: a strict enum as its DINT base, else a scalar a 32-bit read holds. */
|
|
134
|
+
const serviceScalar = (type: PlcType): Required<JsonScalar> | undefined => {
|
|
135
|
+
if (type.kind === "enum") {
|
|
136
|
+
return {
|
|
137
|
+
size: Math.max(...type.members.map((member) => member.value.length)),
|
|
138
|
+
encode: (value) => `Append(DINT_TO_STRING(TO_DINT(${value})));`,
|
|
139
|
+
decode: (value, target) =>
|
|
140
|
+
readInteger(
|
|
141
|
+
integerRange(elementaryType("DINT")),
|
|
142
|
+
`CASE numberValue OF ${type.members.map((m) => `${m.value}: ${value}:=${target.name(type.id)}.${target.field(type.id, m.name)};`).join(" ")} ELSE malformed:=TRUE; END_CASE;`,
|
|
143
|
+
),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
const scalar = jsonScalar(type);
|
|
147
|
+
return scalar?.decode && { ...scalar, decode: scalar.decode };
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
type RecordLayout = Extract<PlcType, { kind: "record" }>;
|
|
151
|
+
|
|
152
|
+
/** A service block's request and response ports and their records; no response when the call answers nothing. */
|
|
153
|
+
interface HttpLayout {
|
|
154
|
+
request: Variable;
|
|
155
|
+
requestLayout: RecordLayout;
|
|
156
|
+
response: { port: Variable; layout: RecordLayout } | null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* A service block's layout, or why its JSON cannot be exchanged: a record the codecs cannot
|
|
161
|
+
* encode, or one whose worst case overflows the buffer.
|
|
162
|
+
*/
|
|
163
|
+
export const httpLayout = (
|
|
164
|
+
block: CoreFunctionBlock,
|
|
165
|
+
types: ReadonlyMap<string, PlcType>,
|
|
166
|
+
): HttpLayout | { error: string } => {
|
|
167
|
+
const request = block.inputs.find((v) => v.name === "request");
|
|
168
|
+
// A call that answers nothing has no result port.
|
|
169
|
+
const result = block.outputs.find((v) => v.name === "result");
|
|
170
|
+
if (!request) {
|
|
171
|
+
return { error: "Missing HTTP record ports." };
|
|
172
|
+
}
|
|
173
|
+
const requestLayout = types.get(request.type);
|
|
174
|
+
const resultLayout = result && types.get(result.type);
|
|
175
|
+
const response =
|
|
176
|
+
result && resultLayout?.kind === "record"
|
|
177
|
+
? { port: result, layout: resultLayout }
|
|
178
|
+
: null;
|
|
179
|
+
if (
|
|
180
|
+
requestLayout?.kind !== "record" ||
|
|
181
|
+
(result &&
|
|
182
|
+
(!response ||
|
|
183
|
+
response.layout.fields.length === 0 ||
|
|
184
|
+
response.layout.fields.length > maxRecordFields))
|
|
185
|
+
) {
|
|
186
|
+
return {
|
|
187
|
+
error: `HTTP requires closed request/response records with 1..${maxRecordFields} response fields.`,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
const scalarSize = (id: string): number | undefined => {
|
|
191
|
+
const type = types.get(id);
|
|
192
|
+
return type && serviceScalar(type)?.size;
|
|
193
|
+
};
|
|
194
|
+
const fieldSize = (
|
|
195
|
+
field: RecordLayout["fields"][number],
|
|
196
|
+
response: boolean,
|
|
197
|
+
): number | undefined => {
|
|
198
|
+
const type = types.get(field.type);
|
|
199
|
+
if (type?.kind !== "array" || response) {
|
|
200
|
+
return scalarSize(field.type);
|
|
201
|
+
}
|
|
202
|
+
const element = scalarSize(type.element);
|
|
203
|
+
return element === undefined ? undefined : 2 + type.length * (element + 1);
|
|
204
|
+
};
|
|
205
|
+
const records = [
|
|
206
|
+
[requestLayout, false],
|
|
207
|
+
...(response ? [[response.layout, true] as const] : []),
|
|
208
|
+
] as const;
|
|
209
|
+
for (const [record, answer] of records) {
|
|
210
|
+
const sizes = record.fields.map((field) => fieldSize(field, answer));
|
|
211
|
+
if (!sizes.every((size): size is number => size !== undefined)) {
|
|
212
|
+
return {
|
|
213
|
+
error:
|
|
214
|
+
"HTTP JSON supports bounded UTF-8 strings, BOOL, enums, and integers up to 32 bits.",
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
const size = record.fields.reduce(
|
|
218
|
+
(total, field) => total + field.name.length + 4,
|
|
219
|
+
sizes.reduce((total, value) => total + value, 2),
|
|
220
|
+
);
|
|
221
|
+
if (size > plcBufferBytes) {
|
|
222
|
+
return {
|
|
223
|
+
error: `The worst-case HTTP JSON payload exceeds the native ${plcBufferBytes}-byte buffer; reduce record/string/array bounds.`,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return { request, requestLayout, response };
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
/** A service block's typed JSON codecs and ports; no application protocol lives here. */
|
|
231
|
+
interface ServiceCodecs {
|
|
232
|
+
port: (label: string) => string;
|
|
233
|
+
/** Appends the request record's fields as JSON. */
|
|
234
|
+
requestCode: string;
|
|
235
|
+
/** Decodes the response record from `payload`, setting `error` to `jobError.malformedResponse` when it is malformed. */
|
|
236
|
+
decodeResponse: string;
|
|
237
|
+
inputs: string;
|
|
238
|
+
outputs: string;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const serviceCodecs = (
|
|
242
|
+
block: CoreFunctionBlock,
|
|
243
|
+
fields: ReadonlyMap<string, string>,
|
|
244
|
+
types: ReadonlyMap<string, PlcType>,
|
|
245
|
+
target: CodesysTypes,
|
|
246
|
+
): ServiceCodecs => {
|
|
247
|
+
const port = (label: string) => {
|
|
248
|
+
const variable = [...block.inputs, ...block.outputs].find(
|
|
249
|
+
(v) => v.name === label,
|
|
250
|
+
);
|
|
251
|
+
if (!variable) {
|
|
252
|
+
throw new Error(`Missing HTTP port ${label}`);
|
|
253
|
+
}
|
|
254
|
+
return required(fields.get(variable.id));
|
|
255
|
+
};
|
|
256
|
+
const layout = httpLayout(block, types);
|
|
257
|
+
if ("error" in layout) {
|
|
258
|
+
throw new Error(layout.error);
|
|
259
|
+
}
|
|
260
|
+
const { request, requestLayout, response } = layout;
|
|
261
|
+
const typeOf = (id: string) => required(types.get(id));
|
|
262
|
+
const scalarOf = (type: PlcType) => required(serviceScalar(type));
|
|
263
|
+
const encode = (type: PlcType, value: string): string =>
|
|
264
|
+
type.kind === "array"
|
|
265
|
+
? Array.from(
|
|
266
|
+
{ length: type.length },
|
|
267
|
+
(_, i) =>
|
|
268
|
+
`${i ? "Append(',');" : ""}${encode(typeOf(type.element), `${value}[${i + type.lowerBound}]`)}`,
|
|
269
|
+
).join("\n")
|
|
270
|
+
: scalarOf(type).encode(value);
|
|
271
|
+
const requestCode = requestLayout.fields
|
|
272
|
+
.map((field, i) => {
|
|
273
|
+
const type = typeOf(field.type);
|
|
274
|
+
const value = `${port("request")}.${target.field(request.type, field.name)}`;
|
|
275
|
+
return `Append(${stStringLiteral(`${i ? "," : ""}"${field.name}":`)});${type.kind === "array" ? "Append('[');" : ""}${encode(type, value)}${type.kind === "array" ? "Append(']');" : ""}`;
|
|
276
|
+
})
|
|
277
|
+
.join("\n");
|
|
278
|
+
const declarations = (variables: readonly Variable[]) =>
|
|
279
|
+
variables
|
|
280
|
+
.map((v) => `${required(fields.get(v.id))} : ${target.name(v.type)};`)
|
|
281
|
+
.join("\n");
|
|
282
|
+
const inputs = declarations(block.inputs);
|
|
283
|
+
const outputs = declarations(block.outputs);
|
|
284
|
+
const decodeRecord = (result: Variable, record: RecordLayout) => {
|
|
285
|
+
// `seen` has a bit for each response field, so a record has at most `maxRecordFields`.
|
|
286
|
+
const responseCode = record.fields
|
|
287
|
+
.map((field, i) => {
|
|
288
|
+
const value = `${port("result")}.${target.field(result.type, field.name)}`;
|
|
289
|
+
const decode = scalarOf(typeOf(field.type)).decode(value, target);
|
|
290
|
+
return `${i === 0 ? "IF" : "ELSIF"} part = ${stStringLiteral(field.name)} THEN IF (seen AND SHL(DWORD#1,${i})) <> 0 THEN malformed:=TRUE; END_IF; seen:=seen OR SHL(DWORD#1,${i}); ${decode}`;
|
|
291
|
+
})
|
|
292
|
+
.join("\n");
|
|
293
|
+
return `cursor:=1;malformed:=FALSE;seen:=0;
|
|
294
|
+
SkipWhitespace();Expect(123);SkipWhitespace();
|
|
295
|
+
WHILE cursor<=TO_UINT(ByteLength(payload)) AND NOT malformed DO
|
|
296
|
+
IF payload[cursor-1]=125 THEN cursor:=cursor+1;EXIT;END_IF;
|
|
297
|
+
ReadString();part:=token;SkipWhitespace();Expect(58);SkipWhitespace();
|
|
298
|
+
${responseCode} ELSE malformed:=TRUE;END_IF;
|
|
299
|
+
SkipWhitespace();
|
|
300
|
+
IF payload[cursor-1]=44 THEN cursor:=cursor+1;SkipWhitespace();IF payload[cursor-1]=125 THEN malformed:=TRUE;END_IF;
|
|
301
|
+
ELSIF payload[cursor-1]<>125 THEN malformed:=TRUE;END_IF;
|
|
302
|
+
END_WHILE;
|
|
303
|
+
SkipWhitespace();
|
|
304
|
+
IF malformed OR cursor<>TO_UINT(ByteLength(payload))+1 OR seen<>DWORD#${2 ** record.fields.length - 1} THEN ${port("error")}:=${jobError.malformedResponse};END_IF;`;
|
|
305
|
+
};
|
|
306
|
+
// A call that answers nothing succeeds on its reply's status alone, so its body is never read.
|
|
307
|
+
const decodeResponse = response
|
|
308
|
+
? decodeRecord(response.port, response.layout)
|
|
309
|
+
: "";
|
|
310
|
+
return { port, requestCode, decodeResponse, inputs, outputs };
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* The global list an OPC UA client's calls to `path` go through, and its slots as channels for the
|
|
315
|
+
* server's gateway. Requests are read-only to the gateway; replies and connection epochs it writes.
|
|
316
|
+
*/
|
|
317
|
+
export const rpcSlots = (
|
|
318
|
+
symbols: GlobalSymbols,
|
|
319
|
+
id: string,
|
|
320
|
+
owner: string,
|
|
321
|
+
path: string,
|
|
322
|
+
): { list: GeneratedObject; channels: ServiceChannel[] } => {
|
|
323
|
+
const name = symbols.names.allocateObject("GVL", `TsplcRpc_${owner}`);
|
|
324
|
+
return {
|
|
325
|
+
list: {
|
|
326
|
+
id: `${id}:rpc`,
|
|
327
|
+
kind: "globalList",
|
|
328
|
+
name,
|
|
329
|
+
declaration: `{attribute 'qualified_only'}
|
|
330
|
+
VAR_GLOBAL
|
|
331
|
+
{attribute 'symbol' := 'read'} requests:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${plcBufferBytes});
|
|
332
|
+
{attribute 'symbol' := 'read'} requestIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${slotIdLength});
|
|
333
|
+
{attribute 'symbol' := 'readwrite'} replyIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${slotIdLength});
|
|
334
|
+
{attribute 'symbol' := 'readwrite'} replies:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${plcBufferBytes});
|
|
335
|
+
{attribute 'symbol' := 'readwrite'} epochs:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${epochLength});
|
|
336
|
+
inUse:ARRAY[1..${opcuaServiceCapacity}] OF __XWORD;
|
|
337
|
+
sequence:ARRAY[1..${opcuaServiceCapacity}] OF UDINT;
|
|
338
|
+
END_VAR`,
|
|
339
|
+
},
|
|
340
|
+
channels: Array.from({ length: opcuaServiceCapacity }, (_, index) => ({
|
|
341
|
+
path,
|
|
342
|
+
request: `${name}.requests[${index + 1}]`,
|
|
343
|
+
reply: `${name}.replies[${index + 1}]`,
|
|
344
|
+
requestId: `${name}.requestIds[${index + 1}]`,
|
|
345
|
+
replyId: `${name}.replyIds[${index + 1}]`,
|
|
346
|
+
epoch: `${name}.epochs[${index + 1}]`,
|
|
347
|
+
})),
|
|
348
|
+
};
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
/** The ASCII code of a one-character string, as a reply's bytes are compared. */
|
|
352
|
+
const ascii = (character: string) => character.charCodeAt(0);
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* A client block that exchanges what `body` appends to `payload` and its reply through a slot of
|
|
356
|
+
* `rpcGlobal`, as `nativeHttp` does over HTTP. A reply whose status is `slotStatus.refused` is
|
|
357
|
+
* reported as HTTP 400, and any status but `slotStatus.ok` as a network error. On success `decode`
|
|
358
|
+
* runs over the reply's body in `payload`.
|
|
359
|
+
*/
|
|
360
|
+
export const opcuaClient = ({
|
|
361
|
+
id,
|
|
362
|
+
name,
|
|
363
|
+
ports,
|
|
364
|
+
port,
|
|
365
|
+
timeoutMs,
|
|
366
|
+
rpcGlobal,
|
|
367
|
+
body,
|
|
368
|
+
decode,
|
|
369
|
+
}: {
|
|
370
|
+
id: string;
|
|
371
|
+
name: string;
|
|
372
|
+
/** Its input and output declarations, with `start`, `cancel`, `busy`, `done` and `error`. */
|
|
373
|
+
ports: string;
|
|
374
|
+
port: (label: string) => string;
|
|
375
|
+
timeoutMs: number;
|
|
376
|
+
rpcGlobal: string;
|
|
377
|
+
body: string;
|
|
378
|
+
decode: string;
|
|
379
|
+
}): GeneratedObject => {
|
|
380
|
+
const channel = (field: string, index = "slotIndex") =>
|
|
381
|
+
`${rpcGlobal}.${field}[${index}]`;
|
|
382
|
+
return {
|
|
383
|
+
id,
|
|
384
|
+
kind: "functionBlock",
|
|
385
|
+
name,
|
|
386
|
+
declaration: `FUNCTION_BLOCK ${name}
|
|
387
|
+
${ports}
|
|
388
|
+
VAR
|
|
389
|
+
timeout:TON;stage:UINT;slotIndex:UINT;candidate:UINT;
|
|
390
|
+
identity:STRING(${slotIdLength});epoch:STRING(${epochLength});prefix:STRING(80);
|
|
391
|
+
payload:STRING(${plcBufferBytes});token:STRING(${plcBufferBytes});part:STRING(${plcBufferBytes});
|
|
392
|
+
cursor:UINT;malformed:BOOL;seen:DWORD;numberValue:LINT;tokenUsed:UINT;
|
|
393
|
+
END_VAR`,
|
|
394
|
+
implementation: `IF NOT ${port("start")} OR ${port("cancel")} THEN
|
|
395
|
+
IF slotIndex>0 THEN ${channel("requestIds")}:='';${channel("requests")}:='';${channel("inUse")}:=0;END_IF;
|
|
396
|
+
slotIndex:=0;stage:=0;timeout(IN:=FALSE);${port("busy")}:=FALSE;${port("done")}:=FALSE;${port("error")}:=0;RETURN;
|
|
397
|
+
END_IF;
|
|
398
|
+
IF stage=0 THEN
|
|
399
|
+
FOR candidate:=1 TO ${opcuaServiceCapacity} DO
|
|
400
|
+
(* __COMPARE_AND_SWAP can fail spuriously on ARM64; retry while the slot reads free. *)
|
|
401
|
+
WHILE slotIndex=0 AND ${channel("epochs", "candidate")}<>'' AND ${channel("inUse", "candidate")}=0 DO
|
|
402
|
+
IF __COMPARE_AND_SWAP(ADR(${channel("inUse", "candidate")}),0,1) THEN slotIndex:=candidate;END_IF;
|
|
403
|
+
END_WHILE;
|
|
404
|
+
IF slotIndex>0 THEN EXIT;END_IF;
|
|
405
|
+
END_FOR;
|
|
406
|
+
IF slotIndex=0 THEN ${port("error")}:=${jobError.noRequestSlot};stage:=90;
|
|
407
|
+
ELSE
|
|
408
|
+
${channel("sequence")}:=${channel("sequence")}+1;
|
|
409
|
+
IF ${channel("sequence")}=0 THEN ${channel("epochs")}:='';${port("error")}:=${jobError.network};stage:=90;
|
|
410
|
+
ELSE
|
|
411
|
+
epoch:=${channel("epochs")};identity:=CONCAT(CONCAT(epoch,':'),UDINT_TO_STRING(${channel("sequence")}));
|
|
412
|
+
prefix:=CONCAT(identity,'|');payload:='';malformed:=FALSE;
|
|
413
|
+
${body}
|
|
414
|
+
IF malformed THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
|
|
415
|
+
ELSIF ByteLength(payload)+LEN(prefix)>${plcBufferBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
|
|
416
|
+
ELSE
|
|
417
|
+
FOR candidate:=0 TO LEN(prefix)-1 DO ${channel("requests")}[candidate]:=prefix[candidate];END_FOR;
|
|
418
|
+
FOR candidate:=0 TO ByteLength(payload)-1 DO ${channel("requests")}[candidate+LEN(prefix)]:=payload[candidate];END_FOR;
|
|
419
|
+
${channel("requests")}[ByteLength(payload)+LEN(prefix)]:=0;${channel("requestIds")}:=identity;stage:=1;
|
|
420
|
+
END_IF;
|
|
421
|
+
END_IF;
|
|
422
|
+
END_IF;
|
|
423
|
+
END_IF;
|
|
424
|
+
timeout(IN:=stage<90,PT:=T#${timeoutMs}ms);
|
|
425
|
+
IF timeout.Q THEN ${port("error")}:=${jobError.timeout};stage:=90;END_IF;
|
|
426
|
+
IF stage=1 THEN
|
|
427
|
+
IF ${channel("epochs")}<>epoch THEN ${port("error")}:=${jobError.network};stage:=90;
|
|
428
|
+
ELSIF ${channel("replyIds")}=identity AND_THEN LEFT(${channel("replies")},LEN(prefix))=prefix THEN
|
|
429
|
+
payload:='';cursor:=LEN(prefix);
|
|
430
|
+
IF ByteLength(${channel("replies")})<cursor+4 THEN ${port("error")}:=${jobError.malformedResponse};
|
|
431
|
+
ELSIF ${channel("replies")}[cursor+1]<>${ascii("|")} THEN ${port("error")}:=${jobError.network};
|
|
432
|
+
ELSIF ${channel("replies")}[cursor]=${ascii(String(slotStatus.refused))} THEN ${port("error")}:=${httpErrors.refused};
|
|
433
|
+
ELSIF ${channel("replies")}[cursor]<>${ascii(String(slotStatus.ok))} THEN ${port("error")}:=${jobError.network};
|
|
434
|
+
ELSE
|
|
435
|
+
FOR candidate:=cursor+2 TO ByteLength(${channel("replies")})-1 DO payload[candidate-cursor-2]:=${channel("replies")}[candidate];END_FOR;
|
|
436
|
+
payload[ByteLength(${channel("replies")})-cursor-2]:=0;
|
|
437
|
+
${decode}
|
|
438
|
+
END_IF;
|
|
439
|
+
stage:=90;
|
|
440
|
+
END_IF;
|
|
441
|
+
END_IF;
|
|
442
|
+
${port("busy")}:=stage<90;
|
|
443
|
+
IF stage=90 THEN
|
|
444
|
+
IF slotIndex>0 THEN ${channel("requestIds")}:='';${channel("requests")}:='';${channel("inUse")}:=0;slotIndex:=0;END_IF;
|
|
445
|
+
timeout(IN:=FALSE);${port("busy")}:=FALSE;${port("done")}:=TRUE;
|
|
446
|
+
END_IF;`,
|
|
447
|
+
};
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
type HttpRuntime = Extract<
|
|
451
|
+
NonNullable<FunctionBlock["runtime"]>,
|
|
452
|
+
{ kind: "http" }
|
|
453
|
+
>;
|
|
454
|
+
|
|
455
|
+
/** An HTTP service block: a native client that sends the request record and decodes the response. */
|
|
456
|
+
const httpServiceBlock = (
|
|
457
|
+
id: string,
|
|
458
|
+
runtime: HttpRuntime,
|
|
459
|
+
name: string,
|
|
460
|
+
{ port, requestCode, decodeResponse, inputs, outputs }: ServiceCodecs,
|
|
461
|
+
endpoint: NativeEndpoint,
|
|
462
|
+
network: string,
|
|
463
|
+
/** The requesting job's id input and this block's request counter, sent as `requestHeader`. */
|
|
464
|
+
trace: { job: string; sequence: string } | undefined,
|
|
465
|
+
): [GeneratedObject, ...GeneratedObject[]] =>
|
|
466
|
+
nativeHttp({
|
|
467
|
+
id,
|
|
468
|
+
name,
|
|
469
|
+
ports: `VAR_INPUT
|
|
470
|
+
${inputs}${trace ? `\n${trace.job} : ${instrumentationFields.job};` : ""}
|
|
471
|
+
END_VAR
|
|
472
|
+
VAR_OUTPUT
|
|
473
|
+
${outputs}
|
|
474
|
+
END_VAR`,
|
|
475
|
+
port,
|
|
476
|
+
endpoint,
|
|
477
|
+
network,
|
|
478
|
+
method: runtime.method,
|
|
479
|
+
json: runtime.json,
|
|
480
|
+
body: runtime.json ? `Append('{'); ${requestCode} Append('}');` : "",
|
|
481
|
+
decode: decodeResponse,
|
|
482
|
+
...(trace && { trace }),
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* A native HTTP/1.1 client block over Net Base Services: it sends what `body` appends to
|
|
487
|
+
* `payload` and, on a 2xx response, runs `decode` over the response body in `payload`.
|
|
488
|
+
*/
|
|
489
|
+
export const nativeHttp = ({
|
|
490
|
+
id,
|
|
491
|
+
name,
|
|
492
|
+
ports,
|
|
493
|
+
port,
|
|
494
|
+
endpoint,
|
|
495
|
+
network,
|
|
496
|
+
method,
|
|
497
|
+
json,
|
|
498
|
+
body,
|
|
499
|
+
decode,
|
|
500
|
+
trace,
|
|
501
|
+
}: {
|
|
502
|
+
id: string;
|
|
503
|
+
name: string;
|
|
504
|
+
/** Its input and output declarations, with `start`, `cancel`, `busy`, `done` and `error`. */
|
|
505
|
+
ports: string;
|
|
506
|
+
port: (label: string) => string;
|
|
507
|
+
endpoint: NativeEndpoint;
|
|
508
|
+
network: string;
|
|
509
|
+
method: string;
|
|
510
|
+
json: boolean;
|
|
511
|
+
body: string;
|
|
512
|
+
decode: string;
|
|
513
|
+
/** The requesting job's id input and this block's request counter, sent as `requestHeader`. */
|
|
514
|
+
trace?: { job: string; sequence: string };
|
|
515
|
+
}): [GeneratedObject, ...GeneratedObject[]] => {
|
|
516
|
+
const tracedRequest = trace
|
|
517
|
+
? `AppendWire(UDINT_TO_STRING(${trace.job}));AppendWire(':');AppendWire(UDINT_TO_STRING(${trace.sequence}));AppendWire('$R$NContent-Length: ');`
|
|
518
|
+
: "";
|
|
519
|
+
const release =
|
|
520
|
+
"resolver(xExecute:=FALSE,itfIPAddress:=remoteIP);client(xEnable:=FALSE);writer(xExecute:=FALSE);reader(xEnable:=FALSE);timeout(IN:=FALSE);";
|
|
521
|
+
const block: GeneratedObject = {
|
|
522
|
+
id,
|
|
523
|
+
kind: "functionBlock",
|
|
524
|
+
name,
|
|
525
|
+
declaration: `FUNCTION_BLOCK ${name}
|
|
526
|
+
${ports}
|
|
527
|
+
VAR
|
|
528
|
+
remoteAddress : NBS.IPv4Address;
|
|
529
|
+
remoteIP : NBS.IIPAddress := remoteAddress;
|
|
530
|
+
resolver : NBS.ResolveHostname := (itfAsyncProperty:=${network});
|
|
531
|
+
${endpoint.tls ? `certificateVerifier : ${name}_CertificateVerifier;\n tlsContext : NBS.TLSContext := (itfCertVerifer:=certificateVerifier,sUseCaseName:='tsPLC HTTPS',ePurpose:=NBS.PURPOSE.CLIENT_SIDE,sTLSVersion:='1.2',sHostname:=${stStringLiteral(endpoint.host)},udiVerificationMode:=2);` : ""}
|
|
532
|
+
client : NBS.TCP_Client := (itfAsyncProperty:=${network},itfIPAddress:=remoteAddress,uiPort:=${endpoint.port},udiTimeOut:=${endpoint.timeoutMs * 1000}${endpoint.tls ? ",itfTLSContext:=tlsContext" : ""});
|
|
533
|
+
writer : NBS.TCP_Write;
|
|
534
|
+
reader : NBS.TCP_Read;
|
|
535
|
+
timeout : TON;
|
|
536
|
+
keepAlive : ${name}_KeepAlive;
|
|
537
|
+
stage : UINT;
|
|
538
|
+
wire : STRING(${wireBytes});
|
|
539
|
+
received : STRING(${wireBytes});
|
|
540
|
+
chunk : ARRAY[0..${wireBytes - 1}] OF BYTE;
|
|
541
|
+
payload : STRING(${plcBufferBytes});
|
|
542
|
+
token : STRING(${plcBufferBytes});
|
|
543
|
+
part : STRING(${plcBufferBytes});
|
|
544
|
+
used : UINT;
|
|
545
|
+
headerEnd : UINT;
|
|
546
|
+
contentLength : DINT;
|
|
547
|
+
status : UINT;
|
|
548
|
+
cursor : UINT;
|
|
549
|
+
malformed : BOOL;
|
|
550
|
+
seen : DWORD;
|
|
551
|
+
numberValue : LINT;
|
|
552
|
+
wireUsed : UINT;
|
|
553
|
+
tokenUsed : UINT;
|
|
554
|
+
index : UINT;${trace ? `\n ${trace.sequence} : ${instrumentationFields.sequence};` : ""}
|
|
555
|
+
END_VAR
|
|
556
|
+
`,
|
|
557
|
+
// The host goes in the resolver call, not an initial value: an online change keeps the values
|
|
558
|
+
// an instance already holds, so a changed host would otherwise wait for a download.
|
|
559
|
+
implementation: `IF NOT ${port("start")} OR ${port("cancel")} THEN
|
|
560
|
+
${release}
|
|
561
|
+
stage:=0; ${port("busy")}:=FALSE; ${port("done")}:=FALSE; ${port("error")}:=0;
|
|
562
|
+
RETURN;
|
|
563
|
+
END_IF;
|
|
564
|
+
IF stage=0 THEN
|
|
565
|
+
client.SetOptionProvider(itfOptionProvider:=keepAlive);
|
|
566
|
+
payload:=''; malformed:=FALSE; used:=0; received:='';${trace ? `\n ${trace.sequence}:=${trace.sequence}+1;` : ""}
|
|
567
|
+
${body}
|
|
568
|
+
IF malformed THEN ${port("error")}:=${jobError.tooLarge}; stage:=90;
|
|
569
|
+
ELSE
|
|
570
|
+
wire:='';wireUsed:=0;
|
|
571
|
+
AppendWire(${stStringLiteral(`${method} ${endpoint.path} HTTP/1.1\r\nHost: ${endpoint.authority}\r\n${endpoint.token ? `Authorization: Bearer ${endpoint.token}\r\n` : ""}${json ? "Content-Type: application/json\r\n" : ""}Accept: application/json\r\nConnection: close\r\n${trace ? `${requestHeader}: ` : "Content-Length: "}`)});${tracedRequest}
|
|
572
|
+
AppendWire(UINT_TO_STRING(ByteLength(payload)));AppendWire('$R$N$R$N');AppendWire(payload); stage:=10;
|
|
573
|
+
END_IF;
|
|
574
|
+
END_IF;
|
|
575
|
+
timeout(IN:=stage<90,PT:=T#${endpoint.timeoutMs}ms);
|
|
576
|
+
IF timeout.Q THEN ${port("error")}:=${jobError.timeout}; stage:=90; END_IF;
|
|
577
|
+
${port("busy")}:=stage<90;
|
|
578
|
+
IF stage=10 THEN
|
|
579
|
+
resolver(xExecute:=TRUE,sHostname:=${stStringLiteral(endpoint.host)},itfIPAddress:=remoteIP);
|
|
580
|
+
IF resolver.xError THEN ${port("error")}:=${jobError.network};stage:=90;ELSIF resolver.xDone THEN stage:=1;END_IF;
|
|
581
|
+
END_IF;
|
|
582
|
+
IF stage=1 THEN
|
|
583
|
+
client(xEnable:=TRUE);
|
|
584
|
+
IF client.xError THEN ${port("error")}:=${endpoint.tls ? jobError.tls : jobError.network};stage:=90; ELSIF client.xActive THEN stage:=2;END_IF;
|
|
585
|
+
END_IF;
|
|
586
|
+
IF stage=2 THEN
|
|
587
|
+
writer(xExecute:=TRUE,itfConnection:=client.itfConnection,pData:=ADR(wire),udiSize:=UINT_TO_UDINT(wireUsed));
|
|
588
|
+
IF writer.xError THEN ${port("error")}:=${jobError.network};stage:=90;ELSIF writer.xDone THEN stage:=3;END_IF;
|
|
589
|
+
END_IF;
|
|
590
|
+
IF stage=3 THEN
|
|
591
|
+
IF used>=${wireBytes - 1} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
|
|
592
|
+
ELSE
|
|
593
|
+
reader(xEnable:=TRUE,itfConnection:=client.itfConnection,pData:=ADR(chunk),udiSize:=${wireBytes - 1});
|
|
594
|
+
IF reader.xError THEN ${port("error")}:=${jobError.network};stage:=90;
|
|
595
|
+
ELSIF reader.xReady AND reader.udiCount>0 THEN
|
|
596
|
+
IF TO_UDINT(used)+reader.udiCount>${wireBytes - 1} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
|
|
597
|
+
ELSE
|
|
598
|
+
FOR index:=0 TO TO_UINT(reader.udiCount)-1 DO received[used+index]:=chunk[index];END_FOR;
|
|
599
|
+
used:=used+TO_UINT(reader.udiCount);received[used]:=0;
|
|
600
|
+
FindHeaders();
|
|
601
|
+
IF headerEnd=0 AND used>${headerBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;END_IF;
|
|
602
|
+
IF headerEnd>0 THEN
|
|
603
|
+
IF headerEnd>${headerBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
|
|
604
|
+
ELSE
|
|
605
|
+
ReadHeaders();
|
|
606
|
+
IF malformed OR contentLength<0 OR contentLength>${plcBufferBytes} THEN ${port("error")}:=${jobError.tooLarge};stage:=90;
|
|
607
|
+
ELSIF TO_DINT(used)>=TO_DINT(headerEnd)+3+contentLength THEN
|
|
608
|
+
IF status<200 OR status>=300 THEN ${port("error")}:=${httpErrors.base}+status;stage:=90;
|
|
609
|
+
ELSE
|
|
610
|
+
payload:='';IF contentLength>0 THEN FOR index:=0 TO TO_UINT(contentLength)-1 DO payload[index]:=received[headerEnd+3+index]; END_FOR;END_IF;payload[TO_UINT(contentLength)]:=0; ${decode}
|
|
611
|
+
stage:=90;
|
|
612
|
+
END_IF;
|
|
613
|
+
END_IF;
|
|
614
|
+
END_IF;
|
|
615
|
+
END_IF;
|
|
616
|
+
END_IF;
|
|
617
|
+
END_IF;
|
|
618
|
+
END_IF;
|
|
619
|
+
END_IF;
|
|
620
|
+
IF stage=90 THEN
|
|
621
|
+
${release}
|
|
622
|
+
${port("busy")}:=FALSE;${port("done")}:=TRUE;
|
|
623
|
+
END_IF;
|
|
624
|
+
`,
|
|
625
|
+
};
|
|
626
|
+
// CODESYS calls FB_exit before a download, reset or application stop discards the instance, and
|
|
627
|
+
// with bInCopyCode before an online change copies it. A connection still open then keeps the
|
|
628
|
+
// Net Base Services task in a socket call, and the runtime can't delete the old application's
|
|
629
|
+
// tasks until it restarts. A request this interrupts completes as a network error rather than
|
|
630
|
+
// being sent again, since tsPLC never repeats a remote side effect.
|
|
631
|
+
const exit: GeneratedObject = {
|
|
632
|
+
id: `${id}:FB_exit`,
|
|
633
|
+
parent: id,
|
|
634
|
+
kind: "method",
|
|
635
|
+
name: "FB_exit",
|
|
636
|
+
declaration:
|
|
637
|
+
"METHOD PUBLIC FB_exit : BOOL\nVAR_INPUT\n bInCopyCode : BOOL;\nEND_VAR",
|
|
638
|
+
implementation: `IF stage>0 AND stage<90 THEN ${port("error")}:=${jobError.network};stage:=90;END_IF;
|
|
639
|
+
${release}
|
|
640
|
+
FB_exit:=TRUE;`,
|
|
641
|
+
};
|
|
642
|
+
return [block, exit, ...tcpKeepAlive(id, name)];
|
|
643
|
+
};
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* TCP keep-alive for an HTTP client's connection, as an option provider the client applies to each socket it opens. A
|
|
647
|
+
* connection whose peer vanished without closing it, as when the server's PC drops off the network, otherwise stays active
|
|
648
|
+
* (Net Base Services' TCP_Client documentation), and a read on it holds the Net Base Services task every client shares,
|
|
649
|
+
* cutting the PLC off from its server, and a download then finds the task unable to stop. With keep-alive, such a
|
|
650
|
+
* connection fails within seconds and the task moves on. A live peer's TCP stack answers the probes however long its
|
|
651
|
+
* server takes to reply, so they never end a slow request.
|
|
652
|
+
*/
|
|
653
|
+
const tcpKeepAlive = (owner: string, name: string): GeneratedObject[] => {
|
|
654
|
+
const id = `${owner}:keepAlive`;
|
|
655
|
+
return [
|
|
656
|
+
{
|
|
657
|
+
id,
|
|
658
|
+
kind: "functionBlock",
|
|
659
|
+
name: `${name}_KeepAlive`,
|
|
660
|
+
// SysSocket Interfaces' RTS_SOCKET_SO_VALUE_TCP_KEEPALIVE, laid out as its seven 32-bit members: bOn, probes,
|
|
661
|
+
// probesResult, timeout (ms idle before the first probe), timeoutResult, interval (ms between probes),
|
|
662
|
+
// intervalResult. Three unanswered probes, the first after 2 s idle and a second apart, end it in 5 s.
|
|
663
|
+
declaration: `FUNCTION_BLOCK ${name}_KeepAlive IMPLEMENTS NBS.IOptionProvider
|
|
664
|
+
VAR
|
|
665
|
+
keepAlive : ARRAY[0..6] OF DINT := [1, ${keepAliveProbes}, 0, ${keepAliveIdleMs}, 0, ${keepAliveIntervalMs}, 0];
|
|
666
|
+
END_VAR`,
|
|
667
|
+
implementation: "",
|
|
668
|
+
},
|
|
669
|
+
{
|
|
670
|
+
id: `${id}:GetOptionCount`,
|
|
671
|
+
parent: id,
|
|
672
|
+
kind: "method",
|
|
673
|
+
name: "GetOptionCount",
|
|
674
|
+
declaration: `METHOD PUBLIC GetOptionCount : USINT
|
|
675
|
+
VAR_OUTPUT eErrorID : NBS.ERROR; END_VAR`,
|
|
676
|
+
implementation: "GetOptionCount:=1;eErrorID:=NBS.ERROR.NO_ERROR;",
|
|
677
|
+
},
|
|
678
|
+
{
|
|
679
|
+
id: `${id}:GetParams`,
|
|
680
|
+
parent: id,
|
|
681
|
+
kind: "method",
|
|
682
|
+
name: "GetParams",
|
|
683
|
+
declaration: `METHOD PUBLIC GetParams : NBS.ERROR
|
|
684
|
+
VAR_INPUT usiIndex : USINT; END_VAR
|
|
685
|
+
VAR_OUTPUT eOperation : NBS.OPERATION; optOption : NBS.OPTION; END_VAR`,
|
|
686
|
+
implementation: `eOperation:=NBS.OPERATION.SET_OPTION;
|
|
687
|
+
optOption.diLevel:=${socketLevel};
|
|
688
|
+
optOption.diOption:=${socketKeepAliveOption};
|
|
689
|
+
optOption.pdiOptionValue:=ADR(keepAlive);
|
|
690
|
+
optOption.udiOptionLen:=SIZEOF(keepAlive);
|
|
691
|
+
GetParams:=NBS.ERROR.NO_ERROR;`,
|
|
692
|
+
},
|
|
693
|
+
{
|
|
694
|
+
id: `${id}:SetResult`,
|
|
695
|
+
parent: id,
|
|
696
|
+
kind: "method",
|
|
697
|
+
name: "SetResult",
|
|
698
|
+
declaration: `METHOD PUBLIC SetResult : NBS.ERROR
|
|
699
|
+
VAR_INPUT usiIndex : USINT; udiResult : UDINT; END_VAR`,
|
|
700
|
+
// A platform without keep-alive leaves the connection as it was before: nothing to undo.
|
|
701
|
+
implementation: "SetResult:=NBS.ERROR.NO_ERROR;",
|
|
702
|
+
},
|
|
703
|
+
];
|
|
704
|
+
};
|
|
705
|
+
|
|
706
|
+
export const httpCertificateVerifier = (
|
|
707
|
+
owner: string,
|
|
708
|
+
name: string,
|
|
709
|
+
endpoint: NativeEndpoint,
|
|
710
|
+
): GeneratedObject[] => {
|
|
711
|
+
if (!endpoint.tls) {
|
|
712
|
+
return [];
|
|
713
|
+
}
|
|
714
|
+
const id = `${owner}:certificateVerifier`;
|
|
715
|
+
// NBS represents certificate handles as pointers; verification keeps the native trust result.
|
|
716
|
+
const ipv4 = /^\d+\.\d+\.\d+\.\d+$/.test(endpoint.host);
|
|
717
|
+
return [
|
|
718
|
+
{
|
|
719
|
+
id,
|
|
720
|
+
kind: "functionBlock",
|
|
721
|
+
name: `${name}_CertificateVerifier`,
|
|
722
|
+
declaration: `FUNCTION_BLOCK ${name}_CertificateVerifier IMPLEMENTS NBS.ICertificateVerifier
|
|
723
|
+
VAR
|
|
724
|
+
hostname:STRING(255):=${stStringLiteral(endpoint.host)};
|
|
725
|
+
${ipv4 ? `address:ARRAY[0..3] OF BYTE := [${endpoint.host.split(".").join(",")}];` : ""}
|
|
726
|
+
END_VAR`,
|
|
727
|
+
implementation: "",
|
|
728
|
+
},
|
|
729
|
+
{
|
|
730
|
+
id: `${id}:VerifyCertificate`,
|
|
731
|
+
parent: id,
|
|
732
|
+
kind: "method",
|
|
733
|
+
name: "VerifyCertificate",
|
|
734
|
+
declaration: `METHOD PUBLIC VerifyCertificate : UDINT
|
|
735
|
+
VAR_INPUT hCert:POINTER TO BYTE;eCurState:UDINT;END_VAR
|
|
736
|
+
VAR matched:BOOL;result:UDINT;END_VAR`,
|
|
737
|
+
implementation: `VerifyCertificate:=eCurState;
|
|
738
|
+
IF eCurState<>0 THEN RETURN;END_IF;
|
|
739
|
+
matched:=CmpX509Cert_Implementation.${ipv4 ? "X509CertCheckIP(hCert,ADR(address),0,ADR(result))" : "X509CertCheckHost(hCert,ADR(hostname),4,ADR(result))"};
|
|
740
|
+
IF result<>0 THEN VerifyCertificate:=result;ELSIF NOT matched THEN VerifyCertificate:=1;END_IF;`,
|
|
741
|
+
},
|
|
742
|
+
];
|
|
743
|
+
};
|
|
744
|
+
|
|
745
|
+
const privateMethod = (
|
|
746
|
+
owner: string,
|
|
747
|
+
name: string,
|
|
748
|
+
declaration: string,
|
|
749
|
+
implementation: string,
|
|
750
|
+
result?: string,
|
|
751
|
+
): GeneratedObject => ({
|
|
752
|
+
id: `${owner}:${name}`,
|
|
753
|
+
parent: owner,
|
|
754
|
+
kind: "method",
|
|
755
|
+
name,
|
|
756
|
+
declaration: `METHOD PRIVATE ${name}${result ? ` : ${result}` : ""}\n${declaration}`,
|
|
757
|
+
implementation,
|
|
758
|
+
});
|
|
759
|
+
|
|
760
|
+
// Standard string helpers accept STRING(255); native buffers must retain their full byte length.
|
|
761
|
+
const byteLengthMethod = (owner: string) =>
|
|
762
|
+
privateMethod(
|
|
763
|
+
owner,
|
|
764
|
+
"ByteLength",
|
|
765
|
+
`VAR_INPUT value:STRING(${wireBytes});END_VAR\nVAR i:UINT;END_VAR`,
|
|
766
|
+
`ByteLength:=0;FOR i:=0 TO ${wireBytes - 1} DO IF value[i]=0 THEN ByteLength:=i;RETURN;END_IF;END_FOR;ByteLength:=${wireBytes};`,
|
|
767
|
+
"UINT",
|
|
768
|
+
);
|
|
769
|
+
|
|
770
|
+
const appendMethod = (owner: string) =>
|
|
771
|
+
privateMethod(
|
|
772
|
+
owner,
|
|
773
|
+
"Append",
|
|
774
|
+
`VAR_INPUT value : STRING(${plcBufferBytes}); END_VAR\nVAR offset:UINT;i:UINT;END_VAR`,
|
|
775
|
+
`offset:=TO_UINT(ByteLength(payload));IF offset+TO_UINT(ByteLength(value))>${plcBufferBytes} THEN malformed:=TRUE; ELSE IF ByteLength(value)>0 THEN FOR i:=0 TO TO_UINT(ByteLength(value))-1 DO payload[offset+i]:=value[i];END_FOR;END_IF;payload[offset+TO_UINT(ByteLength(value))]:=0;END_IF;`,
|
|
776
|
+
);
|
|
777
|
+
|
|
778
|
+
const appendWireMethod = (owner: string) =>
|
|
779
|
+
privateMethod(
|
|
780
|
+
owner,
|
|
781
|
+
"AppendWire",
|
|
782
|
+
`VAR_INPUT value:STRING(${wireBytes});END_VAR\nVAR i:UINT;END_VAR`,
|
|
783
|
+
`IF wireUsed+TO_UINT(ByteLength(value))>${wireBytes - 1} THEN malformed:=TRUE;RETURN;END_IF;IF ByteLength(value)>0 THEN FOR i:=0 TO TO_UINT(ByteLength(value))-1 DO wire[wireUsed+i]:=value[i];END_FOR;END_IF;wireUsed:=wireUsed+TO_UINT(ByteLength(value));wire[wireUsed]:=0;`,
|
|
784
|
+
);
|
|
785
|
+
|
|
786
|
+
const findHeadersMethod = (owner: string) =>
|
|
787
|
+
privateMethod(
|
|
788
|
+
owner,
|
|
789
|
+
"FindHeaders",
|
|
790
|
+
"VAR i:UINT;END_VAR",
|
|
791
|
+
`headerEnd:=0;IF used<4 THEN RETURN;END_IF;
|
|
792
|
+
FOR i:=0 TO used-4 DO IF received[i]=13 AND received[i+1]=10 AND received[i+2]=13 AND received[i+3]=10 THEN headerEnd:=i+1;RETURN;END_IF;END_FOR;`,
|
|
793
|
+
);
|
|
794
|
+
|
|
795
|
+
const matchLiteralMethod = (owner: string) =>
|
|
796
|
+
privateMethod(
|
|
797
|
+
owner,
|
|
798
|
+
"MatchLiteral",
|
|
799
|
+
"VAR_INPUT value:STRING(8);END_VAR\nVAR i:UINT;size:UINT;END_VAR",
|
|
800
|
+
`MatchLiteral:=FALSE;size:=TO_UINT(ByteLength(value));IF cursor+size-1>TO_UINT(ByteLength(payload)) THEN RETURN;END_IF;
|
|
801
|
+
FOR i:=0 TO size-1 DO IF payload[cursor-1+i]<>value[i] THEN RETURN;END_IF;END_FOR;cursor:=cursor+size;MatchLiteral:=TRUE;`,
|
|
802
|
+
"BOOL",
|
|
803
|
+
);
|
|
804
|
+
|
|
805
|
+
const readHeadersMethod = (owner: string) =>
|
|
806
|
+
privateMethod(
|
|
807
|
+
owner,
|
|
808
|
+
"ReadHeaders",
|
|
809
|
+
`VAR lineStart:UINT;lineEnd:UINT;i:UINT;j:UINT;key:STRING(64);octet:BYTE;found:BOOL;digits:UINT;END_VAR`,
|
|
810
|
+
`malformed:=FALSE;found:=FALSE;contentLength:=-1;
|
|
811
|
+
IF LEFT(received,9)<>'HTTP/1.1 ' AND LEFT(received,9)<>'HTTP/1.0 ' THEN malformed:=TRUE;RETURN;END_IF;
|
|
812
|
+
status:=0;FOR i:=9 TO 11 DO IF received[i]<48 OR received[i]>57 THEN malformed:=TRUE;RETURN;END_IF;status:=status*10+TO_UINT(received[i]-48);END_FOR;
|
|
813
|
+
lineStart:=1;
|
|
814
|
+
WHILE lineStart<headerEnd DO
|
|
815
|
+
lineEnd:=lineStart;WHILE lineEnd<headerEnd AND received[lineEnd-1]<>13 DO lineEnd:=lineEnd+1;END_WHILE;
|
|
816
|
+
key:='';j:=0;i:=lineStart;
|
|
817
|
+
WHILE i<lineEnd AND received[i-1]<>58 AND j<63 DO octet:=received[i-1];IF octet>=65 AND octet<=90 THEN octet:=octet+32;END_IF;key[j]:=octet;j:=j+1;i:=i+1;END_WHILE;key[j]:=0;
|
|
818
|
+
IF key='transfer-encoding' THEN malformed:=TRUE;RETURN;END_IF;
|
|
819
|
+
IF key='content-length' THEN
|
|
820
|
+
IF found THEN malformed:=TRUE;RETURN;END_IF;found:=TRUE;contentLength:=0;digits:=0;i:=i+1;
|
|
821
|
+
WHILE i<lineEnd AND received[i-1]=32 DO i:=i+1;END_WHILE;
|
|
822
|
+
WHILE i<lineEnd DO octet:=received[i-1];IF octet<48 OR octet>57 OR digits>=5 THEN malformed:=TRUE;RETURN;END_IF;contentLength:=contentLength*10+TO_DINT(octet-48);digits:=digits+1;i:=i+1;END_WHILE;
|
|
823
|
+
IF digits=0 THEN malformed:=TRUE;RETURN;END_IF;
|
|
824
|
+
END_IF;
|
|
825
|
+
lineStart:=lineEnd+2;
|
|
826
|
+
END_WHILE;`,
|
|
827
|
+
);
|
|
828
|
+
|
|
829
|
+
const writeStringMethod = (owner: string) =>
|
|
830
|
+
privateMethod(
|
|
831
|
+
owner,
|
|
832
|
+
"WriteString",
|
|
833
|
+
`VAR_INPUT value : STRING(${plcBufferBytes}); END_VAR\nVAR i:UINT; one:STRING(1); hex:STRING(16):='0123456789abcdef'; END_VAR`,
|
|
834
|
+
`Append('"');IF ByteLength(value)>0 THEN FOR i:=0 TO ByteLength(value)-1 DO
|
|
835
|
+
one[0]:=value[i];one[1]:=0;
|
|
836
|
+
IF value[i]=34 OR value[i]=92 THEN Append('\\');Append(one);
|
|
837
|
+
ELSIF value[i]<32 THEN Append('\\u00');one[0]:=hex[SHR(value[i],4)];Append(one);one[0]:=hex[value[i] AND 15];Append(one);
|
|
838
|
+
ELSE Append(one);END_IF;
|
|
839
|
+
END_FOR;END_IF;Append('"');`,
|
|
840
|
+
);
|
|
841
|
+
|
|
842
|
+
const skipWhitespaceMethod = (owner: string) =>
|
|
843
|
+
privateMethod(
|
|
844
|
+
owner,
|
|
845
|
+
"SkipWhitespace",
|
|
846
|
+
"",
|
|
847
|
+
`WHILE cursor<=TO_UINT(ByteLength(payload)) DO IF payload[cursor-1]<>32 AND payload[cursor-1]<>9 AND payload[cursor-1]<>10 AND payload[cursor-1]<>13 THEN EXIT;END_IF;cursor:=cursor+1;END_WHILE;`,
|
|
848
|
+
);
|
|
849
|
+
|
|
850
|
+
const expectMethod = (owner: string) =>
|
|
851
|
+
privateMethod(
|
|
852
|
+
owner,
|
|
853
|
+
"Expect",
|
|
854
|
+
"VAR_INPUT value:BYTE; END_VAR",
|
|
855
|
+
`IF cursor>TO_UINT(ByteLength(payload)) OR_ELSE payload[cursor-1]<>value THEN malformed:=TRUE;ELSE cursor:=cursor+1;END_IF;`,
|
|
856
|
+
);
|
|
857
|
+
|
|
858
|
+
const tokenByteMethod = (owner: string) =>
|
|
859
|
+
privateMethod(
|
|
860
|
+
owner,
|
|
861
|
+
"TokenByte",
|
|
862
|
+
"VAR_INPUT value:BYTE;END_VAR",
|
|
863
|
+
`IF tokenUsed>=${plcBufferBytes} OR value=0 THEN malformed:=TRUE;RETURN;END_IF;token[tokenUsed]:=value;tokenUsed:=tokenUsed+1;token[tokenUsed]:=0;`,
|
|
864
|
+
);
|
|
865
|
+
|
|
866
|
+
const readHexMethod = (owner: string) =>
|
|
867
|
+
privateMethod(
|
|
868
|
+
owner,
|
|
869
|
+
"ReadHex",
|
|
870
|
+
"VAR value:UDINT;i:UINT;octet:BYTE;END_VAR",
|
|
871
|
+
`numberValue:=0;FOR i:=1 TO 4 DO
|
|
872
|
+
IF cursor>TO_UINT(ByteLength(payload)) THEN malformed:=TRUE;RETURN;END_IF;
|
|
873
|
+
octet:=payload[cursor-1];cursor:=cursor+1;
|
|
874
|
+
IF octet>=48 AND octet<=57 THEN value:=TO_UDINT(octet-48);ELSIF octet>=65 AND octet<=70 THEN value:=TO_UDINT(octet-55);ELSIF octet>=97 AND octet<=102 THEN value:=TO_UDINT(octet-87);ELSE malformed:=TRUE;RETURN;END_IF;
|
|
875
|
+
numberValue:=numberValue*16+TO_LINT(value);END_FOR;`,
|
|
876
|
+
);
|
|
877
|
+
|
|
878
|
+
const readStringMethod = (owner: string) =>
|
|
879
|
+
privateMethod(
|
|
880
|
+
owner,
|
|
881
|
+
"ReadString",
|
|
882
|
+
`VAR octet:BYTE;point:UDINT;high:UDINT;END_VAR`,
|
|
883
|
+
`token:='';tokenUsed:=0;Expect(34);
|
|
884
|
+
WHILE cursor<=TO_UINT(ByteLength(payload)) AND NOT malformed DO
|
|
885
|
+
octet:=payload[cursor-1];cursor:=cursor+1;
|
|
886
|
+
IF octet=34 THEN ValidateUtf8();RETURN;END_IF;
|
|
887
|
+
IF octet=92 THEN
|
|
888
|
+
IF cursor>TO_UINT(ByteLength(payload)) THEN malformed:=TRUE;RETURN;END_IF;
|
|
889
|
+
octet:=payload[cursor-1];cursor:=cursor+1;
|
|
890
|
+
CASE octet OF
|
|
891
|
+
34,47,92: TokenByte(octet);
|
|
892
|
+
98:TokenByte(8);102:TokenByte(12);110:TokenByte(10);114:TokenByte(13);116:TokenByte(9);
|
|
893
|
+
117:
|
|
894
|
+
ReadHex();point:=TO_UDINT(numberValue);
|
|
895
|
+
IF point>=55296 AND point<=56319 THEN
|
|
896
|
+
high:=point;Expect(92);Expect(117);ReadHex();
|
|
897
|
+
IF numberValue<56320 OR numberValue>57343 THEN malformed:=TRUE;RETURN;END_IF;
|
|
898
|
+
point:=65536+(high-55296)*1024+TO_UDINT(numberValue)-56320;
|
|
899
|
+
ELSIF point>=56320 AND point<=57343 THEN malformed:=TRUE;RETURN;END_IF;
|
|
900
|
+
IF point<128 THEN TokenByte(TO_BYTE(point));
|
|
901
|
+
ELSIF point<2048 THEN TokenByte(TO_BYTE(192+SHR(point,6)));TokenByte(TO_BYTE(128+(point AND 63)));
|
|
902
|
+
ELSIF point<65536 THEN TokenByte(TO_BYTE(224+SHR(point,12)));TokenByte(TO_BYTE(128+(SHR(point,6) AND 63)));TokenByte(TO_BYTE(128+(point AND 63)));
|
|
903
|
+
ELSE TokenByte(TO_BYTE(240+SHR(point,18)));TokenByte(TO_BYTE(128+(SHR(point,12) AND 63)));TokenByte(TO_BYTE(128+(SHR(point,6) AND 63)));TokenByte(TO_BYTE(128+(point AND 63)));END_IF;
|
|
904
|
+
ELSE malformed:=TRUE;RETURN;
|
|
905
|
+
END_CASE;
|
|
906
|
+
ELSIF octet<32 THEN malformed:=TRUE;RETURN;ELSE TokenByte(octet);END_IF;
|
|
907
|
+
END_WHILE;malformed:=TRUE;`,
|
|
908
|
+
);
|
|
909
|
+
|
|
910
|
+
const validateUtf8Method = (owner: string) =>
|
|
911
|
+
privateMethod(
|
|
912
|
+
owner,
|
|
913
|
+
"ValidateUtf8",
|
|
914
|
+
"VAR i:UINT;j:UINT;count:UINT;first:BYTE;next:BYTE;END_VAR",
|
|
915
|
+
`i:=0;
|
|
916
|
+
WHILE i<tokenUsed AND NOT malformed DO
|
|
917
|
+
first:=token[i];
|
|
918
|
+
IF first<128 THEN i:=i+1;
|
|
919
|
+
ELSE
|
|
920
|
+
IF first>=194 AND first<=223 THEN count:=1;ELSIF first>=224 AND first<=239 THEN count:=2;ELSIF first>=240 AND first<=244 THEN count:=3;ELSE malformed:=TRUE;RETURN;END_IF;
|
|
921
|
+
IF i+count>=tokenUsed THEN malformed:=TRUE;RETURN;END_IF;
|
|
922
|
+
next:=token[i+1];
|
|
923
|
+
IF (first=224 AND next<160) OR (first=237 AND next>=160) OR (first=240 AND next<144) OR (first=244 AND next>=144) THEN malformed:=TRUE;RETURN;END_IF;
|
|
924
|
+
FOR j:=1 TO count DO IF token[i+j]<128 OR token[i+j]>191 THEN malformed:=TRUE;RETURN;END_IF;END_FOR;
|
|
925
|
+
i:=i+count+1;
|
|
926
|
+
END_IF;
|
|
927
|
+
END_WHILE;`,
|
|
928
|
+
);
|
|
929
|
+
|
|
930
|
+
const readIntegerMethod = (owner: string) =>
|
|
931
|
+
privateMethod(
|
|
932
|
+
owner,
|
|
933
|
+
"ReadInteger",
|
|
934
|
+
"VAR negative:BOOL;digits:UINT;octet:BYTE;END_VAR",
|
|
935
|
+
`numberValue:=0;negative:=FALSE;digits:=0;
|
|
936
|
+
IF payload[cursor-1]=45 THEN negative:=TRUE;cursor:=cursor+1;END_IF;
|
|
937
|
+
WHILE cursor<=TO_UINT(ByteLength(payload)) DO
|
|
938
|
+
octet:=payload[cursor-1];IF octet<48 OR octet>57 THEN EXIT;END_IF;
|
|
939
|
+
IF digits>=10 THEN malformed:=TRUE;RETURN;END_IF;
|
|
940
|
+
IF digits>0 AND numberValue=0 THEN malformed:=TRUE;RETURN;END_IF;numberValue:=numberValue*10+TO_LINT(octet-48);digits:=digits+1;cursor:=cursor+1;
|
|
941
|
+
END_WHILE;
|
|
942
|
+
IF digits=0 THEN malformed:=TRUE;END_IF;IF negative THEN numberValue:=-numberValue;END_IF;`,
|
|
943
|
+
);
|
|
944
|
+
|
|
945
|
+
/** What the telemetry writer appends its records with. */
|
|
946
|
+
export const jsonEncoders = (owner: string): GeneratedObject[] => [
|
|
947
|
+
byteLengthMethod(owner),
|
|
948
|
+
appendMethod(owner),
|
|
949
|
+
writeStringMethod(owner),
|
|
950
|
+
];
|
|
951
|
+
|
|
952
|
+
const jsonDecoders = (owner: string): GeneratedObject[] => [
|
|
953
|
+
skipWhitespaceMethod(owner),
|
|
954
|
+
expectMethod(owner),
|
|
955
|
+
tokenByteMethod(owner),
|
|
956
|
+
readHexMethod(owner),
|
|
957
|
+
readStringMethod(owner),
|
|
958
|
+
validateUtf8Method(owner),
|
|
959
|
+
readIntegerMethod(owner),
|
|
960
|
+
];
|
|
961
|
+
|
|
962
|
+
/** The methods of a native HTTP client: the JSON codec's and those that frame its request and read the response's headers. */
|
|
963
|
+
export const httpClientMethods = (owner: string): GeneratedObject[] => [
|
|
964
|
+
byteLengthMethod(owner),
|
|
965
|
+
appendMethod(owner),
|
|
966
|
+
appendWireMethod(owner),
|
|
967
|
+
findHeadersMethod(owner),
|
|
968
|
+
matchLiteralMethod(owner),
|
|
969
|
+
readHeadersMethod(owner),
|
|
970
|
+
writeStringMethod(owner),
|
|
971
|
+
...jsonDecoders(owner),
|
|
972
|
+
];
|
|
973
|
+
|
|
974
|
+
/** The methods of an OPC UA client: the JSON codec's. */
|
|
975
|
+
export const opcuaClientMethods = (owner: string): GeneratedObject[] => [
|
|
976
|
+
byteLengthMethod(owner),
|
|
977
|
+
appendMethod(owner),
|
|
978
|
+
matchLiteralMethod(owner),
|
|
979
|
+
writeStringMethod(owner),
|
|
980
|
+
...jsonDecoders(owner),
|
|
981
|
+
];
|
|
982
|
+
|
|
983
|
+
type ServiceRuntime = Extract<
|
|
984
|
+
NonNullable<FunctionBlock["runtime"]>,
|
|
985
|
+
{ kind: "http" | "rpc" }
|
|
986
|
+
>;
|
|
987
|
+
|
|
988
|
+
/** A block that calls a service: its body is the request state machine `emitServiceBlock` writes. */
|
|
989
|
+
export const serviceBlock = <Block extends Pick<FunctionBlock, "runtime">>(
|
|
990
|
+
block: Block,
|
|
991
|
+
): block is Block & { runtime: ServiceRuntime } =>
|
|
992
|
+
block.runtime?.kind === "http" || block.runtime?.kind === "rpc";
|
|
993
|
+
|
|
994
|
+
/** A service-call block: its HTTP or OPC UA client, the client's methods and, over OPC UA, its slots' global list. */
|
|
995
|
+
export function emitServiceBlock(
|
|
996
|
+
{ plan, symbols, instrumentation }: EmissionContext,
|
|
997
|
+
networkName: string | undefined,
|
|
998
|
+
fn: CoreFunctionBlock,
|
|
999
|
+
): { objects: GeneratedObject[]; rpcChannels: ServiceChannel[] } {
|
|
1000
|
+
const endpoint = required(plan.http[fn.id]);
|
|
1001
|
+
const name = required(symbols.blockNames.get(fn.id));
|
|
1002
|
+
const runtime = fn.runtime;
|
|
1003
|
+
const codecs = serviceCodecs(
|
|
1004
|
+
fn,
|
|
1005
|
+
required(symbols.blockFields.get(fn.id)),
|
|
1006
|
+
symbols.typeMap,
|
|
1007
|
+
symbols.targetTypes,
|
|
1008
|
+
);
|
|
1009
|
+
if (endpoint.transport === "opcua") {
|
|
1010
|
+
const slots = rpcSlots(symbols, fn.id, name, endpoint.path);
|
|
1011
|
+
return {
|
|
1012
|
+
objects: [
|
|
1013
|
+
slots.list,
|
|
1014
|
+
opcuaClient({
|
|
1015
|
+
id: fn.id,
|
|
1016
|
+
name,
|
|
1017
|
+
ports: `VAR_INPUT ${codecs.inputs} END_VAR\nVAR_OUTPUT ${codecs.outputs} END_VAR`,
|
|
1018
|
+
port: codecs.port,
|
|
1019
|
+
timeoutMs: endpoint.timeoutMs,
|
|
1020
|
+
rpcGlobal: slots.list.name,
|
|
1021
|
+
body: `Append('{');${codecs.requestCode}Append('}');`,
|
|
1022
|
+
decode: codecs.decodeResponse,
|
|
1023
|
+
}),
|
|
1024
|
+
...opcuaClientMethods(fn.id),
|
|
1025
|
+
],
|
|
1026
|
+
rpcChannels: slots.channels,
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
if (runtime?.kind !== "http") {
|
|
1030
|
+
throw new Error(`Service block ${fn.id} has no HTTP runtime.`);
|
|
1031
|
+
}
|
|
1032
|
+
const requestFields = instrumentation.fields.get(fn.id);
|
|
1033
|
+
return {
|
|
1034
|
+
objects: [
|
|
1035
|
+
...httpServiceBlock(
|
|
1036
|
+
fn.id,
|
|
1037
|
+
runtime,
|
|
1038
|
+
name,
|
|
1039
|
+
codecs,
|
|
1040
|
+
endpoint,
|
|
1041
|
+
`${required(networkName)}.network`,
|
|
1042
|
+
requestFields?.job && requestFields.sequence
|
|
1043
|
+
? { job: requestFields.job, sequence: requestFields.sequence }
|
|
1044
|
+
: undefined,
|
|
1045
|
+
),
|
|
1046
|
+
...httpClientMethods(fn.id),
|
|
1047
|
+
...httpCertificateVerifier(fn.id, name, endpoint),
|
|
1048
|
+
],
|
|
1049
|
+
rpcChannels: [],
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
/** The endpoints the program's HTTP clients call: its service blocks' and the telemetry sender's. */
|
|
1054
|
+
const nativeEndpoints = ({ http, telemetry }: CodesysPlan): NativeEndpoint[] =>
|
|
1055
|
+
[...Object.values(http), ...(telemetry ? [telemetry.endpoint] : [])].filter(
|
|
1056
|
+
(endpoint) => endpoint.transport === "http",
|
|
1057
|
+
);
|
|
1058
|
+
|
|
1059
|
+
/** The libraries the program's HTTP clients reference, beyond what the project template does. */
|
|
1060
|
+
export function httpLibraryReferences(plan: CodesysPlan): string[] {
|
|
1061
|
+
const endpoints = nativeEndpoints(plan);
|
|
1062
|
+
return [
|
|
1063
|
+
...(endpoints.length ? ["Net Base Services, 4.0.0.0 (CODESYS)"] : []),
|
|
1064
|
+
...(endpoints.some((endpoint) => endpoint.tls)
|
|
1065
|
+
? ["CmpX509Cert Implementation, 3.5.22.0 (System)"]
|
|
1066
|
+
: []),
|
|
1067
|
+
];
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
/** `GVL_TsplcNetwork`, the Net Base Services task every HTTP client runs on, when one does. */
|
|
1071
|
+
export function httpNetwork(
|
|
1072
|
+
plan: CodesysPlan,
|
|
1073
|
+
symbols: GlobalSymbols,
|
|
1074
|
+
): GeneratedObject | undefined {
|
|
1075
|
+
if (!nativeEndpoints(plan).length) {
|
|
1076
|
+
return undefined;
|
|
1077
|
+
}
|
|
1078
|
+
return {
|
|
1079
|
+
id: "runtime:httpNetwork",
|
|
1080
|
+
kind: "globalList",
|
|
1081
|
+
name: symbols.names.allocateObject("GVL", "TsplcNetwork"),
|
|
1082
|
+
// Blocks in other global lists take this in their initializers, so it must initialize first.
|
|
1083
|
+
declaration: `{attribute 'qualified_only'}
|
|
1084
|
+
{attribute 'global_init_slot' := '40000'}
|
|
1085
|
+
VAR_GLOBAL
|
|
1086
|
+
network:NBS.AsyncProperty := (usiTaskPrio:=15,udiTaskInterval:=1000,tnTaskName:='tsPLC HTTP');
|
|
1087
|
+
END_VAR
|
|
1088
|
+
`,
|
|
1089
|
+
};
|
|
1090
|
+
}
|