@tsplc/compiler 0.2.17 → 0.2.19

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.
Files changed (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
@@ -0,0 +1,890 @@
1
+ import type {
2
+ CoreFunctionBlock,
3
+ GeneratedObject,
4
+ PlcType,
5
+ } from "@tsplc/compiler/ir";
6
+ import { type Environment, type HttpOptions, secretValue } from "@tsplc/config";
7
+ import { elementaryType, integerRange } from "@tsplc/iec";
8
+ import { plcBufferBytes } from "@tsplc/server/wire";
9
+ import type { CodesysPlan } from "./plan.ts";
10
+ import {
11
+ type CodesysSymbols,
12
+ type EmissionContext,
13
+ instrumentationFieldTypes,
14
+ required,
15
+ } from "./symbols.ts";
16
+ import { type CodesysTypes, stStringLiteral } from "./types.ts";
17
+
18
+ const opcuaServiceCapacity = 16;
19
+
20
+ export interface HttpEndpoint {
21
+ transport?: "http" | "opcua";
22
+ host: string;
23
+ port: number;
24
+ authority: string;
25
+ path: string;
26
+ token: string;
27
+ timeoutMs: number;
28
+ tls: boolean;
29
+ }
30
+ export const resolveHttpEndpoint = (
31
+ value: string,
32
+ input: HttpOptions,
33
+ env: Environment,
34
+ ): HttpEndpoint => {
35
+ const url = new URL(value);
36
+ if (
37
+ !["http:", "https:"].includes(url.protocol) ||
38
+ url.username ||
39
+ url.password ||
40
+ url.hash ||
41
+ url.hostname.includes(":")
42
+ ) {
43
+ throw new Error(
44
+ "fetch requires an HTTP(S) URL with an IPv4 address or DNS hostname, without credentials or fragment.",
45
+ );
46
+ }
47
+ if (
48
+ (url.pathname + url.search).length > 2048 ||
49
+ url.hostname.length > 253 ||
50
+ Number(url.port || (url.protocol === "https:" ? 443 : 80)) === 0
51
+ ) {
52
+ throw new Error(
53
+ "HTTP URL exceeds the native host/path limits or has an invalid port.",
54
+ );
55
+ }
56
+ let token = "";
57
+ const origins = new Set<string>();
58
+ for (const credential of input.credentials) {
59
+ const configured = env[credential.originEnv];
60
+ const secret = env[credential.bearerTokenEnv];
61
+ if (!configured || !secret) {
62
+ throw new Error(
63
+ `HTTP credentials require ${credential.originEnv} and ${credential.bearerTokenEnv}.`,
64
+ );
65
+ }
66
+ const origin = new URL(configured);
67
+ if (
68
+ !["http:", "https:"].includes(origin.protocol) ||
69
+ origin.username ||
70
+ origin.password ||
71
+ origin.pathname !== "/" ||
72
+ origin.search ||
73
+ origin.hash
74
+ ) {
75
+ throw new Error(
76
+ `HTTP credential origin ${credential.originEnv} must contain only a scheme, host and port.`,
77
+ );
78
+ }
79
+ if (origins.has(origin.origin)) {
80
+ throw new Error("HTTP credential origins must be unique.");
81
+ }
82
+ origins.add(origin.origin);
83
+ if (!secretValue.safeParse(secret).success) {
84
+ throw new Error(`Invalid bearer token in ${credential.bearerTokenEnv}.`);
85
+ }
86
+ if (origin.origin === url.origin) {
87
+ token = secret;
88
+ }
89
+ }
90
+ return {
91
+ host: url.hostname,
92
+ port: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
93
+ authority: url.host,
94
+ path: url.pathname + url.search,
95
+ token,
96
+ timeoutMs: input.timeoutMs,
97
+ tls: url.protocol === "https:",
98
+ };
99
+ };
100
+ /** The most characters an integer prints as in decimal, its sign included. */
101
+ const decimalLength = (layout: Parameters<typeof integerRange>[0]) =>
102
+ Math.max(...integerRange(layout).map((bound) => String(bound).length));
103
+
104
+ /**
105
+ * The ST that appends a BOOL, integer, bit string or UTF-8 STRING `value` as JSON with the
106
+ * encoder methods of `httpMethods`, and the most bytes it can append.
107
+ */
108
+ export const jsonScalar = (
109
+ type: PlcType,
110
+ value: string,
111
+ ): { code: string; size: number } | undefined => {
112
+ if (
113
+ type.kind === "string" &&
114
+ type.encoding === "utf8" &&
115
+ type.capacity <= plcBufferBytes
116
+ ) {
117
+ return { code: `WriteString(${value});`, size: type.capacity * 6 + 2 };
118
+ }
119
+ if (type.kind === "bool") {
120
+ return {
121
+ code: `IF ${value} THEN Append('true'); ELSE Append('false'); END_IF;`,
122
+ size: 5,
123
+ };
124
+ }
125
+ if (type.kind === "bits") {
126
+ const wide = type.bits <= 32 ? "UDINT" : "ULINT";
127
+ return {
128
+ code: `Append(${wide}_TO_STRING(TO_${wide}(${value})));`,
129
+ size: decimalLength({ bits: type.bits, signed: false }),
130
+ };
131
+ }
132
+ if (type.kind === "integer") {
133
+ return {
134
+ code: `Append(${type.id}_TO_STRING(${value}));`,
135
+ size: decimalLength(type),
136
+ };
137
+ }
138
+ return undefined;
139
+ };
140
+
141
+ const httpLayouts = (
142
+ block: CoreFunctionBlock,
143
+ types: ReadonlyMap<string, PlcType>,
144
+ ) => {
145
+ const request = block.inputs.find((v) => v.name === "request");
146
+ const response = block.outputs.find((v) => v.name === "result");
147
+ if (!request || !response) {
148
+ throw new Error("Missing HTTP record ports.");
149
+ }
150
+ const requestLayout = types.get(request.type);
151
+ const responseLayout = types.get(response.type);
152
+ if (
153
+ requestLayout?.kind !== "record" ||
154
+ responseLayout?.kind !== "record" ||
155
+ responseLayout.fields.length === 0 ||
156
+ responseLayout.fields.length > 31
157
+ ) {
158
+ throw new Error(
159
+ "HTTP requires closed request/response records with 1..31 response fields.",
160
+ );
161
+ }
162
+ const scalarSize = (id: string): number => {
163
+ const type = types.get(id);
164
+ if (type?.kind === "enum") {
165
+ return Math.max(...type.members.map((member) => member.value.length));
166
+ }
167
+ const scalar =
168
+ type &&
169
+ !((type.kind === "integer" || type.kind === "bits") && type.bits > 32)
170
+ ? jsonScalar(type, "")
171
+ : undefined;
172
+ if (!scalar) {
173
+ throw new Error(
174
+ "HTTP JSON supports bounded UTF-8 strings, BOOL, enums, and integers up to 32 bits.",
175
+ );
176
+ }
177
+ return scalar.size;
178
+ };
179
+ const recordSize = (record: typeof requestLayout, response: boolean) =>
180
+ 2 +
181
+ record.fields.reduce((size, field) => {
182
+ const type = types.get(field.type);
183
+ const valueSize =
184
+ type?.kind === "array" && !response
185
+ ? 2 + type.length * (scalarSize(type.element) + 1)
186
+ : scalarSize(field.type);
187
+ return size + field.name.length + 4 + valueSize;
188
+ }, 0);
189
+ if (
190
+ recordSize(requestLayout, false) > plcBufferBytes ||
191
+ recordSize(responseLayout, true) > plcBufferBytes
192
+ ) {
193
+ throw new Error(
194
+ `The worst-case HTTP JSON payload exceeds the native ${plcBufferBytes}-byte buffer; reduce record/string/array bounds.`,
195
+ );
196
+ }
197
+ return { request, response, requestLayout, responseLayout };
198
+ };
199
+ export const validateHttpLayout = (
200
+ block: CoreFunctionBlock,
201
+ types: ReadonlyMap<string, PlcType>,
202
+ ): void => {
203
+ httpLayouts(block, types);
204
+ };
205
+
206
+ /** The ST that reads a JSON integer into `assign`'s target, flagging one outside `range` as malformed. */
207
+ const readInteger = (range: readonly [bigint, bigint], assign: string) =>
208
+ `ReadInteger(); IF numberValue < ${range[0]} OR numberValue > ${range[1]} THEN malformed:=TRUE; ELSE ${assign} END_IF;`;
209
+
210
+ /** The ST that reads a response field's JSON value into `value`, flagging a malformed one. */
211
+ const decodeField = (
212
+ type: PlcType,
213
+ value: string,
214
+ target: CodesysTypes,
215
+ ): string => {
216
+ if (
217
+ type.kind === "string" &&
218
+ type.encoding === "utf8" &&
219
+ type.capacity <= plcBufferBytes
220
+ ) {
221
+ return `ReadString(); IF ByteLength(token) > ${type.capacity} THEN malformed := TRUE; ELSE ${value} := token; END_IF;`;
222
+ }
223
+ if (type.kind === "bool") {
224
+ return `IF MatchLiteral('true') THEN ${value}:=TRUE; ELSIF MatchLiteral('false') THEN ${value}:=FALSE; ELSE malformed:=TRUE;END_IF;`;
225
+ }
226
+ // A strict enum is read as its DINT base.
227
+ if (type.kind === "enum") {
228
+ return readInteger(
229
+ integerRange(elementaryType("DINT")),
230
+ `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;`,
231
+ );
232
+ }
233
+ if ((type.kind === "integer" || type.kind === "bits") && type.bits <= 32) {
234
+ return readInteger(
235
+ integerRange({
236
+ bits: type.bits,
237
+ signed: type.kind === "integer" && type.signed,
238
+ }),
239
+ `${value}:=TO_${target.name(type.id)}(numberValue);`,
240
+ );
241
+ }
242
+ throw new Error("HTTP responses currently require flat scalar records.");
243
+ };
244
+
245
+ /** A service block's typed JSON codecs and ports; no application protocol lives here. */
246
+ interface ServiceCodecs {
247
+ port: (label: string) => string;
248
+ /** Appends the request record's fields as JSON. */
249
+ requestCode: string;
250
+ /** Decodes the response record from `payload`, setting `error` to 4 when it is malformed. */
251
+ decodeResponse: string;
252
+ inputs: string;
253
+ outputs: string;
254
+ }
255
+
256
+ const serviceCodecs = (
257
+ block: CoreFunctionBlock,
258
+ fields: ReadonlyMap<string, string>,
259
+ types: ReadonlyMap<string, PlcType>,
260
+ target: CodesysTypes,
261
+ ): ServiceCodecs => {
262
+ const port = (label: string) => {
263
+ const variable = [...block.inputs, ...block.outputs].find(
264
+ (v) => v.name === label,
265
+ );
266
+ if (!variable) {
267
+ throw new Error("Missing HTTP port " + label);
268
+ }
269
+ return fields.get(variable.id)!;
270
+ };
271
+ const { request, response, requestLayout, responseLayout } = httpLayouts(
272
+ block,
273
+ types,
274
+ );
275
+ const encode = (typeId: string, value: string): string => {
276
+ const type = types.get(typeId)!;
277
+ if (type.kind === "array") {
278
+ return Array.from(
279
+ { length: type.length },
280
+ (_, i) =>
281
+ `${i ? "Append(',');" : ""}${encode(type.element, `${value}[${i + type.lowerBound}]`)}`,
282
+ ).join("\n");
283
+ }
284
+ if (type.kind === "enum") {
285
+ return `Append(DINT_TO_STRING(TO_DINT(${value})));`;
286
+ }
287
+ const scalar = jsonScalar(type, value);
288
+ if (scalar) {
289
+ return scalar.code;
290
+ }
291
+ throw new Error(
292
+ "HTTP JSON supports bounded UTF-8 strings, BOOL, enums, integers up to 32 bits and fixed arrays.",
293
+ );
294
+ };
295
+ const requestCode = requestLayout.fields
296
+ .map((field, i) => {
297
+ const type = types.get(field.type)!;
298
+ const value = `${port("request")}.${target.field(request.type, field.name)}`;
299
+ return `Append(${stStringLiteral((i ? "," : "") + '"' + field.name + '":')});${type.kind === "array" ? "Append('[');" : ""}${encode(field.type, value)}${type.kind === "array" ? "Append(']');" : ""}`;
300
+ })
301
+ .join("\n");
302
+ const responseCode = responseLayout.fields
303
+ .map((field, i) => {
304
+ const type = types.get(field.type)!;
305
+ const value = `${port("result")}.${target.field(response.type, field.name)}`;
306
+ const decode = decodeField(type, value, target);
307
+ 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}`;
308
+ })
309
+ .join("\n");
310
+ const inputs = block.inputs
311
+ .map((v) => `${fields.get(v.id)} : ${target.name(v.type)};`)
312
+ .join("\n");
313
+ const outputs = block.outputs
314
+ .map((v) => `${fields.get(v.id)} : ${target.name(v.type)};`)
315
+ .join("\n");
316
+ const decodeResponse = `cursor:=1;malformed:=FALSE;seen:=0;
317
+ SkipWhitespace();Expect(123);SkipWhitespace();
318
+ WHILE cursor<=TO_UINT(ByteLength(payload)) AND NOT malformed DO
319
+ IF payload[cursor-1]=125 THEN cursor:=cursor+1;EXIT;END_IF;
320
+ ReadString();part:=token;SkipWhitespace();Expect(58);SkipWhitespace();
321
+ ${responseCode} ELSE malformed:=TRUE;END_IF;
322
+ SkipWhitespace();
323
+ IF payload[cursor-1]=44 THEN cursor:=cursor+1;SkipWhitespace();IF payload[cursor-1]=125 THEN malformed:=TRUE;END_IF;
324
+ ELSIF payload[cursor-1]<>125 THEN malformed:=TRUE;END_IF;
325
+ END_WHILE;
326
+ SkipWhitespace();
327
+ IF malformed OR cursor<>TO_UINT(ByteLength(payload))+1 OR seen<>DWORD#${2 ** responseLayout.fields.length - 1} THEN ${port("error")}:=4;END_IF;`;
328
+ return { port, requestCode, decodeResponse, inputs, outputs };
329
+ };
330
+
331
+ /** An OPC UA service block: it exchanges its request and reply through a slot of `rpcGlobal`. */
332
+ const opcuaServiceBlock = (
333
+ block: CoreFunctionBlock,
334
+ name: string,
335
+ { port, requestCode, decodeResponse, inputs, outputs }: ServiceCodecs,
336
+ endpoint: HttpEndpoint,
337
+ rpcGlobal: string,
338
+ ): GeneratedObject => {
339
+ const channel = (field: string, index = "slotIndex") =>
340
+ `${rpcGlobal}.${field}[${index}]`;
341
+ return {
342
+ id: block.id,
343
+ kind: "functionBlock",
344
+ name,
345
+ declaration: `FUNCTION_BLOCK ${name}
346
+ VAR_INPUT ${inputs} END_VAR
347
+ VAR_OUTPUT ${outputs} END_VAR
348
+ VAR
349
+ timeout:TON;stage:UINT;slotIndex:UINT;candidate:UINT;
350
+ identity:STRING(64);epoch:STRING(32);prefix:STRING(80);
351
+ payload:STRING(${plcBufferBytes});token:STRING(${plcBufferBytes});part:STRING(${plcBufferBytes});
352
+ cursor:UINT;malformed:BOOL;seen:DWORD;numberValue:LINT;tokenUsed:UINT;
353
+ END_VAR`,
354
+ implementation: `IF NOT ${port("start")} OR ${port("cancel")} THEN
355
+ IF slotIndex>0 THEN ${channel("requestIds")}:='';${channel("requests")}:='';${channel("inUse")}:=0;END_IF;
356
+ slotIndex:=0;stage:=0;timeout(IN:=FALSE);${port("busy")}:=FALSE;${port("done")}:=FALSE;${port("error")}:=0;RETURN;
357
+ END_IF;
358
+ IF stage=0 THEN
359
+ FOR candidate:=1 TO ${opcuaServiceCapacity} DO
360
+ (* __COMPARE_AND_SWAP can fail spuriously on ARM64; retry while the slot reads free. *)
361
+ WHILE slotIndex=0 AND ${channel("epochs", "candidate")}<>'' AND ${channel("inUse", "candidate")}=0 DO
362
+ IF __COMPARE_AND_SWAP(ADR(${channel("inUse", "candidate")}),0,1) THEN slotIndex:=candidate;END_IF;
363
+ END_WHILE;
364
+ IF slotIndex>0 THEN EXIT;END_IF;
365
+ END_FOR;
366
+ IF slotIndex=0 THEN ${port("error")}:=7;stage:=90;
367
+ ELSE
368
+ ${channel("sequence")}:=${channel("sequence")}+1;
369
+ IF ${channel("sequence")}=0 THEN ${channel("epochs")}:='';${port("error")}:=5;stage:=90;
370
+ ELSE
371
+ epoch:=${channel("epochs")};identity:=CONCAT(CONCAT(epoch,':'),UDINT_TO_STRING(${channel("sequence")}));
372
+ prefix:=CONCAT(identity,'|');payload:='';malformed:=FALSE;
373
+ Append('{');${requestCode}Append('}');
374
+ IF malformed THEN ${port("error")}:=3;stage:=90;
375
+ ELSIF ByteLength(payload)+LEN(prefix)>${plcBufferBytes} THEN ${port("error")}:=3;stage:=90;
376
+ ELSE
377
+ FOR candidate:=0 TO LEN(prefix)-1 DO ${channel("requests")}[candidate]:=prefix[candidate];END_FOR;
378
+ FOR candidate:=0 TO ByteLength(payload)-1 DO ${channel("requests")}[candidate+LEN(prefix)]:=payload[candidate];END_FOR;
379
+ ${channel("requests")}[ByteLength(payload)+LEN(prefix)]:=0;${channel("requestIds")}:=identity;stage:=1;
380
+ END_IF;
381
+ END_IF;
382
+ END_IF;
383
+ END_IF;
384
+ timeout(IN:=stage<90,PT:=T#${endpoint.timeoutMs}ms);
385
+ IF timeout.Q THEN ${port("error")}:=2;stage:=90;END_IF;
386
+ IF stage=1 THEN
387
+ IF ${channel("epochs")}<>epoch THEN ${port("error")}:=5;stage:=90;
388
+ ELSIF ${channel("replyIds")}=identity AND_THEN LEFT(${channel("replies")},LEN(prefix))=prefix THEN
389
+ payload:='';cursor:=LEN(prefix);
390
+ IF ByteLength(${channel("replies")})<cursor+4 THEN ${port("error")}:=4;
391
+ ELSIF ${channel("replies")}[cursor]<>48 OR ${channel("replies")}[cursor+1]<>124 THEN ${port("error")}:=5;
392
+ ELSE
393
+ FOR candidate:=cursor+2 TO ByteLength(${channel("replies")})-1 DO payload[candidate-cursor-2]:=${channel("replies")}[candidate];END_FOR;
394
+ payload[ByteLength(${channel("replies")})-cursor-2]:=0;
395
+ ${decodeResponse}
396
+ END_IF;
397
+ stage:=90;
398
+ END_IF;
399
+ END_IF;
400
+ ${port("busy")}:=stage<90;
401
+ IF stage=90 THEN
402
+ IF slotIndex>0 THEN ${channel("requestIds")}:='';${channel("requests")}:='';${channel("inUse")}:=0;slotIndex:=0;END_IF;
403
+ timeout(IN:=FALSE);${port("busy")}:=FALSE;${port("done")}:=TRUE;
404
+ END_IF;`,
405
+ };
406
+ };
407
+
408
+ /** An HTTP service block: a native client that sends the request record and decodes the response. */
409
+ const httpServiceBlock = (
410
+ block: CoreFunctionBlock,
411
+ name: string,
412
+ { port, requestCode, decodeResponse, inputs, outputs }: ServiceCodecs,
413
+ endpoint: HttpEndpoint,
414
+ network: string,
415
+ /** The requesting job's id input and this block's request counter, sent as `x-tsplc-request`. */
416
+ trace: { job: string; sequence: string } | undefined,
417
+ ): GeneratedObject =>
418
+ nativeHttp({
419
+ id: block.id,
420
+ name,
421
+ ports: `VAR_INPUT
422
+ ${inputs}${trace ? `\n${trace.job} : ${instrumentationFieldTypes.job};` : ""}
423
+ END_VAR
424
+ VAR_OUTPUT
425
+ ${outputs}
426
+ END_VAR`,
427
+ port,
428
+ endpoint,
429
+ network,
430
+ method: block.runtime?.kind === "http" ? block.runtime.method : "GET",
431
+ json: block.runtime?.kind === "http" && block.runtime.json,
432
+ body:
433
+ block.runtime?.kind === "http" && block.runtime.json
434
+ ? `Append('{'); ${requestCode} Append('}');`
435
+ : "",
436
+ decode: decodeResponse,
437
+ ...(trace && { trace }),
438
+ });
439
+
440
+ /**
441
+ * A native HTTP/1.1 client block over Net Base Services: it sends what `body` appends to
442
+ * `payload` and, on a 2xx response, runs `decode` over the response body in `payload`.
443
+ */
444
+ export const nativeHttp = ({
445
+ id,
446
+ name,
447
+ ports,
448
+ port,
449
+ endpoint,
450
+ network,
451
+ method,
452
+ json,
453
+ body,
454
+ decode,
455
+ trace,
456
+ }: {
457
+ id: string;
458
+ name: string;
459
+ /** Its input and output declarations, with `start`, `cancel`, `busy`, `done` and `error`. */
460
+ ports: string;
461
+ port: (label: string) => string;
462
+ endpoint: HttpEndpoint;
463
+ network: string;
464
+ method: string;
465
+ json: boolean;
466
+ body: string;
467
+ decode: string;
468
+ /** The requesting job's id input and this block's request counter, sent as `x-tsplc-request`. */
469
+ trace?: { job: string; sequence: string };
470
+ }): GeneratedObject => {
471
+ const requestHeader = trace
472
+ ? `AppendWire(UDINT_TO_STRING(${trace.job}));AppendWire(':');AppendWire(UDINT_TO_STRING(${trace.sequence}));AppendWire('$R$NContent-Length: ');`
473
+ : "";
474
+ // Helpers are emitted as native methods under the HTTP block by the emitter.
475
+ return {
476
+ id,
477
+ kind: "functionBlock",
478
+ name,
479
+ declaration: `FUNCTION_BLOCK ${name}
480
+ ${ports}
481
+ VAR
482
+ remoteAddress : NBS.IPv4Address;
483
+ remoteIP : NBS.IIPAddress := remoteAddress;
484
+ resolver : NBS.ResolveHostname := (itfAsyncProperty:=${network});
485
+ ${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);` : ""}
486
+ client : NBS.TCP_Client := (itfAsyncProperty:=${network},itfIPAddress:=remoteAddress,uiPort:=${endpoint.port},udiTimeOut:=${endpoint.timeoutMs * 1000}${endpoint.tls ? ",itfTLSContext:=tlsContext" : ""});
487
+ writer : NBS.TCP_Write;
488
+ reader : NBS.TCP_Read;
489
+ timeout : TON;
490
+ stage : UINT;
491
+ wire : STRING(8192);
492
+ received : STRING(8192);
493
+ chunk : ARRAY[0..8191] OF BYTE;
494
+ payload : STRING(${plcBufferBytes});
495
+ token : STRING(${plcBufferBytes});
496
+ part : STRING(${plcBufferBytes});
497
+ used : UINT;
498
+ headerEnd : UINT;
499
+ contentLength : DINT;
500
+ status : UINT;
501
+ cursor : UINT;
502
+ malformed : BOOL;
503
+ seen : DWORD;
504
+ numberValue : LINT;
505
+ wireUsed : UINT;
506
+ tokenUsed : UINT;
507
+ index : UINT;${trace ? `\n ${trace.sequence} : ${instrumentationFieldTypes.sequence};` : ""}
508
+ END_VAR
509
+ `,
510
+ // The host goes in the resolver call, not an initial value: an online change keeps the values
511
+ // an instance already holds, so a changed host would otherwise wait for a download.
512
+ implementation: `IF NOT ${port("start")} OR ${port("cancel")} THEN
513
+ resolver(xExecute:=FALSE,itfIPAddress:=remoteIP);client(xEnable:=FALSE); writer(xExecute:=FALSE); reader(xEnable:=FALSE); timeout(IN:=FALSE);
514
+ stage:=0; ${port("busy")}:=FALSE; ${port("done")}:=FALSE; ${port("error")}:=0;
515
+ RETURN;
516
+ END_IF;
517
+ IF stage=0 THEN
518
+ payload:=''; malformed:=FALSE; used:=0; received:='';${trace ? `\n ${trace.sequence}:=${trace.sequence}+1;` : ""}
519
+ ${body}
520
+ IF malformed THEN ${port("error")}:=3; stage:=90;
521
+ ELSE
522
+ wire:='';wireUsed:=0;
523
+ 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 ? "x-tsplc-request: " : "Content-Length: "))});${requestHeader}
524
+ AppendWire(UINT_TO_STRING(ByteLength(payload)));AppendWire('$R$N$R$N');AppendWire(payload); stage:=10;
525
+ END_IF;
526
+ END_IF;
527
+ timeout(IN:=stage<90,PT:=T#${endpoint.timeoutMs}ms);
528
+ IF timeout.Q THEN ${port("error")}:=2; stage:=90; END_IF;
529
+ ${port("busy")}:=stage<90;
530
+ IF stage=10 THEN
531
+ resolver(xExecute:=TRUE,sHostname:=${stStringLiteral(endpoint.host)},itfIPAddress:=remoteIP);
532
+ IF resolver.xError THEN ${port("error")}:=5;stage:=90;ELSIF resolver.xDone THEN stage:=1;END_IF;
533
+ END_IF;
534
+ IF stage=1 THEN
535
+ client(xEnable:=TRUE);
536
+ IF client.xError THEN ${port("error")}:=${endpoint.tls ? 6 : 5};stage:=90; ELSIF client.xActive THEN stage:=2;END_IF;
537
+ END_IF;
538
+ IF stage=2 THEN
539
+ writer(xExecute:=TRUE,itfConnection:=client.itfConnection,pData:=ADR(wire),udiSize:=UINT_TO_UDINT(wireUsed));
540
+ IF writer.xError THEN ${port("error")}:=5;stage:=90;ELSIF writer.xDone THEN stage:=3;END_IF;
541
+ END_IF;
542
+ IF stage=3 THEN
543
+ IF used>=8191 THEN ${port("error")}:=3;stage:=90;
544
+ ELSE
545
+ reader(xEnable:=TRUE,itfConnection:=client.itfConnection,pData:=ADR(chunk),udiSize:=8191);
546
+ IF reader.xError THEN ${port("error")}:=5;stage:=90;
547
+ ELSIF reader.xReady AND reader.udiCount>0 THEN
548
+ IF TO_UDINT(used)+reader.udiCount>8191 THEN ${port("error")}:=3;stage:=90;
549
+ ELSE
550
+ FOR index:=0 TO TO_UINT(reader.udiCount)-1 DO received[used+index]:=chunk[index];END_FOR;
551
+ used:=used+TO_UINT(reader.udiCount);received[used]:=0;
552
+ FindHeaders();
553
+ IF headerEnd=0 AND used>4096 THEN ${port("error")}:=3;stage:=90;END_IF;
554
+ IF headerEnd>0 THEN
555
+ IF headerEnd>4096 THEN ${port("error")}:=3;stage:=90;
556
+ ELSE
557
+ ReadHeaders();
558
+ IF malformed OR contentLength<0 OR contentLength>${plcBufferBytes} THEN ${port("error")}:=3;stage:=90;
559
+ ELSIF TO_DINT(used)>=TO_DINT(headerEnd)+3+contentLength THEN
560
+ IF status<200 OR status>=300 THEN ${port("error")}:=10000+status;stage:=90;
561
+ ELSE
562
+ 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}
563
+ stage:=90;
564
+ END_IF;
565
+ END_IF;
566
+ END_IF;
567
+ END_IF;
568
+ END_IF;
569
+ END_IF;
570
+ END_IF;
571
+ END_IF;
572
+ IF stage=90 THEN
573
+ resolver(xExecute:=FALSE,itfIPAddress:=remoteIP);client(xEnable:=FALSE);writer(xExecute:=FALSE);reader(xEnable:=FALSE);timeout(IN:=FALSE);
574
+ ${port("busy")}:=FALSE;${port("done")}:=TRUE;
575
+ END_IF;
576
+ `,
577
+ };
578
+ };
579
+
580
+ export const httpCertificateVerifier = (
581
+ owner: string,
582
+ name: string,
583
+ endpoint: HttpEndpoint,
584
+ ): GeneratedObject[] => {
585
+ if (!endpoint.tls) {
586
+ return [];
587
+ }
588
+ const id = `${owner}:certificateVerifier`;
589
+ // NBS represents certificate handles as pointers; verification keeps the native trust result.
590
+ const ipv4 = /^\d+\.\d+\.\d+\.\d+$/.test(endpoint.host);
591
+ return [
592
+ {
593
+ id,
594
+ kind: "functionBlock",
595
+ name: `${name}_CertificateVerifier`,
596
+ declaration: `FUNCTION_BLOCK ${name}_CertificateVerifier IMPLEMENTS NBS.ICertificateVerifier
597
+ VAR
598
+ hostname:STRING(255):=${stStringLiteral(endpoint.host)};
599
+ ${ipv4 ? `address:ARRAY[0..3] OF BYTE := [${endpoint.host.split(".").join(",")}];` : ""}
600
+ END_VAR`,
601
+ implementation: "",
602
+ },
603
+ {
604
+ id: `${id}:VerifyCertificate`,
605
+ parent: id,
606
+ kind: "method",
607
+ name: "VerifyCertificate",
608
+ declaration: `METHOD PUBLIC VerifyCertificate : UDINT
609
+ VAR_INPUT hCert:POINTER TO BYTE;eCurState:UDINT;END_VAR
610
+ VAR matched:BOOL;result:UDINT;END_VAR`,
611
+ implementation: `VerifyCertificate:=eCurState;
612
+ IF eCurState<>0 THEN RETURN;END_IF;
613
+ matched:=CmpX509Cert_Implementation.${ipv4 ? "X509CertCheckIP(hCert,ADR(address),0,ADR(result))" : "X509CertCheckHost(hCert,ADR(hostname),4,ADR(result))"};
614
+ IF result<>0 THEN VerifyCertificate:=result;ELSIF NOT matched THEN VerifyCertificate:=1;END_IF;`,
615
+ },
616
+ ];
617
+ };
618
+
619
+ export const httpMethods = (
620
+ owner: string,
621
+ transport: "http" | "opcua" = "http",
622
+ ): GeneratedObject[] => {
623
+ const method = (
624
+ name: string,
625
+ declaration: string,
626
+ implementation: string,
627
+ result?: string,
628
+ ): GeneratedObject => ({
629
+ id: `${owner}:${name}`,
630
+ parent: owner,
631
+ kind: "method",
632
+ name,
633
+ declaration: `METHOD PRIVATE ${name}${result ? ` : ${result}` : ""}\n${declaration}`,
634
+ implementation,
635
+ });
636
+ return [
637
+ // Standard string helpers accept STRING(255); native buffers must retain their full byte length.
638
+ method(
639
+ "ByteLength",
640
+ "VAR_INPUT value:STRING(8192);END_VAR\nVAR i:UINT;END_VAR",
641
+ "ByteLength:=0;FOR i:=0 TO 8191 DO IF value[i]=0 THEN ByteLength:=i;RETURN;END_IF;END_FOR;ByteLength:=8192;",
642
+ "UINT",
643
+ ),
644
+ method(
645
+ "Append",
646
+ `VAR_INPUT value : STRING(${plcBufferBytes}); END_VAR\nVAR offset:UINT;i:UINT;END_VAR`,
647
+ `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;`,
648
+ ),
649
+ method(
650
+ "AppendWire",
651
+ "VAR_INPUT value:STRING(8192);END_VAR\nVAR i:UINT;END_VAR",
652
+ `IF wireUsed+TO_UINT(ByteLength(value))>8191 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;`,
653
+ ),
654
+ method(
655
+ "FindHeaders",
656
+ "VAR i:UINT;END_VAR",
657
+ `headerEnd:=0;IF used<4 THEN RETURN;END_IF;
658
+ 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;`,
659
+ ),
660
+ method(
661
+ "MatchLiteral",
662
+ "VAR_INPUT value:STRING(8);END_VAR\nVAR i:UINT;size:UINT;END_VAR",
663
+ `MatchLiteral:=FALSE;size:=TO_UINT(ByteLength(value));IF cursor+size-1>TO_UINT(ByteLength(payload)) THEN RETURN;END_IF;
664
+ 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;`,
665
+ "BOOL",
666
+ ),
667
+ method(
668
+ "ReadHeaders",
669
+ `VAR lineStart:UINT;lineEnd:UINT;i:UINT;j:UINT;key:STRING(64);octet:BYTE;found:BOOL;digits:UINT;END_VAR`,
670
+ `malformed:=FALSE;found:=FALSE;contentLength:=-1;
671
+ IF LEFT(received,9)<>'HTTP/1.1 ' AND LEFT(received,9)<>'HTTP/1.0 ' THEN malformed:=TRUE;RETURN;END_IF;
672
+ 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;
673
+ lineStart:=1;
674
+ WHILE lineStart<headerEnd DO
675
+ lineEnd:=lineStart;WHILE lineEnd<headerEnd AND received[lineEnd-1]<>13 DO lineEnd:=lineEnd+1;END_WHILE;
676
+ key:='';j:=0;i:=lineStart;
677
+ 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;
678
+ IF key='transfer-encoding' THEN malformed:=TRUE;RETURN;END_IF;
679
+ IF key='content-length' THEN
680
+ IF found THEN malformed:=TRUE;RETURN;END_IF;found:=TRUE;contentLength:=0;digits:=0;i:=i+1;
681
+ WHILE i<lineEnd AND received[i-1]=32 DO i:=i+1;END_WHILE;
682
+ 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;
683
+ IF digits=0 THEN malformed:=TRUE;RETURN;END_IF;
684
+ END_IF;
685
+ lineStart:=lineEnd+2;
686
+ END_WHILE;`,
687
+ ),
688
+ method(
689
+ "WriteString",
690
+ `VAR_INPUT value : STRING(${plcBufferBytes}); END_VAR\nVAR i:UINT; one:STRING(1); hex:STRING(16):='0123456789abcdef'; END_VAR`,
691
+ `Append('"');IF ByteLength(value)>0 THEN FOR i:=0 TO ByteLength(value)-1 DO
692
+ one[0]:=value[i];one[1]:=0;
693
+ IF value[i]=34 OR value[i]=92 THEN Append('\\');Append(one);
694
+ 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);
695
+ ELSE Append(one);END_IF;
696
+ END_FOR;END_IF;Append('"');`,
697
+ ),
698
+ method(
699
+ "SkipWhitespace",
700
+ "",
701
+ `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;`,
702
+ ),
703
+ method(
704
+ "Expect",
705
+ "VAR_INPUT value:BYTE; END_VAR",
706
+ `IF cursor>TO_UINT(ByteLength(payload)) OR_ELSE payload[cursor-1]<>value THEN malformed:=TRUE;ELSE cursor:=cursor+1;END_IF;`,
707
+ ),
708
+ method(
709
+ "TokenByte",
710
+ "VAR_INPUT value:BYTE;END_VAR",
711
+ `IF tokenUsed>=${plcBufferBytes} OR value=0 THEN malformed:=TRUE;RETURN;END_IF;token[tokenUsed]:=value;tokenUsed:=tokenUsed+1;token[tokenUsed]:=0;`,
712
+ ),
713
+ method(
714
+ "ReadHex",
715
+ "VAR value:UDINT;i:UINT;octet:BYTE;END_VAR",
716
+ `numberValue:=0;FOR i:=1 TO 4 DO
717
+ IF cursor>TO_UINT(ByteLength(payload)) THEN malformed:=TRUE;RETURN;END_IF;
718
+ octet:=payload[cursor-1];cursor:=cursor+1;
719
+ 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;
720
+ numberValue:=numberValue*16+TO_LINT(value);END_FOR;`,
721
+ ),
722
+ method(
723
+ "ReadString",
724
+ `VAR octet:BYTE;point:UDINT;high:UDINT;END_VAR`,
725
+ `token:='';tokenUsed:=0;Expect(34);
726
+ WHILE cursor<=TO_UINT(ByteLength(payload)) AND NOT malformed DO
727
+ octet:=payload[cursor-1];cursor:=cursor+1;
728
+ IF octet=34 THEN ValidateUtf8();RETURN;END_IF;
729
+ IF octet=92 THEN
730
+ IF cursor>TO_UINT(ByteLength(payload)) THEN malformed:=TRUE;RETURN;END_IF;
731
+ octet:=payload[cursor-1];cursor:=cursor+1;
732
+ CASE octet OF
733
+ 34,47,92: TokenByte(octet);
734
+ 98:TokenByte(8);102:TokenByte(12);110:TokenByte(10);114:TokenByte(13);116:TokenByte(9);
735
+ 117:
736
+ ReadHex();point:=TO_UDINT(numberValue);
737
+ IF point>=55296 AND point<=56319 THEN
738
+ high:=point;Expect(92);Expect(117);ReadHex();
739
+ IF numberValue<56320 OR numberValue>57343 THEN malformed:=TRUE;RETURN;END_IF;
740
+ point:=65536+(high-55296)*1024+TO_UDINT(numberValue)-56320;
741
+ ELSIF point>=56320 AND point<=57343 THEN malformed:=TRUE;RETURN;END_IF;
742
+ IF point<128 THEN TokenByte(TO_BYTE(point));
743
+ ELSIF point<2048 THEN TokenByte(TO_BYTE(192+SHR(point,6)));TokenByte(TO_BYTE(128+(point AND 63)));
744
+ 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)));
745
+ 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;
746
+ ELSE malformed:=TRUE;RETURN;
747
+ END_CASE;
748
+ ELSIF octet<32 THEN malformed:=TRUE;RETURN;ELSE TokenByte(octet);END_IF;
749
+ END_WHILE;malformed:=TRUE;`,
750
+ ),
751
+ method(
752
+ "ValidateUtf8",
753
+ "VAR i:UINT;j:UINT;count:UINT;first:BYTE;next:BYTE;END_VAR",
754
+ `i:=0;
755
+ WHILE i<tokenUsed AND NOT malformed DO
756
+ first:=token[i];
757
+ IF first<128 THEN i:=i+1;
758
+ ELSE
759
+ 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;
760
+ IF i+count>=tokenUsed THEN malformed:=TRUE;RETURN;END_IF;
761
+ next:=token[i+1];
762
+ 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;
763
+ FOR j:=1 TO count DO IF token[i+j]<128 OR token[i+j]>191 THEN malformed:=TRUE;RETURN;END_IF;END_FOR;
764
+ i:=i+count+1;
765
+ END_IF;
766
+ END_WHILE;`,
767
+ ),
768
+ method(
769
+ "ReadInteger",
770
+ "VAR negative:BOOL;digits:UINT;octet:BYTE;END_VAR",
771
+ `numberValue:=0;negative:=FALSE;digits:=0;
772
+ IF payload[cursor-1]=45 THEN negative:=TRUE;cursor:=cursor+1;END_IF;
773
+ WHILE cursor<=TO_UINT(ByteLength(payload)) DO
774
+ octet:=payload[cursor-1];IF octet<48 OR octet>57 THEN EXIT;END_IF;
775
+ IF digits>=10 THEN malformed:=TRUE;RETURN;END_IF;
776
+ 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;
777
+ END_WHILE;
778
+ IF digits=0 THEN malformed:=TRUE;END_IF;IF negative THEN numberValue:=-numberValue;END_IF;`,
779
+ ),
780
+ ].filter(
781
+ (item) =>
782
+ transport === "http" ||
783
+ !["AppendWire", "FindHeaders", "ReadHeaders"].includes(item.name),
784
+ );
785
+ };
786
+
787
+ /** A slot of an OPC UA service: the request and reply strings the server exchanges through it. */
788
+ export interface RpcChannel {
789
+ path: string;
790
+ request: string;
791
+ requestId: string;
792
+ reply: string;
793
+ replyId: string;
794
+ epoch: string;
795
+ }
796
+
797
+ /** A service-call block: its HTTP or OPC UA client, the client's methods and, over OPC UA, its slots' global list. */
798
+ export function emitServiceBlock(
799
+ { plan, symbols, instrumentation }: EmissionContext,
800
+ networkName: string | undefined,
801
+ fn: CoreFunctionBlock,
802
+ ): { objects: GeneratedObject[]; rpcChannels: RpcChannel[] } {
803
+ const objects: GeneratedObject[] = [];
804
+ const rpcChannels: RpcChannel[] = [];
805
+ const endpoint = required(plan.http[fn.id]);
806
+ const rpcGlobal =
807
+ endpoint.transport === "opcua"
808
+ ? symbols.names.allocateObject(
809
+ "GVL",
810
+ "TsplcRpc_" + required(symbols.blockNames.get(fn.id)),
811
+ )
812
+ : undefined;
813
+ if (rpcGlobal) {
814
+ objects.push({
815
+ id: fn.id + ":rpc",
816
+ kind: "globalList",
817
+ name: rpcGlobal,
818
+ declaration: `{attribute 'qualified_only'}
819
+ VAR_GLOBAL
820
+ {attribute 'symbol' := 'read'} requests:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${plcBufferBytes});
821
+ {attribute 'symbol' := 'read'} requestIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(64);
822
+ {attribute 'symbol' := 'readwrite'} replyIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(64);
823
+ {attribute 'symbol' := 'readwrite'} replies:ARRAY[1..${opcuaServiceCapacity}] OF STRING(${plcBufferBytes});
824
+ {attribute 'symbol' := 'readwrite'} epochs:ARRAY[1..${opcuaServiceCapacity}] OF STRING(32);
825
+ inUse:ARRAY[1..${opcuaServiceCapacity}] OF __XWORD;
826
+ sequence:ARRAY[1..${opcuaServiceCapacity}] OF UDINT;
827
+ END_VAR`,
828
+ });
829
+ for (let slot = 1; slot <= opcuaServiceCapacity; slot++) {
830
+ rpcChannels.push({
831
+ path: endpoint.path,
832
+ request: `${rpcGlobal}.requests[${slot}]`,
833
+ reply: `${rpcGlobal}.replies[${slot}]`,
834
+ requestId: `${rpcGlobal}.requestIds[${slot}]`,
835
+ replyId: `${rpcGlobal}.replyIds[${slot}]`,
836
+ epoch: `${rpcGlobal}.epochs[${slot}]`,
837
+ });
838
+ }
839
+ }
840
+ const name = required(symbols.blockNames.get(fn.id));
841
+ const codecs = serviceCodecs(
842
+ fn,
843
+ required(symbols.blockFields.get(fn.id)),
844
+ symbols.typeMap,
845
+ symbols.targetTypes,
846
+ );
847
+ const requestFields = instrumentation.fields.get(fn.id);
848
+ const generated = rpcGlobal
849
+ ? opcuaServiceBlock(fn, name, codecs, endpoint, rpcGlobal)
850
+ : httpServiceBlock(
851
+ fn,
852
+ name,
853
+ codecs,
854
+ endpoint,
855
+ `${required(networkName)}.network`,
856
+ requestFields?.job && requestFields.sequence
857
+ ? { job: requestFields.job, sequence: requestFields.sequence }
858
+ : undefined,
859
+ );
860
+ objects.push(
861
+ generated,
862
+ ...httpMethods(generated.id, endpoint.transport),
863
+ ...httpCertificateVerifier(generated.id, generated.name, endpoint),
864
+ );
865
+ return { objects, rpcChannels };
866
+ }
867
+
868
+ /** `GVL_TsplcNetwork`, the Net Base Services task every HTTP client runs on, when one does. */
869
+ export function httpNetwork(
870
+ plan: CodesysPlan,
871
+ symbols: CodesysSymbols,
872
+ ): GeneratedObject | undefined {
873
+ if (
874
+ !Object.values(plan.http).some((endpoint) => endpoint.transport !== "opcua")
875
+ ) {
876
+ return undefined;
877
+ }
878
+ return {
879
+ id: "runtime:httpNetwork",
880
+ kind: "globalList",
881
+ name: symbols.names.allocateObject("GVL", "TsplcNetwork"),
882
+ // Blocks in other global lists take this in their initializers, so it must initialize first.
883
+ declaration: `{attribute 'qualified_only'}
884
+ {attribute 'global_init_slot' := '40000'}
885
+ VAR_GLOBAL
886
+ network:NBS.AsyncProperty := (usiTaskPrio:=15,udiTaskInterval:=1000,tnTaskName:='tsPLC HTTP');
887
+ END_VAR
888
+ `,
889
+ };
890
+ }