cgse-common 2024.1.1__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.
egse/mixin.py ADDED
@@ -0,0 +1,464 @@
1
+ """
2
+ This module defines Mixin classes that can be used for adding methods and properties to
3
+ classes without strict inheritance.
4
+
5
+ Be careful, some of the Mixin classes require certain attributes to be defined in the
6
+ outer subclass. Read the docstrings carefully to understand what is needed.
7
+ """
8
+
9
+ import contextlib
10
+ import enum
11
+ import functools
12
+ import inspect
13
+ import logging
14
+ import string
15
+ from typing import Callable
16
+ from typing import Dict
17
+
18
+ from egse.command import ClientServerCommand
19
+ from egse.command import CommandError
20
+ from egse.command import CommandExecution
21
+ from egse.protocol import DynamicCommandProtocol
22
+ from egse.protocol import get_function
23
+
24
+ LOGGER = logging.getLogger(__name__)
25
+
26
+ __all__ = [
27
+ "add_lf",
28
+ "add_cr_lf",
29
+ "dynamic_command",
30
+ "DynamicCommandMixin",
31
+ ]
32
+
33
+ # ----- Mixin for dynamic commanding ---------------------------------------------------------------
34
+
35
+ COMMAND_TYPES = {
36
+ "read": "__read_command",
37
+ "write": "__write_command",
38
+ "query": "__query_command",
39
+ "transaction": "__transaction_command",
40
+ }
41
+ STX = "\x02" # start-of-text
42
+ ETX = "\x03" # end-of-text
43
+ EOT = "\x04" # end-of-transmission
44
+ LINE_FEED = "\x0A"
45
+ CARRIAGE_RETURN = "\x0D"
46
+
47
+
48
+ def add_etx(cmd_string: str):
49
+ """
50
+ Add an end-of-text ETX (ASCII code 0x03) to the command string.
51
+
52
+ Args:
53
+ cmd_string: the unprocessed command string
54
+
55
+ Returns:
56
+ The command string with the ETX character appended.
57
+ """
58
+ return cmd_string if cmd_string.endswith(ETX) else cmd_string + ETX
59
+
60
+
61
+ def add_eot(cmd_string: str):
62
+ """
63
+ Add an end-of-transmission EOT (ASCII code 0x04) to the command string.
64
+
65
+ Args:
66
+ cmd_string: the unprocessed command string
67
+
68
+ Returns:
69
+ The command string with the EOT character appended.
70
+ """
71
+ return cmd_string if cmd_string.endswith(EOT) else cmd_string + EOT
72
+
73
+
74
+ def add_lf(cmd_string: str):
75
+ """ Add a line feed to the given command string, if not added yet.
76
+
77
+ Args:
78
+ - cmd_string: Command string.
79
+
80
+ Returns: Given command string with a line feed appended (if not present yet).
81
+ """
82
+
83
+ if not cmd_string.endswith(LINE_FEED):
84
+
85
+ cmd_string += LINE_FEED
86
+
87
+ return cmd_string
88
+
89
+
90
+ def add_cr_lf(cmd_string: str):
91
+ """ Add a carriage return and line feed to the given command string, if not added yet.
92
+
93
+ Args:
94
+ - cmd_string: Command string.
95
+
96
+ Returns: Given command string with a carriage return and line feed appended (if not present yet).
97
+ """
98
+
99
+ if not cmd_string.endswith(CARRIAGE_RETURN + LINE_FEED):
100
+
101
+ cmd_string += CARRIAGE_RETURN + LINE_FEED
102
+
103
+ return cmd_string
104
+
105
+
106
+ def expand_kwargs(kwargs: Dict):
107
+ """Expand keyword arguments and their values as 'key=value' separated by spaces."""
108
+ return " ".join(f"{k}={v}" for k, v in kwargs.items())
109
+
110
+
111
+ def dynamic_command(
112
+ *,
113
+ cmd_type: str, # required keyword-only argument
114
+ cmd_string: str = None,
115
+ process_response: Callable = None,
116
+ process_cmd_string: Callable = None,
117
+ process_kwargs: Callable = None,
118
+ use_format: bool = False,
119
+ pre_cmd: Callable = None,
120
+ post_cmd: Callable = None,
121
+ ):
122
+ """Convert an interface method into a dynamic command.
123
+
124
+ The arguments define the type of command and how the response shall be processed.
125
+
126
+ The command types 'write', 'query', and 'transaction' must be accompanied by a `cmd_string`
127
+ argument that defines the formatting of the eventual command string that will be passed to
128
+ the transport functions. The `cmd_string` is a template string that contains `$`-based
129
+ substitutions for the function arguments. When you specify the `use_format=True` keyword,
130
+ the `cmd_string` will be formatted using the format() function instead of the template
131
+ substitution. The format option is less secure, but provides the functionality to format
132
+ the arguments.
133
+
134
+ A template string looks like:
135
+
136
+ cmd_string="CREATE:SENS:TEMP ${name} ${type} default=${default}"
137
+
138
+ The same `cmd_string` as a format option:
139
+
140
+ cmd_string="CREATE:SENS:TEMP {name} {type} default={default:0.4f}"
141
+ use_format=True
142
+
143
+ The process_response and process_cmd_string keywords allow you to specify a pure function to
144
+ process the response before it is returned, and to process the cmd_string before it is sent
145
+ to the transport function.
146
+
147
+ The `pre_cmd` and `post_cmd` keywords specify a callable/function to be executed before and/or
148
+ after the actual command was executed (i.e. send to the device). These functions are called
149
+ with specific keyword arguments that allow additional device interaction and response processing.
150
+ The `pre_cmd` function is called with the keyword argument `transport=` which passes the device
151
+ transport. This allows the function to interact with the device again through the methods defined
152
+ by the DeviceTransport interface. The `pre_cmd` function must not return anything.
153
+ The `post_cmd` function is called with the keyword arguments `transport=` and `response=`.
154
+ The response argument contains the response from the command that was previously sent to the
155
+ device. The `post_cmd` function can use this response to parse its content and act against
156
+ this content, although possible, it is usually not a good idea to alter the content of the
157
+ response argument. The `post_cmd` function shall return (i.e. pass through) the response.
158
+
159
+ This decorator can add the following static attributes to the method:
160
+
161
+ * __dynamic_interface
162
+ * __read_command, __write_command, __query_command, __transaction_command
163
+ * __cmd_string
164
+ * __process_response
165
+ * __process_cmd_string
166
+ * __use_format
167
+ * __pre_cmd
168
+ * __post_cmd
169
+
170
+ Args:
171
+ cmd_type (str): one of 'read', 'write', 'query', or 'transaction' [required keyword]
172
+ cmd_string (str): format string for the generation of the instrument command
173
+ process_response (Callable): function to process the response
174
+ process_cmd_string (Callable): function to process the command string after substitution
175
+ process_kwargs (Callable): function to expand the kwargs after substitution
176
+ use_format (bool): use string formatting instead of string templates
177
+ pre_cmd (Callable): the function to execute before the command is executed
178
+ post_cmd (Callable): the function to execute after the command is executed
179
+ """
180
+
181
+ # Perform some checks on required arguments
182
+
183
+ if cmd_type not in COMMAND_TYPES:
184
+ raise ValueError(f"Unknown type passed into dynamic command decorator: {type=}")
185
+
186
+ if cmd_type in ('write', 'query', 'transaction') and cmd_string is None:
187
+ raise ValueError(f"No cmd_string was provided for {cmd_type=}.")
188
+
189
+ def func_wrapper(func: Callable):
190
+ """Adds the different static attributes."""
191
+
192
+ setattr(func, "__dynamic_interface", True)
193
+
194
+ setattr(func, COMMAND_TYPES[cmd_type], True)
195
+
196
+ if cmd_string is not None:
197
+ setattr(func, "__cmd_string", cmd_string)
198
+
199
+ if process_response is not None:
200
+ setattr(func, "__process_response", process_response)
201
+
202
+ if process_cmd_string is not None:
203
+ setattr(func, "__process_cmd_string", process_cmd_string)
204
+
205
+ if process_kwargs is not None:
206
+ setattr(func, "__process_kwargs", process_kwargs)
207
+
208
+ if use_format:
209
+ setattr(func, "__use_format", True)
210
+
211
+ if pre_cmd is not None:
212
+ setattr(func, "__pre_cmd", pre_cmd)
213
+
214
+ if post_cmd is not None:
215
+ setattr(func, "__post_cmd", post_cmd)
216
+
217
+ return func
218
+
219
+ return func_wrapper
220
+
221
+
222
+ class DynamicCommandMixin:
223
+ """
224
+ This Mixin class defines the functionality to dynamically call specific instrument commands
225
+ from methods that are defined in the Interface classes for device Controllers.
226
+
227
+ The mixin uses the `self.transport` instance variables that shall be defined by the
228
+ Controller subclass. The `self.transport` shall be a DeviceTransport object providing the
229
+ methods to read, write, and query an instrument.
230
+
231
+ !!! note
232
+ This mixin overrides the `__getattribute__` method!
233
+
234
+ !!! note
235
+ This mixin class shall only be inherited from a Controller class that defines the
236
+ `self.transport` attribute.
237
+ """
238
+
239
+ def __init__(self):
240
+ if not hasattr(self, "transport"):
241
+ raise AttributeError("Transport was not defined in sub-class of DynamicInterfaceMixin")
242
+
243
+ @staticmethod
244
+ def create_command_string(func: Callable, template_str: str, *args, **kwargs):
245
+ """
246
+ Creates a command string that is understood by the instrument. This can be an SCPI
247
+ command or a specific proprietary command string. The `cmd_str` can contain placeholders
248
+ similar to what is used in string formatting.
249
+
250
+ As an example, we have a function with two positional arguments 'a', and 'b' and one keyword
251
+ argument flag:
252
+
253
+ def func(a, b, flag=True):
254
+ pass
255
+
256
+ We have the following template string: `CREATE:FUN:${a} ${b} [${flag}]`.
257
+
258
+ When we call the function as follows: `func("TEMP", 23)`, we would then expect
259
+ the returned string to be "CREATE:FUN:TEMP 23 [True]"
260
+
261
+ DynamicCommandMixin.create_command_string(func, template, "TEMP", 23)
262
+
263
+ Args:
264
+ func (Callable): a function or method that provides the signature
265
+ template_str (str): a template for the command
266
+ args (tuple): positional arguments that will be used in the command string
267
+ kwargs (dict): keywords arguments that will be used in the command string
268
+ """
269
+ try:
270
+ process_kwargs = getattr(func, "__process_kwargs")
271
+ except AttributeError:
272
+ process_kwargs = expand_kwargs
273
+
274
+ template = string.Template(template_str)
275
+
276
+ sig = inspect.signature(func)
277
+ try:
278
+ bound = sig.bind(*args, **kwargs)
279
+ except TypeError as exc:
280
+ raise CommandError(
281
+ f"Arguments {args}, {kwargs} do not match function signature for "
282
+ f"{func.__name__}{sig}") from exc
283
+
284
+ variables = {}
285
+ for idx, par in enumerate(sig.parameters.values()):
286
+ # if the argument is of signature '**kwargs' then expand the kwargs
287
+ if par.kind == inspect.Parameter.VAR_KEYWORD:
288
+ variables[par.name] = process_kwargs(bound.arguments[par.name])
289
+ continue
290
+
291
+ # otherwise, use the argument value or the default
292
+ try:
293
+ variables[par.name] = bound.arguments[par.name]
294
+ except KeyError:
295
+ variables[par.name] = par.default
296
+
297
+ if hasattr(func, "__use_format"):
298
+ cmd_string = template_str.format(**variables)
299
+ else:
300
+ variables = {
301
+ k: v.value if isinstance(v, enum.Enum) else v
302
+ for k, v in variables.items()
303
+ }
304
+ cmd_string = template.safe_substitute(variables)
305
+
306
+ try:
307
+ process_cmd_string = getattr(func, "__process_cmd_string")
308
+ cmd_string = process_cmd_string(cmd_string)
309
+ except AttributeError:
310
+ pass
311
+
312
+ return cmd_string
313
+
314
+ def handle_dynamic_command(self, attr):
315
+ """
316
+ Creates a command wrapper calling the appropriate transport methods that are associated
317
+ with the interface definition as passed into this method with the attr argument.
318
+
319
+ Args:
320
+ attr: The interface method that is decorated as a dynamic_command.
321
+
322
+ Returns:
323
+ Command wrapper with the read or write command, depending on the decorators used
324
+ for that method in the corresponding Interface class.
325
+
326
+ Raises:
327
+ AttributeError: If the command is not listed in the YAML file and/or
328
+ has not been listed.
329
+ """
330
+
331
+ @functools.wraps(attr)
332
+ def command_wrapper(*args, **kwargs):
333
+ """Generates command strings and executes the transport functions."""
334
+ try:
335
+ cmd_str = getattr(attr, "__cmd_string")
336
+ cmd_str = self.create_command_string(attr, cmd_str, *args, **kwargs)
337
+ except AttributeError:
338
+ cmd_str = None
339
+
340
+ response = None
341
+
342
+ with contextlib.suppress(AttributeError):
343
+ getattr(attr, "__pre_cmd")(transport=self.transport,
344
+ function_name=attr.__name__, cmd_str=cmd_str, args=args, kwargs=kwargs)
345
+
346
+ if hasattr(attr, "__write_command"):
347
+ self.transport.write(cmd_str)
348
+ elif hasattr(attr, "__read_command"):
349
+ response = self.transport.read()
350
+ elif hasattr(attr, "__query_command"):
351
+ response = self.transport.query(cmd_str)
352
+ elif hasattr(attr, "__transaction_command"):
353
+ response = self.transport.trans(cmd_str)
354
+ else:
355
+ raise CommandError(f"Interface method '{attr.__name__}' shall be decorated with "
356
+ f"a command type decorator.")
357
+
358
+ with contextlib.suppress(AttributeError):
359
+ response = getattr(attr, "__post_cmd")(transport=self.transport, response=response)
360
+
361
+ with contextlib.suppress(AttributeError):
362
+ process_response = getattr(attr, "__process_response")
363
+ response = process_response(response=response)
364
+
365
+ return response
366
+
367
+ # Add a hook to identify the command_wrapper function as a method, instead of a function.
368
+
369
+ setattr(command_wrapper, "__method_wrapper", True)
370
+
371
+ # Add the docstring of the interface method
372
+
373
+ command_wrapper.__doc__ = attr.__doc__
374
+
375
+ return command_wrapper
376
+
377
+ def __getattribute__(self, item):
378
+ """
379
+ The function __getattribute__() is called unconditionally when calling a method or accessing
380
+ an instance variable. This override of `__getattribute__` additionally checks if the
381
+ attribute is a method which has the `__dynamic_interface` defined and then calls a specific
382
+ function to handle the command dynamically.
383
+
384
+ Check if item exists:
385
+ - if `item` exists and has the __dynamic_interface attribute then let the function
386
+ handle_dynamic_command() handle this, i.e. call the instrument command.
387
+ - else: the method has been defined in the Controller class, and we should just call
388
+ that method (because it is overridden).
389
+ """
390
+
391
+ # If item is not known, an AttributeError will be raised and __getattr__() will be called.
392
+
393
+ attr = object.__getattribute__(self, item)
394
+
395
+ if hasattr(attr, "__dynamic_interface"):
396
+
397
+ # We come here when the method is defined in the Interface class (where it is
398
+ # decorated with the @dynamic_interface), but not in the subclass. So, the method
399
+ # is not overridden. We let the handle_dynamic_command() method handle this.
400
+
401
+ attr = self.handle_dynamic_command(attr)
402
+
403
+ return attr
404
+
405
+
406
+ class DynamicClientCommandMixin:
407
+ """
408
+ This mixin class contains functionality to forward a device command from a client Proxy class
409
+ to its control server.
410
+
411
+ !!! note
412
+ This mixin overrides the `__getattribute__` method!
413
+
414
+ """
415
+ def __getattribute__(self, item):
416
+ # If item is not known, an AttributeError will be raised and __getattr__() will be called.
417
+
418
+ attr = object.__getattribute__(self, item)
419
+
420
+ if hasattr(attr, "__dynamic_interface"):
421
+
422
+ # We come here when the method is defined in the Interface class (where it is
423
+ # decorated with the @dynamic_interface), but not in the subclass. So, the method
424
+ # is not overridden. We let the handle_dynamic_command() method handle this.
425
+
426
+ attr = self.handle_dynamic_command(attr)
427
+
428
+ return attr
429
+
430
+ def handle_dynamic_command(self, attr):
431
+
432
+ @functools.wraps(attr)
433
+ def command_wrapper(*args, **kwargs):
434
+
435
+ attr_name = getattr(attr, "__name__")
436
+
437
+ # This will ensure that the function is called with the proper arguments
438
+
439
+ try:
440
+ inspect.signature(attr).bind(*args, **kwargs)
441
+ except TypeError as exc:
442
+ LOGGER.error(f"Arguments do not match the signature of the function '{attr_name}': {exc}")
443
+ return None
444
+
445
+ # Create a command execution to pass the commanded function and the given arguments
446
+ # to the control server for execution.
447
+
448
+ device_method = get_function(self.__class__, attr_name)
449
+ cmd = ClientServerCommand(name=attr_name,
450
+ cmd=getattr(attr, "__cmd_string", ""),
451
+ response=DynamicCommandProtocol.handle_device_method,
452
+ device_method=device_method)
453
+ ce = CommandExecution(cmd, *args, **kwargs)
454
+
455
+ # Send the command to the control server for execution
456
+
457
+ rc = self.send(ce)
458
+ return rc
459
+
460
+ # rewrite the proper signature for the called function
461
+
462
+ command_wrapper.__signature__ = inspect.signature(attr)
463
+
464
+ return command_wrapper
egse/monitoring.py ADDED
@@ -0,0 +1,96 @@
1
+ import logging
2
+ import multiprocessing
3
+ import pickle
4
+
5
+ import click
6
+ import rich
7
+ import zmq
8
+
9
+ from egse.control import ControlServer
10
+ from egse.protocol import CommandProtocol
11
+ from egse.system import format_datetime
12
+ from egse.zmq_ser import MessageIdentifier
13
+ from egse.zmq_ser import bind_address
14
+
15
+ logger = logging.getLogger("egse.monitoring")
16
+
17
+ class MonitoringProtocol(CommandProtocol):
18
+ def __init__(self, control_server: ControlServer):
19
+ super().__init__()
20
+ self.control_server = control_server
21
+
22
+ def get_bind_address(self):
23
+ return bind_address(self.control_server.get_communication_protocol(), self.control_server.get_monitoring_port())
24
+
25
+ def get_status(self):
26
+ return {
27
+ 'timestamp': format_datetime(),
28
+ }
29
+
30
+ def send_status(self, status):
31
+ self.send(status)
32
+
33
+ def get_housekeeping(self) -> dict:
34
+ return {
35
+ 'timestamp': format_datetime(),
36
+ }
37
+
38
+
39
+
40
+ @click.command()
41
+ @click.argument('hostname')
42
+ @click.argument('port')
43
+ @click.option('--subscribe', '-s', default=('ALL',), multiple=True,
44
+ help="subscribe to a sync identifier, can appear multiple times")
45
+ @click.option('--multipart', '-m', is_flag=True, default=False, help="use multipart messages")
46
+ @click.option('--pickle/--no-pickle', 'use_pickle', default=True)
47
+ def monitoring(hostname: str, port: int, subscribe: str, multipart: bool, use_pickle: bool):
48
+ """Monitor the status of a control server on hostname:port.
49
+
50
+ The port number shall correspond to the port number on which the control server is publishing
51
+ status information.
52
+ """
53
+ context = zmq.Context()
54
+
55
+ receiver = context.socket(zmq.SUB)
56
+ receiver.connect(f"tcp://{hostname}:{port}")
57
+
58
+ for item in subscribe:
59
+ sync_id = 0
60
+ try:
61
+ sync_id = MessageIdentifier[item.upper()]
62
+ except KeyError:
63
+ rich.print(f"[red]ERROR: incorrect subscribe identifier, "
64
+ f"use one of {[x.name for x in MessageIdentifier]}")
65
+ ctx = click.get_current_context()
66
+ rich.print(ctx.get_help())
67
+ ctx.exit()
68
+
69
+ if sync_id == MessageIdentifier.ALL:
70
+ subscribe_string = b''
71
+ else:
72
+ subscribe_string = sync_id.to_bytes(1, byteorder='big')
73
+
74
+ receiver.subscribe(subscribe_string)
75
+
76
+ while True:
77
+ try:
78
+ if multipart:
79
+ sync_id, message = receiver.recv_multipart()
80
+ sync_id = int.from_bytes(sync_id, byteorder='big')
81
+ else:
82
+ sync_id = MessageIdentifier.ALL
83
+ message = receiver.recv()
84
+ response = pickle.loads(message) if use_pickle else message
85
+ rich.print(f"{MessageIdentifier(sync_id).name}, {response}", flush=True)
86
+ except KeyboardInterrupt:
87
+ logger.info("KeyboardInterrupt caught!")
88
+ break
89
+
90
+ receiver.close(linger=0)
91
+ context.term()
92
+
93
+
94
+ if __name__ == "__main__":
95
+ multiprocessing.current_process().name = "Monitoring"
96
+ monitoring()
egse/observer.py ADDED
@@ -0,0 +1,41 @@
1
+ import abc
2
+
3
+
4
+ class Observer(abc.ABC):
5
+ @abc.abstractmethod
6
+ def update(self, changed_object):
7
+ pass
8
+
9
+ @abc.abstractmethod
10
+ def do(self, actions):
11
+ pass
12
+
13
+
14
+ class Observable:
15
+ def __init__(self):
16
+ self.observers = []
17
+
18
+ def addObserver(self, observer):
19
+ if observer not in self.observers:
20
+ self.observers.append(observer)
21
+
22
+ def deleteObserver(self, observer):
23
+ self.observers.remove(observer)
24
+
25
+ def clearObservers(self):
26
+ self.observers = []
27
+
28
+ def countObservers(self):
29
+ return len(self.observers)
30
+
31
+ def notifyObservers(self, changedObject):
32
+ # FIXME: put a try..except here to log any problem that occurred in the observer's update()
33
+ # method
34
+ for observer in self.observers:
35
+ observer.update(changedObject)
36
+
37
+ def actionObservers(self, actions):
38
+ # FIXME: put a try..except here to log any problem that occurred in the observer's do()
39
+ # method
40
+ for observer in self.observers:
41
+ observer.do(actions)