symetrie-hexapod 0.17.3__py3-none-any.whl

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.
@@ -0,0 +1,1438 @@
1
+ """
2
+ This module provides the implementation of the commanding interfaces for the Alpha and Alpha+
3
+ controller using the new dynamic commanding scheme. The three main classes are the `AlphaPlusTelnetInterface`,
4
+ the `AlphaControllerInterface` and the `AlphaPlusControllerInterface`.
5
+
6
+ The `AlphaPlusTelnetInterface` directly talks to the device through the telnet protocol on port 23.
7
+
8
+ The `AlphaControllerInterface` provides an interface with methods that are compatible with both the Alpha controller
9
+ and the AlphaPlusController. This interface shall be sub-classed for proxy and controller classes that use the
10
+ alpha controller, like the PUNA Hexapod.
11
+
12
+ The `AlphaPlusControllerInterface` inherits from the `AlphaControllerInterface` and provides additional methods
13
+ that are specific for the alpha+ controllers. This class should be sub-classed for proxy and controller classes
14
+ that use the alpha+ controller, like the ZONDA hexapod.
15
+
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ from functools import partial
22
+ from telnetlib import Telnet
23
+ from typing import Any
24
+ from typing import Callable
25
+ from typing import Dict
26
+ from typing import List
27
+ from typing import Tuple
28
+
29
+ from egse.device import DeviceConnectionError
30
+ from egse.device import DeviceConnectionInterface
31
+ from egse.device import DeviceInterface
32
+ from egse.device import DeviceTransport
33
+ from egse.mixin import add_cr_lf
34
+ from egse.mixin import dynamic_command
35
+ from egse.response import Failure
36
+ from egse.response import Success
37
+ from egse.settings import Settings
38
+ from egse.system import Timer
39
+ from egse.system import wait_until
40
+
41
+ LOGGER = logging.getLogger(__name__)
42
+ PUNA_PLUS = Settings.load("PUNA Alpha+ Controller")
43
+
44
+ # The following constants represent the index into the GENERAL_STATE list and are used in the code
45
+ # to match the name of a flag in the general_state.
46
+
47
+ HOME_COMPLETE = 6
48
+ IN_POSITION = 3
49
+ IN_MOTION = 4
50
+
51
+ GENERAL_STATE = [
52
+ "Error",
53
+ "System initialized",
54
+ "Control on",
55
+ "In position",
56
+ "Motion task running",
57
+ "Home task running",
58
+ "Home complete",
59
+ "Home virtual",
60
+ "Phase found",
61
+ "Brake on",
62
+ "Motion restricted",
63
+ "Power on encoders",
64
+ "Power on limit switches",
65
+ "Power on drives",
66
+ "Emergency stop",
67
+ ]
68
+
69
+
70
+ ACTUATOR_STATE = [
71
+ "Error",
72
+ "Control on",
73
+ "In position",
74
+ "Motion task running",
75
+ "Home task running",
76
+ "Home complete",
77
+ "Phase found",
78
+ "Brake on",
79
+ "Home hardware input",
80
+ "Negative hardware limit switch",
81
+ "Positive hardware limit switch",
82
+ "Software limit reached",
83
+ "Following error",
84
+ "Drive fault",
85
+ "Encoder error",
86
+ ]
87
+
88
+
89
+ ERROR_CODES = {
90
+ 1: "An emergency stop has been pressed.",
91
+ 2: "A safety input has been triggered. The status of the inputs is given in the DATA field.",
92
+ 3: "A temperature sensor has exceeded the limit threshold. Sensor number is given in DATA field.",
93
+ 4: "Controller system status error (Sys.Status).",
94
+ 5: "Controller ‘abort all’ input has been triggered. (Sys.AbortAll).",
95
+ 6: "Controller watchdog error (Sys.WDTFault).",
96
+ 7: "Configuration load error.",
97
+ 8: "Configuration failed: a wrong hexapod ID has been detected. Detected ID is given in DATA field.",
98
+ 9: "Home task has failed.",
99
+ 10: "Virtual home write task has failed.",
100
+ 11: "The motion program did not start in the defined timeout.",
101
+ 12: "The home task did not start in the defined timeout.",
102
+ 13: "A kinematic error has occurred. Kinematic error number is given in DATA field.",
103
+ 14: "Controller coordinate error status (Coord.ErrorStatus). Error number is given in DATA field.",
104
+ 15: "An error has been detected on encoder.",
105
+ 16: "Brake should have been engaged as the motor control was off.",
106
+ 17: "Controller motor status: Auxiliary fault (AuxFault).",
107
+ 18: "Controller motor status: Encoder loss (EncLoss).",
108
+ 19: "Controller motor status: Amplifier warning (AmpWarn).",
109
+ 20: "Controller motor status: Trigger not found (TriggerNotFound).",
110
+ 21: "Controller motor status: Integrated current 'I2T' fault (I2tFault).",
111
+ 22: "Controller motor status: Software positive limit reach (SoftPlusLimit).",
112
+ 23: "Controller motor status: Software negative limit reach (SoftMinusLimit).",
113
+ 24: "Controller motor status: Amplifier fault (AmpFault).",
114
+ 25: "Controller motor status: Stopped on hardware limit (LimitStop).",
115
+ 26: "Controller motor status: Fatal following error (FeFatal).",
116
+ 27: "Controller motor status: Warning following error (FeWarn).",
117
+ 28: "Controller motor status: Hardware positive limit reach (PlusLimit).",
118
+ 29: "Controller motor status: Hardware negative limit reach (MinusLimit).",
119
+ }
120
+
121
+
122
+ RETURN_CODES = {
123
+ 0: "Success.",
124
+ -1: "Undefined error.",
125
+ -10: "Wrong value for parameter at index 0.",
126
+ -11: "Wrong value for parameter at index 1.",
127
+ -12: "Wrong value for parameter at index 2.",
128
+ -13: "Wrong value for parameter at index 3.",
129
+ -14: "Wrong value for parameter at index 4.",
130
+ -15: "Wrong value for parameter at index 5.",
131
+ -16: "Wrong value for parameter at index 6.",
132
+ -17: "Wrong value for parameter at index 7.",
133
+ -18: "Wrong value for parameter at index 8.",
134
+ -19: "Wrong value for parameter at index 9.",
135
+ -20: "Wrong value for parameter at index 10.",
136
+ -21: "Wrong value for parameter at index 11.",
137
+ -22: "Wrong value for parameter at index 12.",
138
+ -23: "Wrong value for parameter at index 13.",
139
+ -24: "Wrong value for parameter at index 14.",
140
+ -25: "Wrong value for parameter at index 15.",
141
+ -26: "Wrong value for parameter at index 16.",
142
+ -27: "Wrong value for parameter at index 17.",
143
+ -28: "Wrong value for parameter at index 18.",
144
+ -29: "Wrong value for parameter at index 19.",
145
+ -30: "Unknown command number.",
146
+ -31: "This configuration command is a 'get' only type.",
147
+ -32: "This configuration command is a 'set' only type.",
148
+ -33: "The axis number do not correspond to an axis defined on the controller.",
149
+ -34: "A stop task is running.",
150
+ -35: "All motors need to be control on.",
151
+ -36: "All motors need to be control off.",
152
+ -37: "Emergency stop is pressed.",
153
+ -38: "A motion task is running.",
154
+ -39: "A home task is running.",
155
+ -40: "Requested move is not feasible.",
156
+ -41: "Power supply of limit switches is off.",
157
+ -42: "Power supply of encoders is off.",
158
+ -43: "A fatal error is present. This type of error needs a controller restart to be removed.",
159
+ -44: "An error is present, error reset is required.",
160
+ -45: "Home is not completed.",
161
+ -46: "Software option not available (can be linked to hardware configuration).",
162
+ -47: "Virtual home: file was created on another controller (different MAC address).",
163
+ -48: "Virtual home: some positions read in file are out of software limits.",
164
+ -49: "Virtual home: file data were stored while hexapod was moving.",
165
+ -50: "Virtual home: no data available.",
166
+ -51: "Command has been rejected because another action is running.",
167
+ -52: "Timeout waiting for home complete status.",
168
+ -53: "Timeout waiting for control on status.",
169
+ -54: "Timeout on motion program start.",
170
+ -55: "Timeout on home task start.",
171
+ -56: "Timeout on virtual home write file task.",
172
+ -57: "Timeout on virtual home delete file task.",
173
+ -58: "Timeout on virtual home read file task.",
174
+ -59: "Timeout on disk access verification task.",
175
+ -60: "Configuration file: save process failed.",
176
+ -61: "Configuration file: loaded file is empty.",
177
+ -62: "Configuration file: loaded data are corrupted.",
178
+ -63: "No access to the memory disk.",
179
+ -64: "File does not exist.",
180
+ -65: "Folder access failed.",
181
+ -66: "Creation of folder tree on the memory disk failed.",
182
+ -67: "Generation or write of the checksum failed.",
183
+ -68: "File read: no data or wrong data size.",
184
+ -69: "File read: no checksum.",
185
+ -70: "File read: incorrect checksum.",
186
+ -71: "File write: failed.",
187
+ -72: "File open: failed.",
188
+ -73: "File delete: failed.",
189
+ -74: "Get MAC address failed.",
190
+ -75: "NaN (Not a Number) or infinite value found.",
191
+ -76: "The coordinate system transformations are not initialized.",
192
+ -77: "A kinematic error is present.",
193
+ -78: "The motor phase process failed (phase search or phase set from position offset).",
194
+ -79: "The motor phase is not found.",
195
+ -80: "Timeout waiting for control off status.",
196
+ -81: "The requested kinematic mode (number) is not defined for the machine.",
197
+ -82: "Timeout waiting for phase found status.",
198
+ -1000: "Internal error: 'RET_Dev_CfS_NaNReturned'.",
199
+ -1001: "Internal error: 'RET_Dev_CfS_FctNotAvailableInKernel'.",
200
+ -1002: "Internal error: 'RET_Dev_CfS_UndefinedCfSType'.",
201
+ -1003: "Internal error: 'RET_Dev_CfS_FIO_UndefinedFioType'.",
202
+ -1004: "Internal error: 'RET_Dev_CfS_FIO_HomeFile_UndefinedAction'.",
203
+ -1005: "Internal error: 'RET_Dev_UndefinedEnumValue'.",
204
+ -1006: "Internal error: 'RET_Dev_LdataCmdStatusIsNegative'.",
205
+ -1007: "Internal error: 'RET_Dev_NumMotorsInCoord_Sup_DEF_aGrQ_SIZE'.",
206
+ -1008: "Internal error: 'RET_Dev_NumMotorsInCoord_WrongNumber'.",
207
+ -1009: "Internal error: 'RET_String_StrCat_DestSizeReached'.",
208
+ -1010: "Internal error: 'RET_String_LengthOverStringSize'.",
209
+ -1011: "Internal error: 'RET_String_AllCharShouldIntBetween_0_255'.",
210
+ -1012: "Internal error: 'RET_String_StrCpy_DestSizeReached'.",
211
+ -1013: "Internal error: 'RET_ErrAction_HomeReset'.",
212
+ -1014: "Internal error: 'RET_Home_StopReceivedWhileRunning'.",
213
+ -1015: "Internal error: 'RET_UndefinedKinAssembly'.",
214
+ -1016: "Internal error: 'RET_WrongPmcConfig'.",
215
+ }
216
+
217
+
218
+ VALIDATION_LIMITS = [
219
+ "Factory workspace limits",
220
+ "Machine workspace limits",
221
+ "User workspace limits",
222
+ "Actuator limits",
223
+ "Joints limits",
224
+ "Due to backlash compensation",
225
+ ]
226
+
227
+
228
+ def process_cmd_string(command: str) -> str:
229
+ """
230
+ Prepares the command string for sending to the controller.
231
+ A carriage return and newline is appended to the command.
232
+ """
233
+
234
+ return add_cr_lf(command)
235
+
236
+
237
+ def wait_until_cmd_is_zero(transport: DeviceTransport, timeout: float = 1.0, interval: float = 0.01):
238
+ """
239
+ Waits until the `cmd` register is 0 (zero) and returns successfully if it does.
240
+ When the `cmd` register doesn't turn zero within the given timeout, a Failure is returned.
241
+ """
242
+ rc = 0
243
+
244
+ def c_cmd():
245
+ nonlocal rc
246
+ rc_s = transport.query("c_cmd\r\n").decode()
247
+ LOGGER.debug(f"{rc_s = } <- c_cmd in get_pars")
248
+ if not rc_s.startswith("c_cmd"):
249
+ LOGGER.warning(f"{rc_s = }")
250
+ return -1
251
+ rc = int(rc_s.split("\r\n")[1])
252
+ return rc
253
+
254
+ if wait_until(lambda: c_cmd() == 0, interval=interval, timeout=timeout):
255
+ try:
256
+ LOGGER.warning(f"Command check timed out: {RETURN_CODES[rc]} [{rc=}]")
257
+ return Failure(f"Command check resulted in the following error: {RETURN_CODES[rc]}")
258
+ except KeyError:
259
+ return Failure(f"Command check resulted in an unknown error code: {rc = }.")
260
+
261
+ return Success("Command finished successfully")
262
+
263
+
264
+ def get_pars(
265
+ transport: DeviceTransport = None,
266
+ response: bytes = None,
267
+ index: int = 0,
268
+ count: int = 1,
269
+ increment: int = 1,
270
+ timeout: float = 1.0,
271
+ interval: float = 0.01,
272
+ ) -> bytes | Failure:
273
+ """
274
+ Retrieve the response from a given command from the `c_par` array. The `c_par` array will
275
+ contain the correct values only after the `cmd` register is 0 (zero). So, we will wait until
276
+ `cmd` becomes 0, then retrieve the requested parameters from the `c_par` array and return
277
+ them as a normal response to be processed.
278
+
279
+ This function is intended to be used as a `post_cmd` function in the dynamic command decorator.
280
+
281
+ Args:
282
+ transport: the transport interface to communicate with the device
283
+ response: the response from the actual command that was sent
284
+ index: starting index for the `c_par` array
285
+ count: the number of c_par values to retrieve
286
+ increment: the increment in the c_par array
287
+ timeout: the timeout period while waiting for the `cmd` to become 0
288
+ interval: the sampling interval for the `cmd`
289
+
290
+ Returns:
291
+ The requested values from the `c_par` array as a string. This string can be decoded with
292
+ the `decode_pars()` function.
293
+ """
294
+
295
+ if transport is None:
296
+ raise RuntimeError("no device transport was passed into the function!")
297
+
298
+ rc = wait_until_cmd_is_zero(transport=transport, interval=interval, timeout=timeout)
299
+ if isinstance(rc, Failure):
300
+ return rc
301
+
302
+ # The string 'c_par(0),1,1' is considered illegal.
303
+
304
+ if count == 1 and increment == 1:
305
+ query = f"c_par({index})"
306
+ else:
307
+ query = f"c_par({index}),{count},{increment}"
308
+
309
+ response = transport.query(f"{query}\r\n")
310
+
311
+ LOGGER.debug(f"{response = } <- {query} in get_pars")
312
+
313
+ return response
314
+
315
+
316
+ def return_command_status(
317
+ transport: DeviceTransport = None, response: bytes = None, timeout: float = 1.0, interval: float = 0.01
318
+ ) -> Tuple[int, str] | Failure:
319
+ """
320
+ Check the status of last sent command. When the status is zero (0) the command was successfully executed.
321
+ When the status is not zero before timeout seconds, the status check will be aborted and the function
322
+ will then return the latest status code from the `c_cmd` variable.
323
+
324
+ Note: This function shall be used as a `post_cmd` callable in the dynamic_command decorator and the process_response
325
+ shall not be used in conjunction with this command.
326
+
327
+ Args:
328
+ transport: the device transport that can be used send additional commands to the device
329
+ response: The response from the command that was sent to the device (ignored by this function)
330
+ timeout: number of seconds before a timeout will occur
331
+ interval: sleep time between checks for the status condition
332
+
333
+ Returns:
334
+ The status of the last sent command as a tuple (status code, description).
335
+
336
+ Raises:
337
+ A RuntimeError is raised when no device transport is passed into this function.
338
+ """
339
+
340
+ # The response argument is ignored in this function as it generates a new response from the
341
+ # command return code.
342
+
343
+ if transport is None:
344
+ raise RuntimeError("no device transport was passed into the function!")
345
+
346
+ rc = 0
347
+
348
+ def c_cmd():
349
+ nonlocal rc
350
+ rc_s = transport.query("c_cmd\r\n").decode()
351
+ LOGGER.debug(f"{rc_s = } <- c_cmd in check_command_status")
352
+ if not rc_s.startswith("c_cmd"):
353
+ LOGGER.warning(f"{rc_s = }")
354
+ return -1
355
+ rc = int(rc_s.split("\r\n")[1])
356
+ return rc
357
+
358
+ if wait_until(lambda: c_cmd() == 0, interval=interval, timeout=timeout):
359
+ LOGGER.warning(f"Command check: {RETURN_CODES[rc]} [{rc}]")
360
+ else:
361
+ LOGGER.debug("Success!")
362
+ rc = 0
363
+
364
+ return rc, RETURN_CODES[rc]
365
+
366
+
367
+ def check_command_status(
368
+ transport: DeviceTransport = None, response: bytes = None, timeout: float = 1.0, interval: float = 0.01
369
+ ) -> Any:
370
+ """
371
+ Check the state of last sent command. When the state is zero (0) the command was successfully executed. When the
372
+ status is not zero before timeout seconds, the status check will be aborted and a warning message will be issued.
373
+ This function will then return a Failure containing the latest status code from the `c_cmd` variable.
374
+
375
+ The status can take the following values:
376
+
377
+ * > 1: a new command has been written but has not yet been interpreted by the communication application
378
+ * = 1: the last written command is currently under execution
379
+ * = 0: the last command was successfully executed
380
+ * < 0: the last command failed. This status code can be used to determine the cause of the error from
381
+ the RETURN_CODES variable in this module.
382
+
383
+ Note: This function shall be used as a `post_cmd` callable in the dynamic_command decorator.
384
+
385
+ Args:
386
+ transport: the device transport that can be used send additional commands to the device
387
+ response: The response from the command that was sent to the device
388
+ timeout: number of seconds before a timeout will occur
389
+ interval: sleep time between checks for the status condition
390
+
391
+ Returns:
392
+ This function passes through the response without change. When the status check timed out
393
+ a Failure will be returned with an associated error message.
394
+
395
+ Raises:
396
+ A RuntimeError is raised when no device transport is passed into this function.
397
+ """
398
+ if transport is None:
399
+ raise RuntimeError("no device transport was passed into the function!")
400
+
401
+ rc = wait_until_cmd_is_zero(transport=transport, interval=interval, timeout=timeout)
402
+ return rc if isinstance(rc, Failure) else response
403
+
404
+
405
+ def decode_response(response: bytes) -> str | Failure:
406
+ """Decodes the bytes object, strips off the trailing 'CRLF'."""
407
+
408
+ LOGGER.debug(f"{response = } <- decode_response")
409
+
410
+ return response.decode().rstrip()
411
+
412
+
413
+ def validate_response(response: str, cmd: str = None) -> List[str] | Failure:
414
+ """
415
+ Performs a number of checks on the response string and returns the response as a list of strings.
416
+ The command string (which is the first part of the device response) is removed from the returned list.
417
+
418
+ Args:
419
+ response: decoded response from the device
420
+ cmd: the command string that is returned by the device
421
+
422
+ Returns:
423
+ A list of strings containing the split response without the first item (which was the command string).
424
+ If the response contains the string 'error #', a Failure will be returned with the error message.
425
+ If the response doesn't start with the given command string (when cmd != None), a Failure is returned.
426
+ """
427
+ if "error #" in response:
428
+ msg = response.split("\r\n")[-1] # this will strip off the cmd part of the response
429
+ return Failure(msg)
430
+
431
+ if cmd is not None and not response.startswith(cmd):
432
+ return Failure(f"Unexpected response from '{cmd}' command: {response}")
433
+
434
+ LOGGER.debug(f"{response = } <- validate_response")
435
+
436
+ return response.split("\r\n")[1:]
437
+
438
+
439
+ def process_response(response: bytes, cmd: str = None) -> List[str] | Failure:
440
+ """This function is a shortcut for decode_response() and validate_response()."""
441
+
442
+ # You might think this shortcut is really useless and doesn't give us anything,
443
+ # the thing is that this function is used in the decorator, which is not possible
444
+ # for each function individually.
445
+
446
+ return validate_response(decode_response(response), cmd)
447
+
448
+
449
+ def process_validate_ptp(response: bytes) -> Tuple[int, Dict[int, str]] | Failure:
450
+ """
451
+ The response is in this case the value of 'c_par(0)' which is returned by the `post_cmd` function `get_pars`.
452
+
453
+ Args:
454
+ response:
455
+
456
+ Returns:
457
+
458
+ """
459
+ response = process_response(response)
460
+
461
+ if isinstance(response, Failure):
462
+ return response
463
+
464
+ response = int(response[0])
465
+
466
+ if response == 0:
467
+ return 0, {}
468
+
469
+ if response > 0:
470
+ description = decode_validation_error(response)
471
+ return response, description
472
+
473
+ # When response is negative, the validation failed, and we extract the command return code
474
+
475
+ msg = f"{RETURN_CODES.get(response, 'unknown error code')}"
476
+
477
+ LOGGER.error(f"Validate position: error code={response} - {msg}")
478
+
479
+ return response, {response: msg}
480
+
481
+
482
+ def issue_warning(*, response, msg: str):
483
+ LOGGER.warning(f"{msg} {response}")
484
+ return response
485
+
486
+
487
+ from typing import TypeVar
488
+
489
+ T = TypeVar("T", float, int) # Declare type variable
490
+
491
+
492
+ def decode_pars(response: bytes = None, index: int = 0, count: int = 1, func: Callable = float) -> List[T] | Failure:
493
+ response = process_response(response)
494
+
495
+ if isinstance(response, Failure):
496
+ return response
497
+
498
+ return [func(x) for x in response[index : index + count]]
499
+
500
+
501
+ def decode_info(response: bytes) -> str | Failure:
502
+ response = process_response(response)
503
+
504
+ if isinstance(response, Failure):
505
+ return response
506
+
507
+ LOGGER.debug(f"{response = } <- decode_info")
508
+
509
+ return (
510
+ f"Info about the Hexapod Alpha+ Controller:\n"
511
+ f" Software version = {response[1]}.{response[2]}.{response[3]}.{response[4]}\n"
512
+ f" API version = {response[5]}.{response[6]}.{response[7]}.{response[8]}\n"
513
+ f" System Configuration version = {response[11]}"
514
+ )
515
+
516
+
517
+ def decode_version(response: bytes) -> str | Failure:
518
+ response = validate_response(decode_response(response))
519
+
520
+ if isinstance(response, Failure):
521
+ return response
522
+
523
+ return f"{response[5]}.{response[6]}.{response[7]}.{response[8]}"
524
+
525
+
526
+ def decode_uto(response: bytes) -> List[float] | Failure:
527
+ response = validate_response(decode_response(response), "s_uto")
528
+
529
+ if isinstance(response, Failure):
530
+ return response
531
+
532
+ return [float(x) for x in response]
533
+
534
+
535
+ def decode_mtp(response: bytes) -> List[float] | Failure:
536
+ response = validate_response(decode_response(response), "s_mtp")
537
+
538
+ if isinstance(response, Failure):
539
+ return response
540
+
541
+ return [float(x) for x in response]
542
+
543
+
544
+ def decode_general_state(response: bytes) -> Tuple[Dict, List] | Failure:
545
+ response = validate_response(decode_response(response), "s_hexa")
546
+
547
+ if isinstance(response, Failure):
548
+ return response
549
+
550
+ response = int(response[0])
551
+
552
+ LOGGER.debug(f"{response = } <- decode_general_state")
553
+
554
+ s_hexa = [int(x) for x in f"{response:015b}"[::-1]]
555
+ state = dict(zip(GENERAL_STATE, s_hexa))
556
+
557
+ return state, list(state.values())
558
+
559
+
560
+ def decode_actuator_state(response: bytes) -> Tuple[Tuple[Dict, List]] | Failure:
561
+ response = validate_response(decode_response(response), "s_ax")
562
+
563
+ if isinstance(response, Failure):
564
+ return response
565
+
566
+ def decode_state(state: int) -> Tuple[Dict, List]:
567
+ state_bits = [int(x) for x in f"{state:015b}"[::-1]]
568
+ state_dict = dict(zip(ACTUATOR_STATE, state_bits))
569
+ return state_dict, state_bits
570
+
571
+ actuator_states = [int(x) for x in response]
572
+
573
+ return tuple(decode_state(state) for state in actuator_states)
574
+
575
+
576
+ def decode_validation_error(value) -> Dict:
577
+ """
578
+ Decode the bitfield variable that is returned by the VALID_PTP command.
579
+
580
+ Each bit in this variable represents a particular error in the validation of a movement.
581
+ Several errors can be combined into the given variable.
582
+
583
+ Returns a dictionary with the bit numbers that were (on) and the corresponding error description.
584
+ """
585
+
586
+ return {bit: VALIDATION_LIMITS[bit] for bit in range(6) if value >> bit & 0b01}
587
+
588
+
589
+ class AlphaPlusTelnetInterface(DeviceTransport, DeviceConnectionInterface):
590
+ """
591
+ The Hexapod controller device interface based on the telnet protocol. This class implements the
592
+ DeviceTransport protocol which provides the `read()`, `write()`, `trans()`, and `query()` methods.
593
+ """
594
+
595
+ TELNET_TIMEOUT = 1.0
596
+
597
+ def __init__(self, hostname: str = "localhost", port: int = 23):
598
+ """
599
+ Args:
600
+ hostname (str): the IP address or fully qualified hostname of the OGSE hardware
601
+ controller. The default is 'localhost'.
602
+ port (int): the IP port number to connect to. The default is 23.
603
+ """
604
+ super().__init__()
605
+ self.telnet = Telnet()
606
+ self._is_connected = False
607
+ self.hostname = hostname
608
+ self.port = port
609
+
610
+ def connect(self) -> None:
611
+ """
612
+ Connects to the Alpha+ Controller using the Telnet protocol. After connection
613
+ the telnet session logs in with the username provided in the Settings file. The password for this login is also
614
+ provided in the Settings under the same group. Make sure their values are only given in
615
+ the local settings file, not the global settings.
616
+
617
+ After login, the `gpascii` command is started with the option `-2` as instructed
618
+ in the software manual of the controller. The first command sent then is the
619
+ `echo7` command, which configures the system to return variable numbers only,
620
+ not their variable names.
621
+ """
622
+ try:
623
+ self.telnet.open(self.hostname, self.port)
624
+ except ConnectionRefusedError as exc:
625
+ raise DeviceConnectionError(
626
+ device_name="Alpha+ Controller", message=f"Connection refused to {self.hostname} port {self.port}"
627
+ ) from exc
628
+
629
+ try:
630
+ rc = self.telnet.read_until(b"login: ", timeout=self.TELNET_TIMEOUT)
631
+ # print(rc.decode(), flush=True, end="")
632
+ self.telnet.write(f"{PUNA_PLUS.user_name}\r\n".encode())
633
+ rc = self.telnet.read_until(b"Password: ", timeout=self.TELNET_TIMEOUT)
634
+ # print(rc.decode(), flush=True, end="")
635
+ self.telnet.write(f"{PUNA_PLUS.password}\r\n".encode())
636
+ rc = self.telnet.read_until(b"ppmac# ", timeout=self.TELNET_TIMEOUT)
637
+ # print(rc.decode(), flush=True, end="")
638
+ self.telnet.write(b"gpascii -2\r\n")
639
+ rc = self.telnet.read_until(b"\x06\r\n", timeout=self.TELNET_TIMEOUT)
640
+ # print(rc.decode(), flush=True, end="")
641
+ self.telnet.write(b"echo7\r\n")
642
+ rc = self.telnet.read_until(b"\x06\r\n", timeout=self.TELNET_TIMEOUT)
643
+ # print(rc.decode(), flush=True, end="")
644
+ except EOFError as exc:
645
+ raise DeviceConnectionError(
646
+ device_name="Alpha+ Controller",
647
+ message=f"Telnet connection closed for {self.hostname} port {self.port}",
648
+ ) from exc
649
+
650
+ self._is_connected = True
651
+
652
+ def is_connected(self):
653
+ return self._is_connected
654
+
655
+ def disconnect(self):
656
+ rc = self.telnet.read_very_eager()
657
+ print(rc.decode(), flush=True, end="")
658
+ self.telnet.close()
659
+ self._is_connected = False
660
+
661
+ def reconnect(self):
662
+ if self._is_connected:
663
+ self.disconnect()
664
+ self.connect()
665
+
666
+ def trans(self, cmd: str) -> bytes:
667
+ """
668
+ Send a command to the Aplha+ Controller and waits for a response.
669
+ The response is returned after the ACK is stripped off (see `read()` method).
670
+
671
+ Args:
672
+ cmd: a valid command string for the Alpha+ Controller
673
+
674
+ Returns:
675
+ The response from the controller on the command that was sent.
676
+ """
677
+ self.write(cmd)
678
+ response = self.read()
679
+
680
+ LOGGER.debug(f"trans: {response = }")
681
+
682
+ return response
683
+
684
+ def read(self) -> bytes:
685
+ """
686
+ Reads a response from the controller.
687
+
688
+ Note: The acknowledgement `\x06\r\n` is stripped from the response before it is
689
+ returned. If no ACK is present, a warning message will be logged.
690
+
691
+ Returns:
692
+ The response from the controller on a previously sent command.
693
+ """
694
+
695
+ response = self.telnet.read_until(b"\x06\r\n", timeout=self.TELNET_TIMEOUT)
696
+
697
+ LOGGER.debug(f"read: {response = }")
698
+
699
+ if not response.endswith(b"\x06\r\n"):
700
+ LOGGER.warning(f"Expected ACK at the end of the response, {response = }")
701
+ return response
702
+
703
+ return response[:-3] # strip off the ACK
704
+
705
+ def write(self, cmd: str):
706
+ """
707
+ Sends a command string to the Alpha+ Controller.
708
+ The command string shall not end with a CRLF, that is automatically appended
709
+ by this function.
710
+
711
+ Args:
712
+ cmd: a valid command string for the Alpha+ Controller
713
+
714
+ Returns:
715
+ Nothing is returned.
716
+ """
717
+ LOGGER.debug(f"Executing: {cmd.rstrip()}")
718
+ self.telnet.write(cmd.encode())
719
+
720
+
721
+ class AlphaControllerInterface(DeviceInterface):
722
+ @dynamic_command(
723
+ cmd_type="transaction",
724
+ cmd_string="c_cmd=C_STOP",
725
+ process_cmd_string=process_cmd_string,
726
+ process_response=partial(issue_warning, msg="STOP command has been executed."),
727
+ post_cmd=return_command_status,
728
+ )
729
+ def stop(self) -> Tuple[int, str] | Failure:
730
+ """
731
+ Stop the current motion. This command can be sent during a motion of the Hexapod
732
+ and is executed with high priority.
733
+
734
+ Returns:
735
+ A tuple (return code, description). Return code = 0 on success.
736
+ """
737
+ raise NotImplementedError
738
+
739
+ @dynamic_command(
740
+ cmd_type="transaction",
741
+ cmd_string="c_cmd=C_CONTROLON",
742
+ process_cmd_string=process_cmd_string,
743
+ post_cmd=return_command_status,
744
+ )
745
+ def activate_control_loop(self):
746
+ """
747
+ Activates the control loop on motors.
748
+
749
+ It activates the power on the motors and releases the brakes if present.
750
+ The hexapod status 'Control On' will switch to true when the command is successful.
751
+
752
+ This command should be used before starting a movement.
753
+
754
+ Note: it is possible to activate the control loop on motors even if the home is not complete.
755
+ """
756
+ raise NotImplementedError
757
+
758
+ @dynamic_command(
759
+ cmd_type="transaction",
760
+ cmd_string="c_cmd=C_CONTROLOFF",
761
+ process_cmd_string=process_cmd_string,
762
+ post_cmd=return_command_status,
763
+ )
764
+ def deactivate_control_loop(self):
765
+ """
766
+ Disables the control loop on the servo motors.
767
+
768
+ It is advisable to disable the servo motors if the system is not used for
769
+ a long period (more than 1 hour for example). However, this recommendation
770
+ depends on the application for which the system is being used.
771
+
772
+ This command is performed only if the following conditions are met:
773
+ * there is no motion task running
774
+ * there is no action running
775
+ """
776
+ raise NotImplementedError
777
+
778
+ @dynamic_command(
779
+ cmd_type="transaction",
780
+ cmd_string="c_cmd=C_HOME",
781
+ process_cmd_string=process_cmd_string,
782
+ process_response=process_response,
783
+ )
784
+ def homing(self):
785
+ """
786
+ Starts the homing task on the hexapod.
787
+
788
+ Homing needs to be completed before performing any movement. When the hexapod
789
+ is equipped with absolute encoders, this cycle is executed automatically during
790
+ the controller initialization. When the hexapod is not equipped with absolute
791
+ encoders, the homing request movements: homing cycle will search actuators
792
+ reference sensors.
793
+
794
+ Homing is required before performing a control movement. Without absolute encoders,
795
+ the homing is performed with a hexapod movement until detecting the reference sensor
796
+ on each of the actuators. The Hexapod will go to a position were the sensors are
797
+ reached that signal a known calibrated position and then returns to the zero position.
798
+
799
+ Whenever a homing is performed, the method will return before the actual movement
800
+ is finished.
801
+
802
+ The homing cycle takes about two minutes to complete, but the ``homing()`` method
803
+ returns almost immediately. Therefore, to check if the homing is finished, use
804
+ the is_homing_done() method.
805
+
806
+ This command is performed only if the following conditions are met:
807
+ * there is no motion task running
808
+ * the emergency stop button is not engaged (not applicable for absolute encoders)
809
+
810
+ """
811
+ raise NotImplementedError
812
+
813
+ def is_homing_done(self) -> bool | Failure:
814
+ """
815
+ Checks if Homing is done.
816
+
817
+ When this variable indicates 'Homing is done' it means the command has been properly
818
+ executed, but it doesn't mean the Hexapod is in position. The hexapod might still be
819
+ moving to its zero position.
820
+
821
+ Returns:
822
+ True when the homing is done, False otherwise.
823
+ """
824
+ general_state = self.get_general_state()
825
+ if isinstance(general_state, Failure):
826
+ return general_state
827
+
828
+ return bool(general_state[1][HOME_COMPLETE])
829
+
830
+ def is_in_position(self) -> bool | Failure:
831
+ """
832
+ Checks if the hexapod is in position.
833
+
834
+ Returns:
835
+ True when in position, False otherwise.
836
+ """
837
+ general_state = self.get_general_state()
838
+ if isinstance(general_state, Failure):
839
+ return general_state
840
+
841
+ return bool(general_state[1][IN_POSITION]) and not bool(general_state[1][IN_MOTION])
842
+
843
+ @dynamic_command(
844
+ cmd_type="transaction",
845
+ cmd_string="c_cmd=C_CLEARERROR",
846
+ process_cmd_string=process_cmd_string,
847
+ post_cmd=return_command_status,
848
+ )
849
+ def clear_error(self) -> Tuple[int, str] | Failure:
850
+ """
851
+ Clear all errors in the controller software.
852
+
853
+ This command clears the error list on the controller and automatically removes the error bit of the hexapod
854
+ state. After this command, errors might automatically be regenerated if they are still present. For example,
855
+ if an encoder is disconnected, the encoder error will be re-generated after the command because error reason
856
+ is not corrected.
857
+
858
+ Returns:
859
+ The command status is returned as a tuple with (return code, message).
860
+ """
861
+ raise NotImplementedError
862
+
863
+ @dynamic_command(
864
+ cmd_type="transaction",
865
+ cmd_string="c_cfg=1 "
866
+ "c_par(0)=${tx_u} c_par(1)=${ty_u} c_par(2)=${tz_u} "
867
+ "c_par(3)=${rx_u} c_par(4)=${ry_u} c_par(5)=${rz_u} "
868
+ "c_par(6)=${tx_o} c_par(7)=${ty_o} c_par(8)=${tz_o} "
869
+ "c_par(9)=${rx_o} c_par(10)=${ry_o} c_par(11)=${rz_o} "
870
+ "c_cmd=C_CFG_CS",
871
+ process_cmd_string=process_cmd_string,
872
+ post_cmd=return_command_status,
873
+ )
874
+ def configure_coordinates_systems(
875
+ self, tx_u, ty_u, tz_u, rx_u, ry_u, rz_u, tx_o, ty_o, tz_o, rx_o, ry_o, rz_o
876
+ ) -> Tuple[int, str] | Failure:
877
+ """
878
+ Change the definition of the User Coordinate System and the Object Coordinate System.
879
+
880
+ The parameters tx_u, ty_u, tz_u, rx_u, ry_u, rz_u are used to define the user coordinate
881
+ system relative to the Machine Coordinate System and the parameters tx_o, ty_o, tz_o, rx_o,
882
+ ry_o, rz_o are used to define the Object Coordinate System relative to the Platform
883
+ Coordinate System.
884
+
885
+ Args:
886
+ tx_u (float): translation parameter that define the user coordinate system relative
887
+ to the machine coordinate system [in mm]
888
+ ty_u (float): translation parameter that define the user coordinate system relative
889
+ to the machine coordinate system [in mm]
890
+ tz_u (float): translation parameter that define the user coordinate system relative
891
+ to the machine coordinate system [in mm]
892
+
893
+ rx_u (float): rotation parameter that define the user coordinate system relative to
894
+ the machine coordinate system [in deg]
895
+ ry_u (float): rotation parameter that define the user coordinate system relative to
896
+ the machine coordinate system [in deg]
897
+ rz_u (float): rotation parameter that define the user coordinate system relative to
898
+ the machine coordinate system [in deg]
899
+
900
+ tx_o (float): translation parameter that define the object coordinate system relative
901
+ to the platform coordinate system [in mm]
902
+ ty_o (float): translation parameter that define the object coordinate system relative
903
+ to the platform coordinate system [in mm]
904
+ tz_o (float): translation parameter that define the object coordinate system relative
905
+ to the platform coordinate system [in mm]
906
+
907
+ rx_o (float): rotation parameter that define the object coordinate system relative to
908
+ the platform coordinate system [in deg]
909
+ ry_o (float): rotation parameter that define the object coordinate system relative to
910
+ the platform coordinate system [in deg]
911
+ rz_o (float): rotation parameter that define the object coordinate system relative to
912
+ the platform coordinate system [in deg]
913
+
914
+ Returns:
915
+ A tuple with the command status return code and a description.
916
+ """
917
+ raise NotImplementedError
918
+
919
+ @dynamic_command(
920
+ cmd_type="query",
921
+ cmd_string="c_cfg=0 c_cmd=C_CFG_CS",
922
+ process_cmd_string=process_cmd_string,
923
+ process_response=partial(decode_pars, count=12),
924
+ post_cmd=partial(get_pars, count=12),
925
+ )
926
+ def get_coordinates_systems(self):
927
+ """
928
+ Retrieve the definition of the User Coordinate System and the Object Coordinate System.
929
+
930
+ Returns:
931
+ tx_u, ty_u, tz_u, rx_u, ry_u, rz_u, tx_o, ty_o, tz_o, rx_o, ry_o, rz_o where the
932
+ translation parameters are in [mm] and the rotation parameters are in [deg].
933
+ """
934
+ raise NotImplementedError
935
+
936
+ @dynamic_command(
937
+ cmd_type="transaction",
938
+ cmd_string="c_par(0)=${cm} "
939
+ "c_par(1)=${tx} c_par(2)=${ty} c_par(3)=${tz} "
940
+ "c_par(4)=${rx} c_par(5)=${ry} c_par(6)=${rz} "
941
+ "c_cmd=C_MOVE_PTP",
942
+ process_cmd_string=process_cmd_string,
943
+ post_cmd=return_command_status,
944
+ )
945
+ def move_ptp(
946
+ self, cm: int, tx: float, ty: float, tz: float, rx: float, ry: float, rz: float
947
+ ) -> Tuple[int, str] | Failure:
948
+ """
949
+ Start the movement as defined by the arguments.
950
+
951
+ Args:
952
+ cm: control mode, 0=absolute, 1=object relative, 2=user relative
953
+ tx: position on X-axis [mm]
954
+ ty: position on Y-axis [mm]
955
+ tz: position on Z-axis [mm]
956
+ rx: rotation around the X-axis [deg]
957
+ ry: rotation around the Y-axis [deg]
958
+ rz: rotation around the Z-axis [deg]
959
+
960
+ Returns:
961
+
962
+ """
963
+ raise NotImplementedError
964
+
965
+ def move_absolute(self, tx, ty, tz, rx, ry, rz) -> Tuple[int, str] | Failure:
966
+ return self.move_ptp(0, tx, ty, tz, rx, ry, rz)
967
+
968
+ def move_relative_object(self, tx, ty, tz, rx, ry, rz) -> Tuple[int, str] | Failure:
969
+ return self.move_ptp(1, tx, ty, tz, rx, ry, rz)
970
+
971
+ def move_relative_user(self, tx, ty, tz, rx, ry, rz) -> Tuple[int, str] | Failure:
972
+ return self.move_ptp(2, tx, ty, tz, rx, ry, rz)
973
+
974
+ @dynamic_command(
975
+ cmd_type="transaction",
976
+ cmd_string="c_par(0)=${pos} c_cmd=C_MOVE_SPECIFICPOS",
977
+ process_cmd_string=process_cmd_string,
978
+ # process_response=process_response,
979
+ post_cmd=return_command_status,
980
+ )
981
+ def goto_specific_position(self, pos: int):
982
+ raise NotImplementedError
983
+
984
+ def goto_user_zero_position(self):
985
+ return self.goto_specific_position(pos=1)
986
+
987
+ def goto_retracted_position(self):
988
+ return self.goto_specific_position(pos=2)
989
+
990
+ def goto_machine_zero_position(self):
991
+ return self.goto_specific_position(pos=3)
992
+
993
+ goto_zero_position = goto_user_zero_position
994
+
995
+ @dynamic_command(
996
+ cmd_type="transaction",
997
+ cmd_string="s_uto_tx,6,1",
998
+ process_cmd_string=process_cmd_string,
999
+ process_response=decode_uto,
1000
+ )
1001
+ def get_user_positions(self):
1002
+ raise NotImplementedError
1003
+
1004
+ @dynamic_command(
1005
+ cmd_type="transaction",
1006
+ cmd_string="s_mtp_tx,6,1",
1007
+ process_cmd_string=process_cmd_string,
1008
+ process_response=decode_mtp,
1009
+ )
1010
+ def get_machine_positions(self) -> List[float] | Failure:
1011
+ raise NotImplementedError
1012
+
1013
+ @dynamic_command(
1014
+ cmd_type="query",
1015
+ cmd_string="c_cmd=C_VERSION",
1016
+ process_cmd_string=process_cmd_string,
1017
+ process_response=decode_info,
1018
+ post_cmd=partial(get_pars, count=12),
1019
+ )
1020
+ def info(self) -> str:
1021
+ """Returns basic information about the hexapod and the controller.
1022
+
1023
+ Returns:
1024
+ a multiline response message containing the device info.
1025
+ """
1026
+ raise NotImplementedError
1027
+
1028
+ @dynamic_command(
1029
+ cmd_type="query",
1030
+ cmd_string="c_cmd=C_VERSION",
1031
+ process_cmd_string=process_cmd_string,
1032
+ process_response=decode_version,
1033
+ post_cmd=partial(get_pars, count=12),
1034
+ )
1035
+ def version(self) -> str:
1036
+ """Returns the version of the firmware running on the hexapod aplha+ controller.
1037
+
1038
+ Returns:
1039
+ A version number as a string.
1040
+ """
1041
+ raise NotImplementedError
1042
+
1043
+ @dynamic_command(
1044
+ cmd_type="transaction",
1045
+ cmd_string="s_hexa",
1046
+ process_cmd_string=process_cmd_string,
1047
+ process_response=decode_general_state,
1048
+ )
1049
+ def get_general_state(self) -> Tuple[Dict, List] | Failure:
1050
+ """
1051
+ Asks the general state of the hexapod on all the motors following the bits definition
1052
+ presented below.
1053
+
1054
+ GENERAL_STATE =
1055
+ 0: "Error",
1056
+ 1: "System initialized",
1057
+ 2: "Control on",
1058
+ 3: "In position",
1059
+ 4: "Motion task running",
1060
+ 5: "Home task running",
1061
+ 6: "Home complete",
1062
+ 7: "Home virtual",
1063
+ 8: "Phase found",
1064
+ 9: "Brake on",
1065
+ 10:"Motion restricted",
1066
+ 11:"Power on encoders",
1067
+ 12:"Power on limit switches",
1068
+ 13:"Power on drives",
1069
+ 14:"Emergency stop"
1070
+
1071
+ Returns:
1072
+ A dictionary with the bits value of each parameter.
1073
+ """
1074
+ raise NotImplementedError
1075
+
1076
+ @dynamic_command(
1077
+ cmd_type="transaction",
1078
+ cmd_string="s_ax_1,6,1",
1079
+ process_cmd_string=process_cmd_string,
1080
+ process_response=decode_actuator_state,
1081
+ )
1082
+ def get_actuator_state(self) -> Tuple[Dict, List] | Failure:
1083
+ raise NotImplementedError
1084
+
1085
+ @dynamic_command(
1086
+ cmd_type="query",
1087
+ cmd_string="s_pos_ax_1,6,1",
1088
+ process_cmd_string=process_cmd_string,
1089
+ process_response=partial(decode_pars, count=6, func=float),
1090
+ )
1091
+ def get_actuator_length(self):
1092
+ """
1093
+ Retrieve the current length of the hexapod actuators.
1094
+
1095
+ Returns:
1096
+ array: an array of six float values for actuator length L1 to L6 in [mm], and \
1097
+ None: when an Exception was raised and logs the error message.
1098
+ """
1099
+ raise NotImplementedError
1100
+
1101
+ @dynamic_command(
1102
+ cmd_type="query",
1103
+ cmd_string="c_cfg=0 c_cmd=C_CFG_SPEED",
1104
+ process_cmd_string=process_cmd_string,
1105
+ process_response=partial(decode_pars, count=6),
1106
+ post_cmd=partial(get_pars, count=6),
1107
+ )
1108
+ def get_speed(self) -> List[float]:
1109
+ """
1110
+ Returns the positional speed of movements.
1111
+
1112
+ Returns a list of floating point numbers [vt, vr, vt-, vr-, vt+, vr+] where vt and vr are the translation and
1113
+ angular speed respectively, the '-' and '+' are the minimum and maximum speeds.
1114
+ """
1115
+ raise NotImplementedError
1116
+
1117
+ @dynamic_command(
1118
+ cmd_type="transaction",
1119
+ cmd_string="c_cfg=1 c_par(0)=${vt} c_par(1)=${vr} c_cmd=C_CFG_SPEED",
1120
+ process_cmd_string=process_cmd_string,
1121
+ post_cmd=return_command_status,
1122
+ )
1123
+ def set_speed(self, vt: float, vr: float):
1124
+ """
1125
+ Set the positioning speed of movements.
1126
+
1127
+ Args:
1128
+ vt: translational speed, unit = mm per second
1129
+ vr: angular speed, unit = deg per second
1130
+ """
1131
+ raise NotImplementedError
1132
+
1133
+ @dynamic_command(
1134
+ cmd_type="transaction",
1135
+ cmd_string="c_par(0)=${vm} c_par(1)=${cm} "
1136
+ "c_par(2)=${tx} c_par(3)=${ty} c_par(4)=${tz} "
1137
+ "c_par(5)=${rx} c_par(6)=${ry} c_par(7)=${rz} "
1138
+ "c_cmd=C_VALID_PTP",
1139
+ process_cmd_string=process_cmd_string,
1140
+ process_response=process_validate_ptp,
1141
+ post_cmd=get_pars,
1142
+ )
1143
+ def validate_position(self, vm, cm, tx, ty, tz, rx, ry, rz) -> Tuple[int, Dict[int, str]] | Failure:
1144
+ """
1145
+ Ask the controller if the movement defined by the arguments is feasible.
1146
+
1147
+ Returns a tuple where the first element is an integer that represents the
1148
+ bitfield encoding the errors. The second element is a dictionary with the
1149
+ bit numbers that were (on) and the corresponding error description as
1150
+ defined by VALIDATION_LIMITS.
1151
+
1152
+ Args:
1153
+ vm (int): validation mode [only vm=1 is currently implemented by Symétrie]
1154
+ cm (int): control mode (0 = absolute, 1 = object relative, 2 = user relative)
1155
+ tx (float): position on the X-axis [mm]
1156
+ ty (float): position on the Y-axis [mm]
1157
+ tz (float): position on the Z-axis [mm]
1158
+ rx (float): rotation around the X-axis [deg]
1159
+ ry (float): rotation around the Y-axis [deg]
1160
+ rz (float): rotation around the Z-axis [deg]
1161
+
1162
+ """
1163
+ raise NotImplementedError
1164
+
1165
+ def check_absolute_movement(self, tx, ty, tz, rx, ry, rz) -> Tuple[int, Dict[int, str]] | Failure:
1166
+ """
1167
+ Check if the requested object movement is valid.
1168
+
1169
+ The absolute movement is expressed in the user coordinate system.
1170
+
1171
+ Args:
1172
+ tx (float): position on the X-axis [mm]
1173
+ ty (float): position on the Y-axis [mm]
1174
+ tz (float): position on the Z-axis [mm]
1175
+ rx (float): rotation around the X-axis [deg]
1176
+ ry (float): rotation around the Y-axis [deg]
1177
+ rz (float): rotation around the Z-axis [deg]
1178
+
1179
+ Returns:
1180
+ tuple: where the first element is an integer that represents the
1181
+ bitfield encoding the errors. The second element is a dictionary
1182
+ with the bit numbers that were (on) and the corresponding error
1183
+ description.
1184
+ """
1185
+ # Currently only the vm=1 mode is developed by Symétrie
1186
+ # Parameter cm = 0 for absolute
1187
+ return self.validate_position(1, 0, tx, ty, tz, rx, ry, rz)
1188
+
1189
+ def check_relative_object_movement(self, tx, ty, tz, rx, ry, rz) -> Tuple[int, Dict[int, str]] | Failure:
1190
+ """
1191
+ Check if the requested object movement is valid.
1192
+
1193
+ The relative motion is expressed in the object coordinate system.
1194
+
1195
+ Args:
1196
+ tx (float): position on the X-axis [mm]
1197
+ ty (float): position on the Y-axis [mm]
1198
+ tz (float): position on the Z-axis [mm]
1199
+ rx (float): rotation around the X-axis [deg]
1200
+ ry (float): rotation around the Y-axis [deg]
1201
+ rz (float): rotation around the Z-axis [deg]
1202
+
1203
+ Returns:
1204
+ tuple: where the first element is an integer that represents the
1205
+ bitfield encoding the errors. The second element is a dictionary
1206
+ with the bit numbers that were (on) and the corresponding error
1207
+ description.
1208
+ """
1209
+ # Currently only the vm=1 mode is developed by Symétrie
1210
+ # Parameter cm = 1 for object relative
1211
+ return self.validate_position(1, 1, tx, ty, tz, rx, ry, rz)
1212
+
1213
+ def check_relative_user_movement(self, tx, ty, tz, rx, ry, rz) -> Tuple[int, Dict[int, str]] | Failure:
1214
+ """
1215
+ Check if the requested object movement is valid.
1216
+
1217
+ The relative motion is expressed in the user coordinate system.
1218
+
1219
+ Args:
1220
+ tx (float): position on the X-axis [mm]
1221
+ ty (float): position on the Y-axis [mm]
1222
+ tz (float): position on the Z-axis [mm]
1223
+ rx (float): rotation around the X-axis [deg]
1224
+ ry (float): rotation around the Y-axis [deg]
1225
+ rz (float): rotation around the Z-axis [deg]
1226
+
1227
+ Returns:
1228
+ tuple: where the first element is an integer that represents the
1229
+ bitfield encoding the errors. The second element is a dictionary
1230
+ with the bit numbers that were (on) and the corresponding error
1231
+ description.
1232
+ """
1233
+ # Currently only the vm=1 mode is developed by Symétrie
1234
+ # Parameter cm = 2 for user relative
1235
+ return self.validate_position(1, 2, tx, ty, tz, rx, ry, rz)
1236
+
1237
+
1238
+ class AlphaPlusControllerInterface(AlphaControllerInterface):
1239
+ @dynamic_command(
1240
+ cmd_type="query",
1241
+ cmd_string="${name}",
1242
+ process_cmd_string=process_cmd_string,
1243
+ process_response=process_response,
1244
+ )
1245
+ def query_variable(self, name: str) -> str:
1246
+ raise NotImplementedError
1247
+
1248
+ @dynamic_command(
1249
+ cmd_type="query",
1250
+ cmd_string="${name},${count},${increment}",
1251
+ process_cmd_string=process_cmd_string,
1252
+ process_response=process_response,
1253
+ )
1254
+ def query_variables(self, name: str, count: int, increment: int = 1):
1255
+ raise NotImplementedError
1256
+
1257
+ @dynamic_command(
1258
+ cmd_type="query",
1259
+ cmd_string="${name}(${idx})",
1260
+ process_cmd_string=process_cmd_string,
1261
+ process_response=process_response,
1262
+ )
1263
+ def query_array(self, name: str, idx: int):
1264
+ raise NotImplementedError
1265
+
1266
+ @dynamic_command(
1267
+ cmd_type="query",
1268
+ cmd_string="${name}(${idx}),${count},${increment}",
1269
+ process_cmd_string=process_cmd_string,
1270
+ process_response=process_response,
1271
+ )
1272
+ def query_array_values(self, name: str, idx: int, count: int, increment: int = 1):
1273
+ raise NotImplementedError
1274
+
1275
+ @dynamic_command(
1276
+ cmd_type="transaction",
1277
+ cmd_string="c_cfg=0 c_par(0)=${lim} c_cmd=C_CFG_LIMIT",
1278
+ process_cmd_string=process_cmd_string,
1279
+ process_response=partial(decode_pars, index=1, count=12),
1280
+ post_cmd=partial(get_pars, count=13),
1281
+ )
1282
+ def get_limits_value(self, lim):
1283
+ """
1284
+ Three different and independent operational workspace limits are defined on the controller:
1285
+
1286
+ * Factory limits: are expressed in machine coordinate system limits. Those parameters cannot be modified.
1287
+ * Machine coordinate system limits: they are expressed in the Machine coordinate system. It can be used to
1288
+ secure the hexapod (and/or object) from its environment.
1289
+ * User coordinate system limits: they are expressed in the User coordinate system. It can be used to limits
1290
+ the movements of the object mounted on hexapod.
1291
+
1292
+ Remark: operational workspace limits must be understood as limits in terms of amplitude of movement. Those
1293
+ limits are defined for each operational axis with a negative and positive value and are used in the validation
1294
+ process. Position on each operational axis must be within those two values.
1295
+
1296
+ Args:
1297
+ lim (int): 0 = factory (GET only), 1 = machine cs limit, 2 = user cs limit
1298
+
1299
+ Returns:
1300
+ A list of 12 float values: tx-, ty-, tz-, rx-, ry-, rz-, tx+, ty+, tz+, rx+, ry+, rz+
1301
+ The first six values are the negative limits for translation and rotation, the last six numbers are the
1302
+ positive limits for translation and rotation.
1303
+
1304
+ """
1305
+ raise NotImplementedError
1306
+
1307
+
1308
+ if __name__ == "__main__":
1309
+ from rich import print as rp
1310
+
1311
+ from egse.hexapod.symetrie.punaplus import PunaPlusController
1312
+
1313
+ # Thie IP address for the emulator running in VirtualBox is 192.168.56.10
1314
+ # When you run the emulator in Parallels, the IP address is 10.37.129.10
1315
+
1316
+ puna = PunaPlusController(hostname="10.37.129.10", port=23)
1317
+ puna.connect()
1318
+
1319
+ with Timer("PunaPlusController"):
1320
+ rp(puna.info())
1321
+ rp(puna.version())
1322
+ rp(puna.is_homing_done())
1323
+ rp(puna.homing())
1324
+ if wait_until(puna.is_homing_done, interval=1, timeout=300):
1325
+ rp("[red]Task puna.is_homing_done() timed out after 30s.[/red]")
1326
+ rp(puna.is_homing_done())
1327
+ rp(puna.is_in_position())
1328
+ rp(puna.activate_control_loop())
1329
+ rp(puna.get_general_state())
1330
+ rp(puna.get_actuator_state())
1331
+ rp(puna.deactivate_control_loop())
1332
+ rp(puna.get_general_state())
1333
+ rp(puna.get_actuator_state())
1334
+ rp(puna.stop())
1335
+ rp(puna.get_limits_value(0))
1336
+ rp(puna.get_limits_value(1))
1337
+ rp(puna.check_absolute_movement(1, 1, 1, 1, 1, 1))
1338
+ rp(puna.check_absolute_movement(51, 51, 51, 1, 1, 1))
1339
+ rp(puna.get_speed())
1340
+ rp(puna.set_speed(2.0, 1.0))
1341
+ rp(speed := puna.get_speed())
1342
+
1343
+ if speed[:2] != [2.0, 1.0]:
1344
+ rp(f"[red]Expected {speed[:2]} == [2.0, 1.0][/red")
1345
+
1346
+ input("Check speed parameters in GUI")
1347
+
1348
+ rp(puna.set_speed(1.2, 1.1))
1349
+
1350
+ rp(speed := puna.get_speed())
1351
+
1352
+ if speed[:2] != [1.2, 1.1]:
1353
+ rp(f"[red]Expected {speed[:2]} == [1.2, 1.1][/red")
1354
+
1355
+ rp(puna.get_actuator_length())
1356
+
1357
+ # rp(puna.machine_limit_enable(0))
1358
+ # rp(puna.machine_limit_enable(1))
1359
+ # rp(puna.get_limits_state())
1360
+ rp(puna.get_coordinates_systems())
1361
+ rp(
1362
+ puna.configure_coordinates_systems(
1363
+ 0.033000,
1364
+ -0.238000,
1365
+ 230.205000,
1366
+ 0.003282,
1367
+ 0.005671,
1368
+ 0.013930,
1369
+ 0.000000,
1370
+ 0.000000,
1371
+ 0.000000,
1372
+ 0.000000,
1373
+ 0.000000,
1374
+ 0.000000,
1375
+ )
1376
+ )
1377
+ rp(puna.get_coordinates_systems())
1378
+ rp(puna.get_machine_positions())
1379
+ rp(puna.get_user_positions())
1380
+
1381
+ input("Check configuration in GUI")
1382
+
1383
+ rp(
1384
+ puna.configure_coordinates_systems(
1385
+ 0.000000,
1386
+ 0.000000,
1387
+ 0.000000,
1388
+ 0.000000,
1389
+ 0.000000,
1390
+ 0.000000,
1391
+ 0.000000,
1392
+ 0.000000,
1393
+ 0.000000,
1394
+ 0.000000,
1395
+ 0.000000,
1396
+ 0.000000,
1397
+ )
1398
+ )
1399
+
1400
+ rp(puna.validate_position(1, 0, 0, 0, 0, 0, 0, 0))
1401
+ rp(puna.validate_position(1, 0, 0, 0, 50, 0, 0, 0))
1402
+
1403
+ rp(puna.goto_zero_position())
1404
+ rp(puna.is_in_position())
1405
+ if wait_until(puna.is_in_position, interval=1, timeout=300):
1406
+ rp("[red]Task puna.is_in_position() timed out after 30s.[/red]")
1407
+ rp(puna.is_in_position())
1408
+
1409
+ rp(puna.get_machine_positions())
1410
+ rp(puna.get_user_positions())
1411
+
1412
+ rp(puna.move_absolute(0, 0, 12, 0, 0, 10))
1413
+
1414
+ rp(puna.is_in_position())
1415
+ if wait_until(puna.is_in_position, interval=1, timeout=300):
1416
+ rp("[red]Task puna.is_in_position() timed out after 30s.[/red]")
1417
+ rp(puna.is_in_position())
1418
+
1419
+ rp(puna.get_machine_positions())
1420
+ rp(puna.get_user_positions())
1421
+
1422
+ rp(puna.move_absolute(0, 0, 0, 0, 0, 0))
1423
+
1424
+ rp(puna.is_in_position())
1425
+ if wait_until(puna.is_in_position, interval=1, timeout=300):
1426
+ rp("[red]Task puna.is_in_position() timed out after 30s.[/red]")
1427
+ rp(puna.is_in_position())
1428
+
1429
+ rp(puna.get_machine_positions())
1430
+ rp(puna.get_user_positions())
1431
+
1432
+ # # puna.reset()
1433
+ puna.disconnect()
1434
+
1435
+ # rp(0, decode_validation_error(0))
1436
+ # rp(11, decode_validation_error(11))
1437
+ # rp(8, decode_validation_error(8))
1438
+ # rp(24, decode_validation_error(24))