@tsplc/compiler 0.5.9 → 0.5.12

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 (74) hide show
  1. package/dist/cli.js +396 -66
  2. package/dist/cli.js.map +10 -8
  3. package/dist/codesys.js +2 -2
  4. package/dist/codesys.js.map +1 -1
  5. package/package.json +9 -9
  6. package/src/project/cli.ts +15 -3
  7. package/src/project/deployments.ts +443 -0
  8. package/src/project/git.ts +35 -0
  9. package/src/project/plant.ts +119 -36
  10. package/src/project/release.ts +15 -6
  11. package/src/runtime/.runtime-65O4JH/server/router.ts +17 -0
  12. package/src/runtime/.runtime-65O4JH/src/cell.ts +45 -0
  13. package/src/runtime/.runtime-65O4JH/src/controller.ts +58 -0
  14. package/src/runtime/.runtime-65O4JH/src/lane.ts +6 -0
  15. package/src/runtime/.runtime-65O4JH/src/main.ts +11 -0
  16. package/src/runtime/.runtime-65O4JH/src/services.ts +8 -0
  17. package/src/runtime/.runtime-65O4JH/tsconfig.json +13 -0
  18. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +31 -0
  19. package/src/runtime/.runtime-Brw2kO/server/router.ts +17 -0
  20. package/src/runtime/.runtime-Brw2kO/src/cell.ts +45 -0
  21. package/src/runtime/.runtime-Brw2kO/src/controller.ts +58 -0
  22. package/src/runtime/.runtime-Brw2kO/src/lane.ts +6 -0
  23. package/src/runtime/.runtime-Brw2kO/src/main.ts +11 -0
  24. package/src/runtime/.runtime-Brw2kO/src/services.ts +8 -0
  25. package/src/runtime/.runtime-Brw2kO/tsconfig.json +13 -0
  26. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +31 -0
  27. package/src/runtime/.runtime-NHfu1D/server/router.ts +17 -0
  28. package/src/runtime/.runtime-NHfu1D/src/cell.ts +45 -0
  29. package/src/runtime/.runtime-NHfu1D/src/controller.ts +58 -0
  30. package/src/runtime/.runtime-NHfu1D/src/lane.ts +6 -0
  31. package/src/runtime/.runtime-NHfu1D/src/main.ts +11 -0
  32. package/src/runtime/.runtime-NHfu1D/src/services.ts +8 -0
  33. package/src/runtime/.runtime-NHfu1D/tsconfig.json +13 -0
  34. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +31 -0
  35. package/src/runtime/.runtime-WbtNvR/server/router.ts +17 -0
  36. package/src/runtime/.runtime-WbtNvR/src/cell.ts +45 -0
  37. package/src/runtime/.runtime-WbtNvR/src/controller.ts +58 -0
  38. package/src/runtime/.runtime-WbtNvR/src/lane.ts +6 -0
  39. package/src/runtime/.runtime-WbtNvR/src/main.ts +11 -0
  40. package/src/runtime/.runtime-WbtNvR/src/services.ts +8 -0
  41. package/src/runtime/.runtime-WbtNvR/tsconfig.json +13 -0
  42. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +31 -0
  43. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +17 -0
  44. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +45 -0
  45. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +58 -0
  46. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +6 -0
  47. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +11 -0
  48. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +8 -0
  49. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +13 -0
  50. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +31 -0
  51. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +17 -0
  52. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +45 -0
  53. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +58 -0
  54. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +6 -0
  55. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +11 -0
  56. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +8 -0
  57. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +13 -0
  58. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +31 -0
  59. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +17 -0
  60. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +45 -0
  61. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +58 -0
  62. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +6 -0
  63. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +11 -0
  64. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +8 -0
  65. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +13 -0
  66. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +31 -0
  67. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +17 -0
  68. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +45 -0
  69. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +58 -0
  70. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +6 -0
  71. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +11 -0
  72. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +8 -0
  73. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +13 -0
  74. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +31 -0
@@ -5,21 +5,35 @@ import {
5
5
  type Target,
6
6
  type Variable,
7
7
  } from "@tsplc/agent";
