@tsplc/build 0.4.0 → 0.4.1
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/dist/cli.js +25 -6
- package/dist/cli.js.map +8 -7
- package/dist/index.js +35 -6
- package/dist/index.js.map +8 -7
- package/docker/Dockerfile +1 -1
- package/package.json +4 -4
- package/python/build.py +9 -6
- package/python/codesys_online.py +75 -26
- package/python/hardware.py +144 -26
- package/python/worker.py +13 -5
- package/src/controller-online.ts +34 -1
- package/src/controller-protocol.ts +4 -5
- package/src/controller-session.ts +274 -142
- package/src/device-tree.ts +52 -12
- package/src/index.ts +1 -0
package/docker/Dockerfile
CHANGED
|
@@ -40,7 +40,7 @@ RUN apt-get -o Acquire::Retries=3 update \
|
|
|
40
40
|
&& add-apt-repository -y ppa:fex-emu/fex \
|
|
41
41
|
&& apt-get -o Acquire::Retries=3 update \
|
|
42
42
|
&& apt-get -o Acquire::Retries=3 install -y --no-install-recommends \
|
|
43
|
-
fex-emu-armv8.2=
|
|
43
|
+
fex-emu-armv8.2=2611.1-1~n gcc python3 msitools p7zip-full fonts-liberation \
|
|
44
44
|
&& rm -rf /var/lib/apt/lists/*
|
|
45
45
|
COPY --from=base /usr /opt/fex-rootfs/usr
|
|
46
46
|
COPY --from=base /lib /opt/fex-rootfs/lib
|
package/package.json
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"url": "git+https://github.com/rip-technologies/tsplc.git",
|
|
16
16
|
"directory": "packages/build"
|
|
17
17
|
},
|
|
18
|
-
"version": "0.4.
|
|
18
|
+
"version": "0.4.1",
|
|
19
19
|
"type": "module",
|
|
20
20
|
"exports": {
|
|
21
21
|
".": {
|
|
@@ -54,9 +54,9 @@
|
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
56
|
"zod": "4.3.6",
|
|
57
|
-
"@tsplc/config": "0.4.
|
|
58
|
-
"@tsplc/typegen": "0.4.
|
|
59
|
-
"@tsplc/iec": "0.4.
|
|
57
|
+
"@tsplc/config": "0.4.1",
|
|
58
|
+
"@tsplc/typegen": "0.4.1",
|
|
59
|
+
"@tsplc/iec": "0.4.1"
|
|
60
60
|
},
|
|
61
61
|
"bin": {
|
|
62
62
|
"tsplc-build": "./dist/cli.js"
|
package/python/build.py
CHANGED
|
@@ -17,7 +17,7 @@ import tempfile
|
|
|
17
17
|
import time
|
|
18
18
|
from xml.sax.saxutils import escape, quoteattr
|
|
19
19
|
|
|
20
|
-
from hardware import apply_controller, configure_device_tree, import_device_description, verify_pinned
|
|
20
|
+
from hardware import apply_controller, configure_device_tree, import_device_description, update_device_tree, verify_pinned
|
|
21
21
|
|
|
22
22
|
# create_symbol_config's client-side layout calculator; the image check in docker/install/verify.py uses it too.
|
|
23
23
|
SYMBOL_LAYOUT_CALCULATOR = "{0141eb75-141b-4ea1-9a8c-75f952b22a6c}"
|
|
@@ -697,8 +697,10 @@ def cache_path(directory, kind, scripts, inputs):
|
|
|
697
697
|
|
|
698
698
|
def device_tree_cache(request, directory):
|
|
699
699
|
"""The project as it stands once its device tree is generated. Generating the tree takes most of
|
|
700
|
-
a build, and the same template, controller, tree and hardware.py always produce the
|
|
701
|
-
|
|
700
|
+
a build, and the same template, controller, tree structure and hardware.py always produce the
|
|
701
|
+
same one; whoever opens it maps its channels."""
|
|
702
|
+
return cache_path(directory, "device-tree", ["hardware.py"],
|
|
703
|
+
[request["templateHash"], request.get("controller"), request["deviceTree"]["structure"]])
|
|
702
704
|
|
|
703
705
|
|
|
704
706
|
def build_cache(request, directory):
|
|
@@ -736,15 +738,16 @@ def describe_devices(engine, tree, root):
|
|
|
736
738
|
|
|
737
739
|
def open_template(engine, request, path, devices, caches, progress):
|
|
738
740
|
"""Opens the template as `path` with its controller and device tree, whose descriptions are in
|
|
739
|
-
`devices`; from the cache in `caches` when it holds this tree. Returns the project,
|
|
740
|
-
it pinned, and a newly generated tree to keep once the project works."""
|
|
741
|
+
`devices`; from the cache in `caches` when it holds this tree's structure. Returns the project,
|
|
742
|
+
the channels it pinned, and a newly generated tree to keep once the project works."""
|
|
741
743
|
tree = request.get("deviceTree")
|
|
742
744
|
cache = device_tree_cache(request, caches) if tree else None
|
|
743
745
|
if cache and os.path.isfile(cache):
|
|
744
746
|
progress("Reusing the generated device tree")
|
|
745
747
|
describe_devices(engine, tree, devices)
|
|
746
748
|
shutil.copyfile(cache, path)
|
|
747
|
-
|
|
749
|
+
project = engine.projects.open(path, primary=True)
|
|
750
|
+
return project, update_device_tree(engine, project, tree, progress), None
|
|
748
751
|
progress("Opening project")
|
|
749
752
|
project = engine.projects.open(request["template"], primary=True)
|
|
750
753
|
project.save_as(path)
|
package/python/codesys_online.py
CHANGED
|
@@ -7,7 +7,7 @@ import os
|
|
|
7
7
|
import re
|
|
8
8
|
from build import (clear_diagnostics, fail_on_errors, import_source, keep_device_tree, open_template,
|
|
9
9
|
reported_errors, write_progress)
|
|
10
|
-
from hardware import verify_pinned
|
|
10
|
+
from hardware import update_device_tree, verify_pinned
|
|
11
11
|
from System import Activator, AppDomain, Array, Enum, Environment, Object
|
|
12
12
|
from System.Net import Dns, IPAddress
|
|
13
13
|
from System.Reflection import BindingFlags, TargetInvocationException
|
|
@@ -238,18 +238,29 @@ def connect_controller(engine, application, settings, credentials_file=None):
|
|
|
238
238
|
return device, credentials
|
|
239
239
|
|
|
240
240
|
|
|
241
|
+
def opened_ahead(request, prepared, progress):
|
|
242
|
+
"""The project a warm worker opened ahead, when it is this operation's; another one is closed."""
|
|
243
|
+
if prepared is None:
|
|
244
|
+
return None
|
|
245
|
+
if os.path.normcase(prepared.path) == os.path.normcase(request['project']):
|
|
246
|
+
progress('Using the project opened ahead')
|
|
247
|
+
return prepared
|
|
248
|
+
prepared.close()
|
|
249
|
+
return None
|
|
250
|
+
|
|
251
|
+
|
|
241
252
|
def open_operation_project(engine, request, prepared, progress):
|
|
242
|
-
"""Returns the project, the channels
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
return engine
|
|
253
|
+
"""Returns the project, the channels its tree pinned, and a newly generated tree to keep once the operation works."""
|
|
254
|
+
project = opened_ahead(request, prepared, progress)
|
|
255
|
+
if project is None:
|
|
256
|
+
# Operations reuse the downloaded project, which has its controller and tree; a download without one starts from the template.
|
|
257
|
+
if request['operation'] == 'download' and request.get('baseline') is None:
|
|
258
|
+
return open_template(engine, request, request['project'], request.get('devices'), request['caches'], progress)
|
|
259
|
+
progress('Opening project')
|
|
260
|
+
project = engine.projects.open(request['project'], primary=True)
|
|
261
|
+
tree = request.get('deviceTree')
|
|
262
|
+
# The downloaded tree has this tree's structure, but the channel mappings of the last download.
|
|
263
|
+
return project, update_device_tree(engine, project, tree, progress) if tree else {}, None
|
|
253
264
|
|
|
254
265
|
|
|
255
266
|
def restore_previous(engine, request, progress):
|
|
@@ -299,13 +310,52 @@ def restore_previous(engine, request, progress):
|
|
|
299
310
|
project.close()
|
|
300
311
|
|
|
301
312
|
|
|
302
|
-
def
|
|
303
|
-
|
|
304
|
-
progress_path = request.get('progress')
|
|
313
|
+
def request_progress(request):
|
|
314
|
+
path = request.get('progress')
|
|
305
315
|
def progress(stage):
|
|
306
|
-
if
|
|
307
|
-
write_progress(
|
|
316
|
+
if path:
|
|
317
|
+
write_progress(path, stage)
|
|
318
|
+
return progress
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def save_operation_project(project, generated, progress):
|
|
322
|
+
progress('Saving downloaded project')
|
|
323
|
+
project.save()
|
|
324
|
+
if generated:
|
|
325
|
+
keep_device_tree(*generated)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def close_operation_project(project, progress):
|
|
329
|
+
# The original language-model manager joins its asynchronous downloaded
|
|
330
|
+
# reference saver on project close. Publication happens after this returns.
|
|
331
|
+
progress('Closing project and waiting for downloaded reference')
|
|
332
|
+
project.close()
|
|
333
|
+
progress('Project closed')
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def finish_online(request, finishing):
|
|
337
|
+
"""Saves and closes the project of the operation a warm worker already replied to, which waits
|
|
338
|
+
for its downloaded reference. `finishing` is what that operation kept: the project and its newly
|
|
339
|
+
generated tree."""
|
|
340
|
+
progress = request_progress(request)
|
|
341
|
+
if finishing is None:
|
|
342
|
+
raise RuntimeError('No controller operation is waiting to be saved')
|
|
343
|
+
project, generated = finishing
|
|
344
|
+
try:
|
|
345
|
+
save_operation_project(project, generated, progress)
|
|
346
|
+
finally:
|
|
347
|
+
close_operation_project(project, progress)
|
|
348
|
+
return {}
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def run_online(engine, request, prepared=None, keep=None):
|
|
352
|
+
"""`prepared` is a project a warm worker opened ahead; an online change of that project uses it.
|
|
353
|
+
A request to finish later replies once the controller runs the application, and hands `keep`
|
|
354
|
+
the open project and its newly generated tree, for `finish_online` to save."""
|
|
355
|
+
progress = request_progress(request)
|
|
308
356
|
progress('Starting; processor count {0}'.format(Environment.ProcessorCount))
|
|
357
|
+
if request.get('finishLater') and keep is None:
|
|
358
|
+
raise RuntimeError('Only a warm worker can finish an operation later')
|
|
309
359
|
if request['operation'] == 'restore':
|
|
310
360
|
if prepared is not None:
|
|
311
361
|
prepared.close()
|
|
@@ -315,6 +365,7 @@ def run_online(engine, request, prepared=None):
|
|
|
315
365
|
application = project.active_application
|
|
316
366
|
online_app = None
|
|
317
367
|
online_device = None
|
|
368
|
+
kept = []
|
|
318
369
|
try:
|
|
319
370
|
progress('Project opened; configuring controller connection')
|
|
320
371
|
if application is None:
|
|
@@ -427,18 +478,16 @@ def run_online(engine, request, prepared=None):
|
|
|
427
478
|
'state': state, 'application': application.get_name(),
|
|
428
479
|
'values': {expression: online_app.read_value(expression) for expression in request.get('read', [])}}
|
|
429
480
|
online_app.logout()
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
481
|
+
if request.get('finishLater'):
|
|
482
|
+
keep(project, generated)
|
|
483
|
+
kept.append(project)
|
|
484
|
+
else:
|
|
485
|
+
save_operation_project(project, generated, progress)
|
|
434
486
|
return result
|
|
435
487
|
finally:
|
|
436
488
|
if online_app is not None:
|
|
437
489
|
online_app.Dispose()
|
|
438
490
|
if online_device is not None:
|
|
439
491
|
online_device.Dispose()
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
progress('Closing project and waiting for downloaded reference')
|
|
443
|
-
project.close()
|
|
444
|
-
progress('Project closed')
|
|
492
|
+
if not kept:
|
|
493
|
+
close_operation_project(project, progress)
|
package/python/hardware.py
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
"""The controller and its device tree, which a build generates once and caches by this file's hash
|
|
1
|
+
"""The controller and its device tree, which a build generates once and caches by this file's hash
|
|
2
|
+
and the tree's structure; an operation that opens a generated tree writes its adapter settings and
|
|
3
|
+
maps its channels.
|
|
2
4
|
Runs inside CODESYS's Python engine, not the Mac's Python installation."""
|
|
3
5
|
from __future__ import print_function
|
|
4
6
|
|
|
@@ -54,10 +56,18 @@ def child_device(parent, spec):
|
|
|
54
56
|
return matches[0]
|
|
55
57
|
|
|
56
58
|
|
|
59
|
+
def same_value(parameter, value):
|
|
60
|
+
return unicode(parameter.value).replace(" ", "") == unicode(value).replace(" ", "")
|
|
61
|
+
|
|
62
|
+
|
|
57
63
|
def set_parameter(parameter, value):
|
|
64
|
+
"""Writes `value` unless the parameter already holds it, since each write revalidates the whole tree; returns whether it wrote."""
|
|
65
|
+
if same_value(parameter, value):
|
|
66
|
+
return False
|
|
58
67
|
parameter.value = value
|
|
59
|
-
if
|
|
68
|
+
if not same_value(parameter, value):
|
|
60
69
|
raise RuntimeError("{0} reads back {1}, not {2}".format(parameter.visible_name, parameter.value, value))
|
|
70
|
+
return True
|
|
61
71
|
|
|
62
72
|
|
|
63
73
|
def string_literal(parameter, text):
|
|
@@ -114,16 +124,38 @@ def channel_at(pinned, address):
|
|
|
114
124
|
return list(channel)[int(match.group(4))] if match.group(2) == "X" else channel
|
|
115
125
|
|
|
116
126
|
|
|
127
|
+
def channel_elements(pinned):
|
|
128
|
+
"""Every pinned channel by address, with the bits of each pinned byte as %IX and %QX addresses."""
|
|
129
|
+
elements = dict(pinned)
|
|
130
|
+
for address, channel in pinned.items():
|
|
131
|
+
match = re.match(r"^%([IQ])B(\d+)$", address)
|
|
132
|
+
if match and channel.bit_size == 8:
|
|
133
|
+
for bit, element in enumerate(channel):
|
|
134
|
+
elements.setdefault("%{0}X{1}.{2}".format(match.group(1), match.group(2), bit), element)
|
|
135
|
+
return elements
|
|
136
|
+
|
|
137
|
+
|
|
117
138
|
def map_channels(pinned, tree, application):
|
|
118
|
-
"""Map bound bits and bytes to their variables
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
139
|
+
"""Map bound bits and bytes to their variables and comment the channels of IO that keeps AT;
|
|
140
|
+
a channel no longer bound loses its mapping or comment. Writes only what differs, since each
|
|
141
|
+
write revalidates the whole tree, and returns how many it made."""
|
|
142
|
+
variables = dict((mapping["address"], application + "." + mapping["variable"]) for mapping in tree.get("mappings", []))
|
|
143
|
+
comments = dict((comment["address"], comment["text"]) for device in tree["devices"]
|
|
144
|
+
for comment in device.get("comments", []) if comment["address"] not in variables)
|
|
145
|
+
for address in sorted(set(variables) | set(comments)):
|
|
146
|
+
channel_at(pinned, address)
|
|
147
|
+
writes = 0
|
|
148
|
+
for address, element in sorted(channel_elements(pinned).items()):
|
|
149
|
+
variable = variables.get(address, "")
|
|
150
|
+
# CODESYS resolves IEC names regardless of case.
|
|
151
|
+
if (element.io_mapping.variable or "").lower() != variable.lower():
|
|
152
|
+
element.io_mapping.variable = variable
|
|
153
|
+
writes += 1
|
|
154
|
+
comment = comments.get(address, "")
|
|
155
|
+
if (element.user_comment or "") != comment:
|
|
156
|
+
element.user_comment = comment
|
|
157
|
+
writes += 1
|
|
158
|
+
return writes
|
|
127
159
|
|
|
128
160
|
|
|
129
161
|
def add_modbus_channel(project, server, register):
|
|
@@ -159,6 +191,22 @@ def add_modbus_channel(project, server, register):
|
|
|
159
191
|
return int(UInt32(item_type.GetField("uiParamID").GetValue(item))) // MODBUS_CHANNEL
|
|
160
192
|
|
|
161
193
|
|
|
194
|
+
def configure_adapter(parameters, device):
|
|
195
|
+
"""Writes the adapter settings a generated tree takes in place; the device tree's structure leaves out their values."""
|
|
196
|
+
writes = 0
|
|
197
|
+
if device.get("address"):
|
|
198
|
+
writes += set_parameter(parameters[TARGET_ADDRESS], ip_array(device["address"], hexadecimal=True))
|
|
199
|
+
if device.get("rpiMicroseconds"):
|
|
200
|
+
fields = [field for field in parameters[CONNECTION_SETTINGS] if field.identifier == "RPI"]
|
|
201
|
+
writes += set_parameter(fields[0], str(device["rpiMicroseconds"]))
|
|
202
|
+
return writes
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def configure_server(parameters, device):
|
|
206
|
+
"""A card's Modbus server is at its adapter's address, which a generated tree takes in place too."""
|
|
207
|
+
return int(set_parameter(parameters[MODBUS_ADDRESS], ip_array(device["address"])))
|
|
208
|
+
|
|
209
|
+
|
|
162
210
|
def configure_modbus(engine, project, ethernet, devices):
|
|
163
211
|
"""One Modbus TCP server per card with registers, with channels pinned like the EtherNet/IP bytes."""
|
|
164
212
|
pinned = {}
|
|
@@ -172,11 +220,12 @@ def configure_modbus(engine, project, ethernet, devices):
|
|
|
172
220
|
server = child_device(client, (device["name"] + "_Modbus",) + MODBUS_SERVER)
|
|
173
221
|
server.driver_info.always_update_variables = engine.AlwaysUpdateVariablesMode.OnlyIfUnused
|
|
174
222
|
parameters = host_parameters(server)
|
|
175
|
-
|
|
223
|
+
configure_server(parameters, device)
|
|
176
224
|
set_parameter(parameters[MODBUS_PORT], str(device["modbus"]["port"]))
|
|
177
|
-
for register in device["modbus"]["registers"]
|
|
178
|
-
|
|
179
|
-
|
|
225
|
+
channels = [(register, add_modbus_channel(project, server, register) * MODBUS_CHANNEL) for register in device["modbus"]["registers"]]
|
|
226
|
+
# Adding a channel replaces the server's parameters, so they are read once every channel is added.
|
|
227
|
+
parameters = host_parameters(server)
|
|
228
|
+
for register, channel in channels:
|
|
180
229
|
pinned[register["write"]] = parameters[channel + MODBUS_TRIGGER]
|
|
181
230
|
pinned[register["status"]] = parameters[channel + MODBUS_STATUS]
|
|
182
231
|
pinned[register["requests"]] = parameters[channel + MODBUS_REQUESTS]
|
|
@@ -230,31 +279,100 @@ def configure_device_tree(engine, project, tree, root, progress):
|
|
|
230
279
|
set_parameter(parameters[identifier], string_literal(parameters[identifier], value) if key == "interface" else ip_array(value))
|
|
231
280
|
scanner = child_device(ethernet, SCANNER)
|
|
232
281
|
pinned = {}
|
|
282
|
+
registers = [device for device in tree["devices"] if device.get("modbus")]
|
|
283
|
+
if registers:
|
|
284
|
+
# Every write revalidates the whole tree, so the Modbus servers, with few channels, come before
|
|
285
|
+
# the adapters' many. The scanner was added first, so the Modbus client still follows it.
|
|
286
|
+
progress("Generating Modbus TCP devices")
|
|
287
|
+
pinned.update(configure_modbus(engine, project, ethernet, registers))
|
|
288
|
+
progress("Generating EtherNet/IP adapters")
|
|
233
289
|
for device in tree["devices"]:
|
|
234
290
|
identity = import_device_description(engine, device, root)
|
|
235
291
|
adapter = child_device(scanner, (device["name"], identity.type, identity.id, identity.version))
|
|
236
292
|
# CODESYS otherwise skips mapped variables no IEC code reads, such as inputs only clients observe.
|
|
237
293
|
adapter.driver_info.always_update_variables = engine.AlwaysUpdateVariablesMode.OnlyIfUnused
|
|
238
294
|
parameters = host_parameters(adapter)
|
|
239
|
-
|
|
240
|
-
set_parameter(parameters[TARGET_ADDRESS], ip_array(device["address"], hexadecimal=True))
|
|
241
|
-
if device.get("rpiMicroseconds"):
|
|
242
|
-
fields = [field for field in parameters[CONNECTION_SETTINGS] if field.identifier == "RPI"]
|
|
243
|
-
set_parameter(fields[0], str(device["rpiMicroseconds"]))
|
|
295
|
+
configure_adapter(parameters, device)
|
|
244
296
|
for address, channel in pin_channels(engine, parameters, device).items():
|
|
245
297
|
if address in pinned:
|
|
246
|
-
raise RuntimeError("{0} overlaps another
|
|
298
|
+
raise RuntimeError("{0} overlaps another device".format(address))
|
|
247
299
|
pinned[address] = channel
|
|
248
|
-
|
|
249
|
-
if registers:
|
|
250
|
-
progress("Generating Modbus TCP devices")
|
|
251
|
-
pinned.update(configure_modbus(engine, project, ethernet, registers))
|
|
252
|
-
# Adding a later adapter can reflow earlier automatic addresses.
|
|
300
|
+
# Adding a later device can reflow earlier automatic addresses.
|
|
253
301
|
settle(pinned)
|
|
254
302
|
map_channels(pinned, tree, project.active_application.get_name())
|
|
255
303
|
return pinned
|
|
256
304
|
|
|
257
305
|
|
|
306
|
+
def device_of_type(parent, spec):
|
|
307
|
+
matches = [child for child in parent.get_children(False)
|
|
308
|
+
if getattr(child, "is_device", False) and child.get_device_identification().type == spec[1]]
|
|
309
|
+
if len(matches) != 1:
|
|
310
|
+
raise RuntimeError("{0} has no generated {1}".format(parent.get_name(), spec[0]))
|
|
311
|
+
return matches[0]
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def named_device(parent, name):
|
|
315
|
+
matches = [child for child in parent.find(name, False) if getattr(child, "is_device", False)]
|
|
316
|
+
if len(matches) != 1:
|
|
317
|
+
raise RuntimeError("{0} has no generated device {1}".format(parent.get_name(), name))
|
|
318
|
+
return matches[0]
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def pinned_addresses(tree):
|
|
322
|
+
"""The address of every channel generating `tree` pins: each assembly byte and each register's four."""
|
|
323
|
+
addresses = []
|
|
324
|
+
for device in tree["devices"]:
|
|
325
|
+
for direction, region in (("inputs", "I"), ("outputs", "Q")):
|
|
326
|
+
area = device.get(direction)
|
|
327
|
+
if area:
|
|
328
|
+
base = int(area["address"][3:])
|
|
329
|
+
addresses += ["%{0}B{1}".format(region, base + offset) for offset in range(area["size"])]
|
|
330
|
+
for register in device.get("modbus", {}).get("registers", []):
|
|
331
|
+
addresses += [register[key] for key in ("write", "status", "requests", "value")]
|
|
332
|
+
return addresses
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def generated_devices(project, tree):
|
|
336
|
+
"""Each of `tree`'s devices with its adapter and, when it has registers, its Modbus server, as a tree generated earlier holds them."""
|
|
337
|
+
ethernet = device_of_type(template_controller(project), ETHERNET)
|
|
338
|
+
scanner = device_of_type(ethernet, SCANNER)
|
|
339
|
+
client = device_of_type(ethernet, MODBUS_CLIENT) if any(device.get("modbus") for device in tree["devices"]) else None
|
|
340
|
+
return [(device, named_device(scanner, device["name"]),
|
|
341
|
+
named_device(client, device["name"] + "_Modbus") if device.get("modbus") else None) for device in tree["devices"]]
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def generated_channels(engine, devices, tree):
|
|
345
|
+
"""The pinned channels of the generated `devices`, by address."""
|
|
346
|
+
kinds = (engine.ChannelType.Input, engine.ChannelType.Output)
|
|
347
|
+
channels = {}
|
|
348
|
+
for _, adapter, server in devices:
|
|
349
|
+
for generated in (adapter, server) if server else (adapter,):
|
|
350
|
+
for parameter in host_parameters(generated).values():
|
|
351
|
+
if parameter.channel_type in kinds:
|
|
352
|
+
# An automatic channel reports its assigned address here.
|
|
353
|
+
channels[parameter.io_mapping.manual_iec_address] = parameter
|
|
354
|
+
missing = [address for address in pinned_addresses(tree) if address not in channels]
|
|
355
|
+
if missing:
|
|
356
|
+
raise RuntimeError("The project's device tree has no channel at " + ", ".join(missing))
|
|
357
|
+
return dict((address, channels[address]) for address in pinned_addresses(tree))
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def update_device_tree(engine, project, tree, progress):
|
|
361
|
+
"""Brings a tree generated earlier with `tree`'s structure, in a cached template or a downloaded
|
|
362
|
+
project, up to its adapter settings and channel mappings; returns its pinned channels."""
|
|
363
|
+
progress("Updating the device tree's adapter settings and channel mappings")
|
|
364
|
+
devices = generated_devices(project, tree)
|
|
365
|
+
settings = 0
|
|
366
|
+
for device, adapter, server in devices:
|
|
367
|
+
settings += configure_adapter(host_parameters(adapter), device)
|
|
368
|
+
if server:
|
|
369
|
+
settings += configure_server(host_parameters(server), device)
|
|
370
|
+
pinned = generated_channels(engine, devices, tree)
|
|
371
|
+
writes = map_channels(pinned, tree, project.active_application.get_name())
|
|
372
|
+
progress("Wrote {0} adapter settings and {1} channel mappings and comments".format(settings, writes))
|
|
373
|
+
return pinned
|
|
374
|
+
|
|
375
|
+
|
|
258
376
|
def verify_pinned(pinned):
|
|
259
377
|
for address, channel in pinned.items():
|
|
260
378
|
if channel.io_mapping.manual_iec_address != address:
|
package/python/worker.py
CHANGED
|
@@ -45,20 +45,28 @@ def run_build(engine, directory, loaded):
|
|
|
45
45
|
|
|
46
46
|
|
|
47
47
|
def run_controller_operation(engine, directory, loaded):
|
|
48
|
-
from codesys_online import run_online
|
|
49
|
-
prepared = loaded.pop("prepared", None)
|
|
50
|
-
close_loaded(loaded)
|
|
48
|
+
from codesys_online import finish_online, run_online
|
|
51
49
|
root = os.path.join(os.path.dirname(directory), "controller")
|
|
52
50
|
with io.open(os.path.join(root, "request.json"), encoding="utf-8") as source:
|
|
53
51
|
request = json.load(source)
|
|
54
|
-
|
|
52
|
+
prepared = loaded.pop("prepared", None)
|
|
53
|
+
finishing = loaded.pop("finishing", None) if request["operation"] == "finish" else None
|
|
54
|
+
close_loaded(loaded)
|
|
55
|
+
if request["operation"] == "finish":
|
|
56
|
+
result = finish_online(request, finishing)
|
|
57
|
+
else:
|
|
58
|
+
result = run_online(engine, request, prepared, lambda project, generated: loaded.update(finishing=(project, generated)))
|
|
59
|
+
write_json(engine, os.path.join(root, "result.json"), result)
|
|
55
60
|
|
|
56
61
|
|
|
57
62
|
def close_loaded(loaded):
|
|
58
|
-
"""Closes the project an earlier build or prepare left open
|
|
63
|
+
"""Closes the project an earlier build or prepare left open, and one a controller operation
|
|
64
|
+
left to finish, unsaved, so its download is never committed."""
|
|
59
65
|
for key in ("project", "prepared"):
|
|
60
66
|
if loaded.get(key) is not None:
|
|
61
67
|
loaded[key].close()
|
|
68
|
+
if loaded.get("finishing") is not None:
|
|
69
|
+
loaded["finishing"][0].close()
|
|
62
70
|
loaded.clear()
|
|
63
71
|
|
|
64
72
|
|
package/src/controller-online.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
|
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
5
|
import { posix, resolve } from "node:path";
|
|
6
6
|
import { setTimeout as delay } from "node:timers/promises";
|
|
7
|
-
import type
|
|
7
|
+
import { controllerBudgets, type ResolvedConfig } from "@tsplc/config/build";
|
|
8
8
|
import { z } from "zod";
|
|
9
9
|
import {
|
|
10
10
|
type Baseline,
|
|
@@ -287,6 +287,37 @@ const answers = (name: string, port: number) =>
|
|
|
287
287
|
() => false,
|
|
288
288
|
);
|
|
289
289
|
|
|
290
|
+
const warmStateSchema = z.object({ finishing: z.boolean() });
|
|
291
|
+
|
|
292
|
+
/** Whether warm builder container `name` still commits an operation it has reported; not when it doesn't answer. */
|
|
293
|
+
const finishing = (name: string) =>
|
|
294
|
+
callContainer(name, warmPort, "GET").then(
|
|
295
|
+
(state) => warmStateSchema.safeParse(state).data?.finishing === true,
|
|
296
|
+
() => false,
|
|
297
|
+
);
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Waits while warm builder container `name` saves and commits the project of an operation it has
|
|
301
|
+
* already reported, so a login, a check of the download baseline or a replacement container sees
|
|
302
|
+
* the committed one. Returns at once when no such container runs. A commit is bounded by the
|
|
303
|
+
* worker's `prepare` budget and a copy to the output directory, so one that outlasts twice that
|
|
304
|
+
* budget is reported instead of waited for.
|
|
305
|
+
*/
|
|
306
|
+
export const settleWarmController = async (
|
|
307
|
+
config: ResolvedConfig,
|
|
308
|
+
name: string,
|
|
309
|
+
) => {
|
|
310
|
+
const deadline = Date.now() + 2 * controllerBudgets(config.timeouts).prepare;
|
|
311
|
+
while (await finishing(name)) {
|
|
312
|
+
if (Date.now() >= deadline) {
|
|
313
|
+
throw new Error(
|
|
314
|
+
"CODESYS is still saving the last deployment's project; try again once it has",
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
await delay(1000);
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
|
|
290
321
|
/** A logout takes seconds; one still running after this waits on a worker that stopped answering. */
|
|
291
322
|
const logoutTimeout = 60_000;
|
|
292
323
|
|
|
@@ -414,6 +445,8 @@ const warmController = async (
|
|
|
414
445
|
report(
|
|
415
446
|
"Starting CODESYS: no running builder matches this image, controller and Docker settings, which takes minutes",
|
|
416
447
|
);
|
|
448
|
+
// A container for other settings may still commit the last deployment, which a rollback restores.
|
|
449
|
+
await settleWarmController(config, name);
|
|
417
450
|
await docker(["rm", "--force", name], timeout);
|
|
418
451
|
// Its own request: the operations' configs come later, one per release.
|
|
419
452
|
const requestDirectory = resolve(config.outDir, ".codesys/warm-request");
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// What the host and the builder container exchange for controller operations: the receipt,
|
|
2
2
|
// the target a baseline is bound to, warm and login commands, and how failures are worded.
|
|
3
|
-
import { createHash } from "node:crypto";
|
|
4
3
|
import {
|
|
5
4
|
controllerSchema,
|
|
6
5
|
type ResolvedConfig,
|
|
@@ -8,6 +7,7 @@ import {
|
|
|
8
7
|
tcpPort,
|
|
9
8
|
} from "@tsplc/config/build";
|
|
10
9
|
import { z } from "zod";
|
|
10
|
+
import { deviceTreeStructure } from "./device-tree";
|
|
11
11
|
|
|
12
12
|
export const imageIdSchema = z.string().regex(/^sha256:[a-f0-9]{64}$/);
|
|
13
13
|
const endpointSchema = z.strictObject({
|
|
@@ -76,7 +76,8 @@ export const failureReason = (error: unknown) =>
|
|
|
76
76
|
|
|
77
77
|
/**
|
|
78
78
|
* What a download binds the controller to. An online change needs the same connection, controller
|
|
79
|
-
* and device tree, because it only recompiles the program into the downloaded project.
|
|
79
|
+
* and device tree, because it only recompiles the program into the downloaded project. The tree is
|
|
80
|
+
* its structure: an operation maps its channels into the downloaded tree.
|
|
80
81
|
*/
|
|
81
82
|
export const controllerTarget = (
|
|
82
83
|
config: ResolvedConfig,
|
|
@@ -87,9 +88,7 @@ export const controllerTarget = (
|
|
|
87
88
|
device: online.device,
|
|
88
89
|
controller: config.controller,
|
|
89
90
|
...(config.deviceTree && {
|
|
90
|
-
deviceTree:
|
|
91
|
-
.update(JSON.stringify(config.deviceTree))
|
|
92
|
-
.digest("hex"),
|
|
91
|
+
deviceTree: deviceTreeStructure(config.deviceTree),
|
|
93
92
|
}),
|
|
94
93
|
});
|
|
95
94
|
|