8
- import {
9
- type AgentClient,
10
- AgentOperationError,
11
- createAgentClient,
12
- } from "@tsplc/agent/client";
8
+ import { type AgentClient, createAgentClient } from "@tsplc/agent/client";
13
9
  import type { LoginCommand, LoginResult } from "@tsplc/build";
14
10
  import type { CompileEnvironment } from "@tsplc/compiler";
15
- import type { LoadedConfig } from "@tsplc/config";
11
+ import {
12
+ type LoadedConfig,
13
+ type PlantVariables,
14
+ releaseEnvironment,
15
+ } from "@tsplc/config";
16
16
  import { LoginUnavailable, noLogin } from "@tsplc/debug";
17
17
  import { z } from "zod";
18
+ import {
19
+ type Approval,
20
+ type Follow,
21
+ openDashboard,
22
+ printDeployments,
23
+ redeploy,
24
+ rollBack,
25
+ submitDeployment,
26
+ } from "./deployments";
27
+ import { gitSource } from "./git";
18
28
  import { prepareRelease } from "./release";
19
29
  import { choose, confirm, progress, timedProgress } from "./terminal";
20
30
 
21
31
  const plantCommands = [
22
32
  "deploy",
33
+ "deployments",
34
+ "rollback",
35
+ "redeploy",
36
+ "dashboard",
23
37
  "target",
24
38
  "status",
25
39
  "login",
@@ -32,6 +46,7 @@ const plantCommands = [
32
46
  "start",
33
47
  "stop",
34
48
  "reset",
49
+ "restart",
35
50
  ] as const;
36
51
 
37
52
  export type PlantCommand = (typeof plantCommands)[number];
@@ -41,6 +56,9 @@ export const plantCommand = (name: string) =>
41
56
 
42
57
  export interface PlantFlags {
43
58
  download?: boolean;
59
+ format?: "json" | "text";
60
+ review?: boolean;
61
+ wait?: boolean;
44
62
  "initialize-user"?: boolean;
45
63
  restore?: boolean;
46
64
  select?: boolean;
@@ -153,12 +171,26 @@ export const controllerCredentials = async (
153
171
  return agent.stored && !agent.initializeUser ? null : prompt();
154
172
  };
155
173
 
174
+ /** The plant PC's variables and secrets by name, as `variables A, B and secret C`, or null when it holds none. */
175
+ const plantSummary = ({ values, secrets }: PlantVariables) => {
176
+ const named = (noun: string, names: readonly string[]) =>
177
+ names.length
178
+ ? `${noun}${names.length === 1 ? "" : "s"} ${names.join(", ")}`
179
+ : null;
180
+ const parts = [
181
+ named("variable", Object.keys(values)),
182
+ named("secret", secrets),
183
+ ].filter((part) => part !== null);
184
+ return parts.length ? parts.join(" and ") : null;
185
+ };
186
+
156
187
  const deploy = async (
157
188
  agent: AgentClient,
158
189
  file: string,
159
190
  loaded: LoadedConfig,
160
191
  flags: PlantFlags,
161
192
  environment: CompileEnvironment,
193
+ follow: Follow,
162
194
  ) => {
163
195
  const status = await agent.status();
164
196
  if (status.login) {
@@ -166,13 +198,25 @@ const deploy = async (
166
198
  }
167
199
  const target =
168
200
  !status.target || flags.select ? await selectTarget(agent) : status.target;
201
+ const plant = await agent.releaseVariables(
202
+ loaded.config.secrets?.service ?? null,
203
+ );
204
+ const built = releaseEnvironment(
205
+ loaded.config,
206
+ { env: environment, values: loaded.values },
207
+ plant,
208
+ );
169
209
  console.log(`Building the release for ${target.host}…`);
210
+ const held = plantSummary(plant);
211
+ if (held) {
212
+ console.log(` With the plant PC's ${held}`);
213
+ }
170
214
  const building = timedProgress();
171
215
  const { release, diagnostics } = await prepareRelease(
172
216
  file,
173
217
  loaded,
174
218
  flags,
175
- environment,
219
+ built,
176
220
  );
177
221
  if (!release) {
178
222
  return { diagnostics };
@@ -202,29 +246,21 @@ const deploy = async (
202
246
  };
203
247
  console.log(
204
248
  release.manifest.server
205
- ? "Deploying the server and the program…"
206
- : "Deploying the program…",
249
+ ? "Uploading the server and the program…"
250
+ : "Uploading the program…",
207
251
  );
208
- const deploying = timedProgress();
209
- deploying("Uploading");
210
- try {
211
- return await agent.deploy(release, settings, deploying);
212
- } catch (error) {
213
- if (
214
- !(error instanceof AgentOperationError && error.downloadRequired) ||
215
- !(await confirm(
216
- `${error.message}. A full download stops the running application while it loads. Download now?`,
217
- flags,
218
- ))
219
- ) {
220
- throw error;
221
- }
222
- return agent.deploy(
252
+ return {
253
+ exitCode: await submitDeployment(
254
+ agent,
223
255
  release,
224
- { ...settings, download: true },
225
- timedProgress(),
226
- );
227
- }
256
+ settings,
257
+ {
258
+ mode: flags.review ? "review" : "apply",
259
+ git: await gitSource(loaded.root),
260
+ },
261
+ follow,
262
+ ),
263
+ };
228
264
  };
229
265
 
230
266
  /** Opens a login when none is working; it stays open across commands until `tsplc logout`. */
@@ -346,7 +382,7 @@ const printLogin = (result: LoginResult) => {
346
382
 
347
383
  /**
348
384
  * Runs a command against the plant agent. Returns a deployment's compiler diagnostics when the
349
- * program doesn't compile.
385
+ * program doesn't compile, and the exit code of a command that queues a deployment.
350
386
  */
351
387
  export const runPlantCommand = async (
352
388
  agent: AgentClient,
@@ -358,8 +394,16 @@ export const runPlantCommand = async (
358
394
  load: () => Promise<LoadedConfig>;
359
395
  /** What the release's compilation reads. */
360
396
  environment: CompileEnvironment;
397
+ /** Someone at a terminal can answer prompts. */
398
+ interactive: boolean;
361
399
  },
362
400
  ) => {
401
+ const approval: Approval = {
402
+ yes: flags.yes ?? false,
403
+ interactive: project.interactive,
404
+ confirm: (question) => confirm(question, {}),
405
+ };
406
+ const follow = { wait: flags.wait ?? false, approval };
363
407
  const expect = (count: number, usage: string) => {
364
408
  if (args.length !== count) {
365
409
  throw new Error(`Usage: tsplc ${command} ${usage}`);
@@ -370,24 +414,44 @@ export const runPlantCommand = async (
370
414
  printLogin(await agent.command(loginCommand));
371
415
  };
372
416
  switch (command) {
373
- case "deploy": {
417
+ case "deploy":
374
418
  expect(
375
419
  0,
376
- "[--target name] [--download] [--select] [--initialize-user] [--simulate]",
420
+ "[--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait] [-y]",
377
421
  );
378
- const deployed = await deploy(
422
+ return deploy(
379
423
  agent,
380
424
  project.file,
381
425
  await project.load(),
382
426
  flags,
383
427
  project.environment,
428
+ follow,
384
429
  );
385
- if ("diagnostics" in deployed) {
386
- return deployed;
430
+ case "deployments":
431
+ expect(0, "[--format json]");
432
+ return printDeployments(agent, flags);
433
+ case "rollback":
434
+ if (args.length > 1) {
435
+ throw new Error("Usage: tsplc rollback [id] [--wait] [-y]");
387
436
  }
388
- console.log(`Deployed release ${deployed.id} (${deployed.operation}).`);
389
- return;
437
+ return { exitCode: await rollBack(agent, args[0], follow) };
438
+ case "redeploy": {
439
+ const [id, ...extra] = args;
440
+ if (!id || extra.length) {
441
+ throw new Error("Usage: tsplc redeploy <id> [--review] [--wait] [-y]");
442
+ }
443
+ return {
444
+ exitCode: await redeploy(
445
+ agent,
446
+ id,
447
+ flags.review ? "review" : "apply",
448
+ follow,
449
+ ),
450
+ };
390
451
  }
452
+ case "dashboard":
453
+ expect(0, "");
454
+ return openDashboard(agent, project.interactive);
391
455
  case "target": {
392
456
  expect(0, "");
393
457
  const target = await selectTarget(agent);
@@ -458,6 +522,25 @@ export const runPlantCommand = async (
458
522
  throw new Error("Cancelled.");
459
523
  }
460
524
  return send({ command: "stop" });
525
+ case "restart": {
526
+ if (args.length > 1) {
527
+ throw new Error("Usage: tsplc restart [warm|cold] [-y]");
528
+ }
529
+ const reset = z.enum(["warm", "cold"]).parse(args[0] ?? "warm");
530
+ if (
531
+ !(await confirm(
532
+ `Reset the application (${reset}) and start it again? Its variables go back to their initial values${reset === "warm" ? ", but for retain ones" : ""}.`,
533
+ flags,
534
+ ))
535
+ ) {
536
+ throw new Error("Cancelled.");
537
+ }
538
+ const { state } = await agent.restartController({ reset });
539
+ console.log(
540
+ `Reset ${reset}; the application is ${state === "run" ? "running" : state}.`,
541
+ );
542
+ return;
543
+ }
461
544
  case "reset": {
462
545
  expect(1, "warm|cold");
463
546
  const kind = z.enum(["warm", "cold"]).parse(args[0]);
@@ -45,9 +45,18 @@ export const prepareRelease = async (
45
45
  file: string,
46
46
  loaded: LoadedConfig,
47
47
  flags: { simulate?: boolean; "frozen-lockfile"?: boolean },
48
- environment: CompileEnvironment,
48
+ built: {
49
+ /** What the build reads, with the plant PC's values and placeholders for its secrets. */
50
+ env: CompileEnvironment;
51
+ /** Every plain value the release carries to its server. */
52
+ values: ReleaseManifest["values"];
53
+ /** The secrets the agent fills in. */
54
+ secrets: ReleaseManifest["secrets"];
55
+ },
49
56
  ) => {
50
- const { config, root } = loaded;
57
+ // Every step reads the loaded config's environment, so it carries the plant PC's.
58
+ const project: LoadedConfig = { ...loaded, env: built.env };
59
+ const { config, root } = project;
51
60
  if (!config.compiler) {
52
61
  throw new Error("tsplc deploy deploys tsPLC programs; configure compiler.");
53
62
  }
@@ -61,10 +70,9 @@ export const prepareRelease = async (
61
70
  emitOnly: true,
62
71
  forController: true,
63
72
  frozenLockfile: flags["frozen-lockfile"],
64
- ...buildConfigs(loaded, flags),
73
+ ...buildConfigs(project, flags),
65
74
  buildTarget: buildTargetFor(command),
66
75
  controller: controllerFor(config, command),
67
- environment,
68
76
  });
69
77
  if (hasErrors(emitted.diagnostics)) {
70
78
  return { diagnostics: emitted.diagnostics };
@@ -73,7 +81,7 @@ export const prepareRelease = async (
73
81
  if (!settings) {
74
82
  throw new Error("Configure build settings for deployment.");
75
83
  }
76
- await generateProject(file, { loaded, targets: emitted.targets });
84
+ await generateProject(file, { loaded: project, targets: emitted.targets });
77
85
 
78
86
  const portable = (path: string) => path.split(sep).join("/");
79
87
  const libraries = (settings.libraries ?? []).map((library) => ({
@@ -143,7 +151,8 @@ export const prepareRelease = async (
143
151
  server: server?.path,
144
152
  debug: config.debug,
145
153
  serverTokenEnv: serverTokenEnv(config),
146
- secrets: config.secrets,
154
+ secrets: built.secrets,
155
+ values: built.values,
147
156
  };
148
157
  return { release: { manifest, files } };
149
158
  };
@@ -0,0 +1,17 @@
1
+ import { initTRPC } from "@trpc/server";
2
+ import { iec, type PlcMeta } from "@tsplc/server";
3
+ import { z } from "zod";
4
+
5
+ const api = initTRPC.meta<PlcMeta>().create();
6
+ /** Callable by the PLC through createServiceClient. */
7
+ const plcProcedure = api.procedure.meta({ plc: true });
8
+
9
+ export const appRouter = api.router({
10
+ cell: api.router({
11
+ report: plcProcedure
12
+ .input(z.strictObject({ count: iec.UINT(), running: z.boolean() }))
13
+ .output(z.strictObject({ answer: iec.DINT() }))
14
+ .mutation(({ input }) => ({ answer: input.count * 2 + 1 })),
15
+ }),
16
+ });
17
+ export type AppRouter = typeof appRouter;
@@ -0,0 +1,45 @@
1
+ import { retain } from "@tsplc/compiler/retain";
2
+ import { Lane } from "./lane";
3
+
4
+ export type Mode = "idle" | "running";
5
+
6
+ export interface Card {
7
+ input: { sensor: BOOL };
8
+ output: { motion: BOOL; speed: INT };
9
+ }
10
+
11
+ /** The cell's IO, its operator's controls and its counts: what the program publishes. */
12
+ export interface Cell {
13
+ cards: Card[];
14
+ mode: Mode;
15
+ start: BOOL;
16
+ bump: BOOL;
17
+ count: UINT;
18
+ scans: UDINT;
19
+ lanes: Record<Lane, BOOL>;
20
+ lastLane: Lane | undefined;
21
+ report: BOOL;
22
+ replies: UDINT;
23
+ answer: DINT;
24
+ failures: UDINT;
25
+ settings: { speed: INT };
26
+ }
27
+
28
+ export const createCell = (): Cell => ({
29
+ cards: Array.from({ length: 3 }, () => ({
30
+ input: { sensor: false },
31
+ output: { motion: false, speed: 0 },
32
+ })),
33
+ mode: "idle",
34
+ start: false,
35
+ bump: false,
36
+ count: 0,
37
+ scans: 0,
38
+ lanes: { [Lane.Unknown]: false, [Lane.Left]: false, [Lane.Right]: false },
39
+ lastLane: undefined,
40
+ report: false,
41
+ replies: 0,
42
+ answer: 0,
43
+ failures: 0,
44
+ settings: retain({ speed: 50 }),
45
+ });
@@ -0,0 +1,58 @@
1
+ import { telemetry } from "@tsplc/compiler/telemetry";
2
+ import type { Cell } from "./cell";
3
+ import { Lane } from "./lane";
4
+ import type { ReportReply, Services } from "./services";
5
+
6
+ export class CellController {
7
+ private sending = false;
8
+
9
+ constructor(
10
+ private readonly cell: Cell,
11
+ private readonly services: Services,
12
+ ) {}
13
+
14
+ scan(): void {
15
+ const cell = this.cell;
16
+ cell.scans += 1;
17
+ for (const card of cell.cards) {
18
+ card.output.motion = card.input.sensor && cell.mode === "running";
19
+ card.output.speed = card.input.sensor ? cell.settings.speed : 0;
20
+ }
21
+ if (cell.start) {
22
+ cell.start = false;
23
+ cell.mode = "running";
24
+ }
25
+ if (cell.bump) {
26
+ cell.bump = false;
27
+ cell.count = cell.count + 1;
28
+ }
29
+ cell.lastLane = undefined;
30
+ if (cell.lanes[Lane.Left]) {
31
+ cell.lastLane = Lane.Left;
32
+ }
33
+ if (cell.lanes[Lane.Right]) {
34
+ cell.lastLane = Lane.Right;
35
+ }
36
+ if (cell.report && !this.sending) {
37
+ cell.report = false;
38
+ void this.send();
39
+ }
40
+ }
41
+
42
+ private async send(): Promise<void> {
43
+ this.sending = true;
44
+ try {
45
+ const reply: ReportReply = await this.services.cell.report({
46
+ count: this.cell.count,
47
+ running: this.cell.mode === "running",
48
+ });
49
+ this.cell.replies += 1;
50
+ this.cell.answer = reply.answer;
51
+ telemetry.info("Report answered", { answer: reply.answer });
52
+ } catch (error) {
53
+ this.cell.failures += 1;
54
+ telemetry.captureException(error);
55
+ }
56
+ this.sending = false;
57
+ }
58
+ }
@@ -0,0 +1,6 @@
1
+ /** Where the cell sends a part. */
2
+ export enum Lane {
3
+ Unknown = 0,
4
+ Left = 1,
5
+ Right = 2,
6
+ }
@@ -0,0 +1,11 @@
1
+ import { createCell } from "./cell";
2
+ import { CellController } from "./controller";
3
+ import { services } from "./services";
4
+
5
+ export const cell = createCell();
6
+ const controller = new CellController(cell, services);
7
+
8
+ /** One PLC scan. */
9
+ export function main(): void {
10
+ controller.scan();
11
+ }
@@ -0,0 +1,8 @@
1
+ import type { inferRouterOutputs } from "@trpc/server";
2
+ import { createServiceClient } from "@tsplc/compiler/async";
3
+ import type { AppRouter } from "../server/router";
4
+
5
+ /** The server procedures the program calls. */
6
+ export const services = createServiceClient<AppRouter>();
7
+ export type Services = typeof services;
8
+ export type ReportReply = inferRouterOutputs<AppRouter>["cell"]["report"];
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "strict": true,
4
+ "target": "ES2022",
5
+ "module": "ESNext",
6
+ "moduleResolution": "Bundler",
7
+ "noEmit": true,
8
+ "skipLibCheck": true,
9
+ "types": ["bun", "@tsplc/compiler/globals"],
10
+ "allowImportingTsExtensions": true
11
+ },
12
+ "include": ["src/**/*.ts", "server/**/*.ts"]
13
+ }
@@ -0,0 +1,31 @@
1
+ import { defineConfig, ms } from "@tsplc/config";
2
+
3
+ /** A cell whose plain TypeScript program the Bun runtime runs in the compiler's tests. */
4
+ export default defineConfig({
5
+ name: "BunRuntimeCell",
6
+ backend: "codesys",
7
+ build: { outDir: "build/codesys", symbols: true },
8
+ codesys: {
9
+ http: {
10
+ timeoutMs: 2000,
11
+ credentials: [
12
+ { originEnv: "CELL_SERVER_URL", bearerTokenEnv: "CELL_SERVER_TOKEN" },
13
+ ],
14
+ },
15
+ programNames: { main: "Main" },
16
+ },
17
+ compiler: {
18
+ programs: { main: { module: "src/main.ts", export: "main" } },
19
+ },
20
+ tasks: [
21
+ {
22
+ name: "MainTask",
23
+ priority: 1,
24
+ schedule: { kind: "cyclic", interval: ms(20) },
25
+ programs: ["main"],
26
+ },
27
+ ],
28
+ publish: { development: ["cell"], production: ["cell"] },
29
+ server: { transport: "http", baseUrlEnv: "CELL_SERVER_URL" },
30
+ typegen: { dir: "generated" },
31
+ });
@@ -0,0 +1,17 @@
1
+ import { initTRPC } from "@trpc/server";
2
+ import { iec, type PlcMeta } from "@tsplc/server";
3
+ import { z } from "zod";
4
+
5
+ const api = initTRPC.meta<PlcMeta>().create();
6
+ /** Callable by the PLC through createServiceClient. */
7
+ const plcProcedure = api.procedure.meta({ plc: true });
8
+
9
+ export const appRouter = api.router({
10
+ cell: api.router({
11
+ report: plcProcedure
12
+ .input(z.strictObject({ count: iec.UINT(), running: z.boolean() }))
13
+ .output(z.strictObject({ answer: iec.DINT() }))
14
+ .mutation(({ input }) => ({ answer: input.count * 2 + 1 })),
15
+ }),
16
+ });
17
+ export type AppRouter = typeof appRouter;
@@ -0,0 +1,45 @@
1
+ import { retain } from "@tsplc/compiler/retain";
2
+ import { Lane } from "./lane";
3
+
4
+ export type Mode = "idle" | "running";
5
+
6
+ export interface Card {
7
+ input: { sensor: BOOL };
8
+ output: { motion: BOOL; speed: INT };
9
+ }
10
+
11
+ /** The cell's IO, its operator's controls and its counts: what the program publishes. */
12
+ export interface Cell {
13
+ cards: Card[];
14
+ mode: Mode;
15
+ start: BOOL;
16
+ bump: BOOL;
17
+ count: UINT;
18
+ scans: UDINT;
19
+ lanes: Record<Lane, BOOL>;
20
+ lastLane: Lane | undefined;
21
+ report: BOOL;
22
+ replies: UDINT;
23
+ answer: DINT;
24
+ failures: UDINT;
25
+ settings: { speed: INT };
26
+ }
27
+
28
+ export const createCell = (): Cell => ({
29
+ cards: Array.from({ length: 3 }, () => ({
30
+ input: { sensor: false },
31
+ output: { motion: false, speed: 0 },
32
+ })),
33
+ mode: "idle",
34
+ start: false,
35
+ bump: false,
36
+ count: 0,
37
+ scans: 0,
38
+ lanes: { [Lane.Unknown]: false, [Lane.Left]: false, [Lane.Right]: false },
39
+ lastLane: undefined,
40
+ report: false,
41
+ replies: 0,
42
+ answer: 0,
43
+ failures: 0,
44
+ settings: retain({ speed: 50 }),
45
+ });
@@ -0,0 +1,58 @@
1
+ import { telemetry } from "@tsplc/compiler/telemetry";
2
+ import type { Cell } from "./cell";
3
+ import { Lane } from "./lane";
4
+ import type { ReportReply, Services } from "./services";
5
+
6
+ export class CellController {
7
+ private sending = false;
8
+
9
+ constructor(
10
+ private readonly cell: Cell,
11
+ private readonly services: Services,
12
+ ) {}
13
+
14
+ scan(): void {
15
+ const cell = this.cell;
16
+ cell.scans += 1;
17
+ for (const card of cell.cards) {
18
+ card.output.motion = card.input.sensor && cell.mode === "running";
19
+ card.output.speed = card.input.sensor ? cell.settings.speed : 0;
20
+ }
21
+ if (cell.start) {
22
+ cell.start = false;
23
+ cell.mode = "running";
24
+ }
25
+ if (cell.bump) {
26
+ cell.bump = false;
27
+ cell.count = cell.count + 1;
28
+ }
29
+ cell.lastLane = undefined;
30
+ if (cell.lanes[Lane.Left]) {
31
+ cell.lastLane = Lane.Left;
32
+ }
33
+ if (cell.lanes[Lane.Right]) {
34
+ cell.lastLane = Lane.Right;
35
+ }
36
+ if (cell.report && !this.sending) {
37
+ cell.report = false;
38
+ void this.send();
39
+ }
40
+ }
41
+
42
+ private async send(): Promise<void> {
43
+ this.sending = true;
44
+ try {
45
+ const reply: ReportReply = await this.services.cell.report({
46
+ count: this.cell.count,
47
+ running: this.cell.mode === "running",
48
+ });
49
+ this.cell.replies += 1;
50
+ this.cell.answer = reply.answer;
51
+ telemetry.info("Report answered", { answer: reply.answer });
52
+ } catch (error) {
53
+ this.cell.failures += 1;
54
+ telemetry.captureException(error);
55
+ }
56
+ this.sending = false;
57
+ }
58
+ }
@@ -0,0 +1,6 @@
1
+ /** Where the cell sends a part. */
2
+ export enum Lane {
3
+ Unknown = 0,
4
+ Left = 1,
5
+ Right = 2,
6
+ }
@@ -0,0 +1,11 @@
1
+ import { createCell } from "./cell";
2
+ import { CellController } from "./controller";
3
+ import { services } from "./services";
4
+
5
+ export const cell = createCell();
6
+ const controller = new CellController(cell, services);
7
+
8
+ /** One PLC scan. */
9
+ export function main(): void {
10
+ controller.scan();
11
+ }
@@ -0,0 +1,8 @@
1
+ import type { inferRouterOutputs } from "@trpc/server";
2
+ import { createServiceClient } from "@tsplc/compiler/async";
3
+ import type { AppRouter } from "../server/router";
4
+
5
+ /** The server procedures the program calls. */
6
+ export const services = createServiceClient<AppRouter>();
7
+ export type Services = typeof services;
8
+ export type ReportReply = inferRouterOutputs<AppRouter>["cell"]["report"];
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "strict": true,
4
+ "target": "ES2022",
5
+ "module": "ESNext",
6
+ "moduleResolution": "Bundler",
7
+ "noEmit": true,
8
+ "skipLibCheck": true,
9
+ "types": ["bun", "@tsplc/compiler/globals"],
10
+ "allowImportingTsExtensions": true
11
+ },
12
+ "include": ["src/**/*.ts", "server/**/*.ts"]
13
+ }