syndesi 0.1.5__py3-none-any.whl → 0.2.0__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.
Files changed (41) hide show
  1. syndesi/adapters/__init__.py +7 -3
  2. syndesi/adapters/adapter.py +321 -0
  3. syndesi/adapters/auto.py +45 -0
  4. syndesi/adapters/iadapter.py +158 -20
  5. syndesi/adapters/ip.py +106 -40
  6. syndesi/adapters/ip_server.py +108 -0
  7. syndesi/adapters/proxy.py +92 -0
  8. syndesi/adapters/remote.py +18 -0
  9. syndesi/adapters/serialport.py +158 -0
  10. syndesi/adapters/stop_conditions.py +173 -0
  11. syndesi/adapters/timed_queue.py +32 -0
  12. syndesi/adapters/timeout.py +297 -0
  13. syndesi/adapters/visa.py +10 -8
  14. syndesi/api/__init__.py +0 -0
  15. syndesi/api/api.py +77 -0
  16. syndesi/protocols/__init__.py +2 -2
  17. syndesi/protocols/delimited.py +34 -22
  18. syndesi/protocols/iprotocol.py +2 -2
  19. syndesi/protocols/protocol.py +17 -0
  20. syndesi/protocols/raw.py +9 -60
  21. syndesi/protocols/scpi.py +37 -16
  22. syndesi/protocols/sdp.py +4 -4
  23. syndesi/proxy/__init__.py +0 -0
  24. syndesi/proxy/proxy.py +136 -0
  25. syndesi/proxy/proxy_api.py +93 -0
  26. syndesi/tools/log.py +107 -0
  27. syndesi/tools/logger.py +113 -0
  28. syndesi/tools/others.py +1 -0
  29. syndesi/tools/remote_api.py +113 -0
  30. syndesi/tools/remote_server.py +133 -0
  31. syndesi/tools/shell.py +111 -0
  32. syndesi/tools/types.py +24 -18
  33. {syndesi-0.1.5.dist-info → syndesi-0.2.0.dist-info}/LICENSE +0 -0
  34. {syndesi-0.1.5.dist-info → syndesi-0.2.0.dist-info}/METADATA +17 -15
  35. syndesi-0.2.0.dist-info/RECORD +63 -0
  36. syndesi-0.2.0.dist-info/entry_points.txt +3 -0
  37. syndesi-0.2.0.dist-info/top_level.txt +1 -0
  38. syndesi-0.1.5.data/scripts/syndesi +0 -1
  39. syndesi-0.1.5.dist-info/RECORD +0 -42
  40. syndesi-0.1.5.dist-info/top_level.txt +0 -2
  41. {syndesi-0.1.5.dist-info → syndesi-0.2.0.dist-info}/WHEEL +0 -0
@@ -1,4 +1,8 @@
1
- from .iadapter import IAdapter
1
+ from .adapter import Adapter
2
2
  from .ip import IP
3
- from .serial import Serial
4
- from .visa import VISA
3
+ from .serialport import SerialPort
4
+ from .visa import VISA
5
+ from .proxy import Proxy
6
+
7
+ from .timeout import Timeout
8
+ from .stop_conditions import Termination, Length, StopCondition
@@ -0,0 +1,321 @@
1
+ # adapters.py
2
+ # Sébastien Deriaz
3
+ # 06.05.2023
4
+ #
5
+ # Adapters provide a common abstraction for the media layers (physical + data link + network)
6
+ # The following classes are provided, which all are derived from the main Adapter class
7
+ # - IP
8
+ # - Serial
9
+ # - VISA
10
+ #
11
+ # Note that technically VISA is not part of the media layer, only USB is.
12
+ # This is a limitation as it is to this day not possible to communicate "raw"
13
+ # with a device through USB yet
14
+ #
15
+ # An adapter is meant to work with bytes objects but it can accept strings.
16
+ # Strings will automatically be converted to bytes using utf-8 encoding
17
+ #
18
+
19
+ from abc import abstractmethod, ABC
20
+ from .timed_queue import TimedQueue
21
+ from threading import Thread
22
+ from typing import Union
23
+ from enum import Enum
24
+ from .stop_conditions import StopCondition, Termination, Length
25
+ from .timeout import Timeout, TimeoutException, timeout_fuse
26
+ from typing import Union
27
+ from ..tools.types import is_number
28
+ from ..tools.log import LoggerAlias
29
+ import logging
30
+ from time import time
31
+ from dataclasses import dataclass
32
+ from ..tools.others import DEFAULT
33
+
34
+ DEFAULT_TIMEOUT = Timeout(response=1, continuation=100e-3, total=None)
35
+ DEFAULT_STOP_CONDITION = None
36
+
37
+
38
+ class AdapterDisconnected(Exception):
39
+ pass
40
+
41
+ STOP_DESIGNATORS = {
42
+ 'timeout' : {
43
+ Timeout.TimeoutType.RESPONSE : 'TR',
44
+ Timeout.TimeoutType.CONTINUATION : 'TC',
45
+ Timeout.TimeoutType.TOTAL : 'TT'
46
+ },
47
+ 'stop_condition' : {
48
+ Termination : 'ST',
49
+ Length : 'SL'
50
+ },
51
+ 'previous-read-buffer' : 'RB'
52
+ }
53
+
54
+ class Origin(Enum):
55
+ TIMEOUT = 'timeout'
56
+ STOP_CONDITION = 'stop_condition'
57
+
58
+ @dataclass
59
+ class ReturnMetrics:
60
+ read_duration : float
61
+ origin : Origin
62
+ timeout_type : Timeout.TimeoutType
63
+ stop_condition : StopCondition
64
+ previous_read_buffer_used : bool
65
+ n_fragments : int
66
+ response_time : float
67
+ continuation_times : list
68
+ total_time : float
69
+
70
+ class Adapter(ABC):
71
+ class Status(Enum):
72
+ DISCONNECTED = 0
73
+ CONNECTED = 1
74
+
75
+ def __init__(self, alias : str = '', stop_condition : Union[StopCondition, None] = DEFAULT, timeout : Union[float, Timeout] = DEFAULT) -> None:
76
+ """
77
+ Adapter instance
78
+
79
+ Parameters
80
+ ----------
81
+ alias : str
82
+ The alias is used to identify the class in the logs
83
+ timeout : float or Timeout instance
84
+ Default timeout is Timeout(response=1, continuation=0.1, total=None)
85
+ stop_condition : StopCondition or None
86
+ Default to None
87
+ """
88
+ super().__init__()
89
+ self._alias = alias
90
+
91
+ self._default_stop_condition = stop_condition == DEFAULT
92
+ if self._default_stop_condition:
93
+ self._stop_condition = DEFAULT_STOP_CONDITION
94
+ else:
95
+ self._stop_condition = stop_condition
96
+ self._read_queue = TimedQueue()
97
+ self._thread : Union[Thread, None] = None
98
+ self._status = self.Status.DISCONNECTED
99
+ self._logger = logging.getLogger(LoggerAlias.ADAPTER.value)
100
+
101
+ # Buffer for data that has been pulled from the queue but
102
+ # not used because of termination or length stop condition
103
+ self._previous_read_buffer = b''
104
+
105
+ self._default_timeout = timeout == DEFAULT
106
+ if self._default_timeout:
107
+ self._timeout = DEFAULT_TIMEOUT
108
+ else:
109
+ if is_number(timeout):
110
+ self._timeout = Timeout(response=timeout, continuation=100e-3)
111
+ elif isinstance(timeout, Timeout):
112
+ self._timeout = timeout
113
+ else:
114
+ raise ValueError(f"Invalid timeout type : {type(timeout)}")
115
+
116
+ def set_default_timeout(self, default_timeout : Union[Timeout, tuple, float]):
117
+ """
118
+ Set the default timeout for this adapter. If a previous timeout has been set, it will be fused
119
+
120
+ Parameters
121
+ ----------
122
+ default_timeout : Timeout or tuple or float
123
+ """
124
+ if self._default_timeout:
125
+ self._timeout = default_timeout
126
+ else:
127
+ self._timeout = timeout_fuse(self._timeout, default_timeout)
128
+
129
+ def set_default_stop_condition(self, stop_condition):
130
+ """
131
+ Set the default stop condition for this adapter.
132
+
133
+ Parameters
134
+ ----------
135
+ stop_condition : StopCondition
136
+ """
137
+ if self._default_stop_condition:
138
+ self._stop_condition = stop_condition
139
+
140
+ def flushRead(self):
141
+ """
142
+ Flush the input buffer
143
+ """
144
+ self._read_queue.clear()
145
+ self._previous_read_buffer = b''
146
+
147
+ @abstractmethod
148
+ def open(self):
149
+ """
150
+ Start communication with the device
151
+ """
152
+ pass
153
+
154
+ @abstractmethod
155
+ def close(self):
156
+ """
157
+ Stop communication with the device
158
+ """
159
+ pass
160
+
161
+ @abstractmethod
162
+ def write(self, data : Union[bytes, str]):
163
+ """
164
+ Send data to the device
165
+
166
+ Parameters
167
+ ----------
168
+ data : bytes or str
169
+ """
170
+ pass
171
+
172
+ # TODO : Return None or b'' when read thread is killed while reading
173
+ # This is to detect if a server socket has been closed
174
+
175
+
176
+ def read(self, timeout=None, stop_condition=None, return_metrics : bool = False) -> bytes:
177
+ """
178
+ Read data from the device
179
+
180
+ Parameters
181
+ ----------
182
+ timeout : Timeout or None
183
+ Set a custom timeout, if None (default), the adapter timeout is used
184
+ stop_condition : StopCondition or None
185
+ Set a custom stop condition, if None (Default), the adapater stop condition is used
186
+ return_metrics : ReturnMetrics class
187
+ """
188
+ read_start = time()
189
+ if self._status == self.Status.DISCONNECTED:
190
+ self.open()
191
+
192
+ # Use adapter values if no custom value is specified
193
+ if timeout is None:
194
+ timeout = self._timeout
195
+ elif isinstance(timeout, float):
196
+ timeout = Timeout(timeout)
197
+
198
+
199
+ if stop_condition is None:
200
+ stop_condition = self._stop_condition
201
+
202
+ # If the adapter is closed, open it
203
+ if self._status == self.Status.DISCONNECTED:
204
+ self.open()
205
+
206
+ if self._thread is None or not self._thread.is_alive():
207
+ self._start_thread()
208
+
209
+ timeout_ms = timeout.initiate_read(len(self._previous_read_buffer) > 0)
210
+
211
+ if stop_condition is not None:
212
+ stop_condition.initiate_read()
213
+
214
+ deferred_buffer = b''
215
+
216
+ # Start with the deferred buffer
217
+ # TODO : Check if data could be lost here, like the data is put in the previous_read_buffer and is never
218
+ # read back again because there's no stop condition
219
+ if len(self._previous_read_buffer) > 0 and stop_condition is not None:
220
+ stop, output, self._previous_read_buffer = stop_condition.evaluate(self._previous_read_buffer)
221
+ previous_read_buffer_used = True
222
+ else:
223
+ stop = False
224
+ output = b''
225
+ previous_read_buffer_used = False
226
+
227
+ n_fragments = 0
228
+ # If everything is used up, read the queue
229
+ if not stop:
230
+ while True:
231
+ (timestamp, fragment) = self._read_queue.get(timeout_ms)
232
+ n_fragments += 1
233
+
234
+ if fragment == b'':
235
+ raise AdapterDisconnected()
236
+
237
+ # 1) Evaluate the timeout
238
+ stop, timeout_ms = timeout.evaluate(timestamp)
239
+ if stop:
240
+ data_strategy, origin = timeout.dataStrategy()
241
+ if data_strategy == Timeout.OnTimeoutStrategy.DISCARD:
242
+ # Trash everything
243
+ output = b''
244
+ elif data_strategy == Timeout.OnTimeoutStrategy.RETURN:
245
+ # Return the data that has been read up to this point
246
+ output += deferred_buffer
247
+ if fragment is not None:
248
+ output += fragment
249
+ elif data_strategy == Timeout.OnTimeoutStrategy.STORE:
250
+ # Store the data
251
+ self._previous_read_buffer = output
252
+ output = b''
253
+ elif data_strategy == Timeout.OnTimeoutStrategy.ERROR:
254
+ raise TimeoutException(origin)
255
+ break
256
+ else:
257
+ origin = None
258
+
259
+
260
+
261
+ # Add the deferred buffer
262
+ if len(deferred_buffer) > 0:
263
+ fragment = deferred_buffer + fragment
264
+
265
+ # 2) Evaluate the stop condition
266
+ if stop_condition is not None:
267
+ stop, kept_fragment, deferred_buffer = stop_condition.evaluate(fragment)
268
+ output += kept_fragment
269
+ if stop:
270
+ self._previous_read_buffer = deferred_buffer
271
+ else:
272
+ output += fragment
273
+ if stop:
274
+ break
275
+
276
+ if origin is not None:
277
+ # The stop originates from the timeout
278
+ designator = STOP_DESIGNATORS['timeout'][origin]
279
+ else:
280
+ designator = STOP_DESIGNATORS['stop_condition'][type(stop_condition)]
281
+ else:
282
+ designator = STOP_DESIGNATORS['previous-read-buffer']
283
+
284
+ read_duration = time() - read_start
285
+ if self._previous_read_buffer:
286
+ self._logger.debug(f'Read [{designator}, {read_duration*1e3:.3f}ms] : {output} , previous read buffer : {self._previous_read_buffer}')
287
+ else:
288
+ self._logger.debug(f'Read [{designator}, {read_duration*1e3:.3f}ms] : {output}')
289
+
290
+ if return_metrics:
291
+ return output, ReturnMetrics(
292
+ read_duration=read_duration,
293
+ origin=Origin.TIMEOUT if origin is not None else Origin.STOP_CONDITION,
294
+ timeout_type=origin if origin is not None else None,
295
+ stop_condition=type(stop_condition) if origin is None else None,
296
+ previous_read_buffer_used=previous_read_buffer_used,
297
+ n_fragments=n_fragments,
298
+ response_time=timeout.response_time,
299
+ continuation_times=timeout.continuation_times,
300
+ total_time=timeout.total_time
301
+ )
302
+ else:
303
+ return output
304
+
305
+ @abstractmethod
306
+ def _start_thread(self):
307
+ pass
308
+
309
+ def __del__(self):
310
+ self.close()
311
+
312
+ @abstractmethod
313
+ def query(self, data : Union[bytes, str], timeout=None, stop_condition=None, return_metrics : bool = False) -> bytes:
314
+ """
315
+ Shortcut function that combines
316
+ - flush_read
317
+ - write
318
+ - read
319
+ """
320
+ pass
321
+
@@ -0,0 +1,45 @@
1
+ # auto.py
2
+ # Sébastien Deriaz
3
+ # 24.06.2024
4
+ #
5
+ # Automatic adapter function
6
+ # This function is used to automatically choose an adapter based on the user's input
7
+ # 192.168.1.1 -> IP
8
+ # COM4 -> Serial
9
+ # /dev/tty* -> Serial
10
+ # etc...
11
+ # If an adapter class is supplied, it is simply passed through
12
+ #
13
+ # Additionnaly, it is possible to do COM4:115200 so as to make the life of the user easier
14
+ # Same with /dev/ttyACM0:115200
15
+
16
+ from typing import Union
17
+ import re
18
+ from . import Adapter, IP, SerialPort
19
+
20
+ IP_PATTERN = '([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(:[0-9]+)*'
21
+
22
+ WINDOWS_SERIAL_PATTERN = '(COM[0-9]+)(:[0-9]+)*'
23
+ LINUX_SERIAL_PATTERN = '(/dev/tty[a-zA-Z0-9]+)(:[0-9]+)*'
24
+
25
+ def auto_adapter(adapter_or_string : Union[Adapter, str]):
26
+ if isinstance(adapter_or_string, Adapter):
27
+ # Simply return it
28
+ return adapter_or_string
29
+ elif isinstance(adapter_or_string, str):
30
+ # Parse it
31
+ ip_match = re.match(IP_PATTERN, adapter_or_string)
32
+ if ip_match:
33
+ # Return an IP adapter
34
+ return IP(address=ip_match.groups(0), port=ip_match.groups(1))
35
+ elif re.match(WINDOWS_SERIAL_PATTERN, adapter_or_string):
36
+ port, baudrate = re.match(WINDOWS_SERIAL_PATTERN, adapter_or_string).groups()
37
+ return SerialPort(port=port, baudrate=int(baudrate))
38
+ elif re.match(LINUX_SERIAL_PATTERN, adapter_or_string):
39
+ port, baudrate = re.match(LINUX_SERIAL_PATTERN, adapter_or_string)
40
+ return SerialPort(port=port, baudrate=int(baudrate))
41
+ else:
42
+ raise ValueError(f"Couldn't parse adapter description : {adapter_or_string}")
43
+
44
+ else:
45
+ raise ValueError(f"Invalid adapter : {adapter_or_string}")
@@ -9,30 +9,76 @@
9
9
  # - VISA
10
10
  #
11
11
  # Note that technically VISA is not part of the media layer, only USB is.
12
- # This is a limitation as it is to this day not possible to communication "raw"
12
+ # This is a limitation as it is to this day not possible to communicate "raw"
13
13
  # with a device through USB yet
14
14
  #
15
- #
16
- #
17
- #
18
- # Timeout system
19
- # We can differentiate two kinds of timeout :
20
- # - transmission timeout (aka "timeout"): the time it takes for a device to start transmitting what we expect
21
- # - continuation timeout : the time it takes for a device to continue sending the requested data
15
+ # An adapter is meant to work with bytes objects but it can accept strings.
16
+ # Strings will automatically be converted to bytes using utf-8 encoding
22
17
 
23
18
  from abc import abstractmethod, ABC
19
+ from .timed_queue import TimedQueue
20
+ from threading import Thread
21
+ from typing import Union
22
+ from enum import Enum
23
+ from .stop_conditions import StopCondition
24
+ from .timeout import Timeout, TimeoutException
25
+ from typing import Union
26
+ from ..tools.types import is_number
27
+ from ..tools.logger import AdapterLogger
28
+
29
+ DEFAULT_TIMEOUT = Timeout(response=1, continuation=100e-3, total=None)
30
+ DEFAUT_STOP_CONDITION = None
24
31
 
25
32
  class IAdapter(ABC):
26
- @abstractmethod
27
- def __init__(self, descriptor, *args):
28
- pass
29
33
 
30
- @abstractmethod
34
+ class Status(Enum):
35
+ DISCONNECTED = 0
36
+ CONNECTED = 1
37
+
38
+ def __init__(self,
39
+ timeout : Union[float, Timeout] = DEFAULT_TIMEOUT,
40
+ stop_condition : Union[StopCondition, None] = DEFAUT_STOP_CONDITION,
41
+ log_level : int = 0):
42
+ """
43
+ IAdapter instance
44
+
45
+ Parameters
46
+ ----------
47
+ timeout : float or Timeout instance
48
+ Default timeout is Timeout(response=1, continuation=0.1, total=None)
49
+ stop_condition : StopCondition or None
50
+ Default to None
51
+ log : int
52
+ 0 : basic logging
53
+ 1 : detailed logging
54
+ 2 : complete logging
55
+ """
56
+
57
+ if is_number(timeout):
58
+ self._timeout = Timeout(response=timeout, continuation=100e-3)
59
+ elif isinstance(timeout, Timeout):
60
+ self._timeout = timeout
61
+ else:
62
+ raise ValueError(f"Invalid timeout type : {type(timeout)}")
63
+
64
+ self._stop_condition = stop_condition
65
+ self._read_queue = TimedQueue()
66
+ self._thread : Union[Thread, None] = None
67
+ self._status = self.Status.DISCONNECTED
68
+ # Buffer for data that has been pulled from the queue but
69
+ # not used because of termination or length stop condition
70
+ self._previous_read_buffer = b''
71
+
72
+ self._logger = AdapterLogger('adapter')
73
+ self._logger.set_log_level(log_level)
74
+ self._logger.log_status('Initializing adapter', 0)
75
+
31
76
  def flushRead(self):
32
77
  """
33
78
  Flush the input buffer
34
79
  """
35
- pass
80
+ self._read_queue.clear()
81
+ self._previous_read_buffer = b''
36
82
 
37
83
  @abstractmethod
38
84
  def open(self):
@@ -49,25 +95,117 @@ class IAdapter(ABC):
49
95
  pass
50
96
 
51
97
  @abstractmethod
52
- def write(self, data : bytes):
98
+ def write(self, data : Union[bytes, str]):
53
99
  """
54
100
  Send data to the device
101
+
102
+ Parameters
103
+ ----------
104
+ data : bytes or str
55
105
  """
56
106
  pass
57
-
107
+
58
108
  @abstractmethod
59
- def read(self, timeout=None, continuation_timeout=None, until_char=None) -> bytes:
109
+ def _start_thread(self):
60
110
  """
61
- Read data from the device
111
+ Initiate the read thread
62
112
  """
63
113
  pass
114
+
115
+ def read(self, timeout=None, stop_condition=None) -> bytes:
116
+ """
117
+ Read data from the device
64
118
 
65
- @abstractmethod
66
- def query(self, data : bytes, timeout=None, continuation_timeout=None) -> bytes:
119
+ Parameters
120
+ ----------
121
+ timeout : Timeout or None
122
+ Set a custom timeout, if None (default), the adapter timeout is used
123
+ stop_condition : StopCondition or None
124
+ Set a custom stop condition, if None (Default), the adapater stop condition is used
125
+ """
126
+ if self._status == self.Status.DISCONNECTED:
127
+ self.open()
128
+
129
+ # Use adapter values if no custom value is specified
130
+ if timeout is None:
131
+ timeout = self._timeout
132
+
133
+ if stop_condition is None:
134
+ stop_condition = self._stop_condition
135
+
136
+ # If the adapter is closed, open it
137
+ if self._status == self.Status.DISCONNECTED:
138
+ self.open()
139
+
140
+ if self._thread is None or not self._thread.is_alive():
141
+ self._start_thread()
142
+
143
+ timeout_ms = timeout.initiate_read(len(self._previous_read_buffer) > 0)
144
+
145
+ if stop_condition is not None:
146
+ stop_condition.initiate_read()
147
+
148
+ deferred_buffer = b''
149
+
150
+ # Start with the deferred buffer
151
+ if len(self._previous_read_buffer) > 0 and stop_condition is not None:
152
+ stop, output, self._previous_read_buffer = stop_condition.evaluate(self._previous_read_buffer)
153
+ else:
154
+ stop = False
155
+ output = b''
156
+ # If everything is used up, read the queue
157
+ if not stop:
158
+ while True:
159
+ (timestamp, fragment) = self._read_queue.get(timeout_ms)
160
+
161
+ # 1) Evaluate the timeout
162
+ stop, timeout_ms = timeout.evaluate(timestamp)
163
+ if stop:
164
+ data_strategy, origin = timeout.dataStrategy()
165
+ if data_strategy == Timeout.OnTimeoutStrategy.DISCARD:
166
+ # Trash everything
167
+ output = b''
168
+ elif data_strategy == Timeout.OnTimeoutStrategy.RETURN:
169
+ # Return the data that has been read up to this point
170
+ output += deferred_buffer
171
+ if fragment is not None:
172
+ output += fragment
173
+ elif data_strategy == Timeout.OnTimeoutStrategy.STORE:
174
+ # Store the data
175
+ self._previous_read_buffer = output
176
+ output = b''
177
+ elif data_strategy == Timeout.OnTimeoutStrategy.ERROR:
178
+ raise TimeoutException(origin)
179
+ break
180
+
181
+
182
+ # Add the deferred buffer
183
+ if len(deferred_buffer) > 0:
184
+ fragment = deferred_buffer + fragment
185
+
186
+ # 2) Evaluate the stop condition
187
+ if stop_condition is not None:
188
+ stop, kept_fragment, deferred_buffer = stop_condition.evaluate(fragment)
189
+ output += kept_fragment
190
+ if stop:
191
+ self._previous_read_buffer = deferred_buffer
192
+ else:
193
+ output += fragment
194
+ if stop:
195
+ break
196
+ if self._logger:
197
+ self._logger.log_read(output, self._previous_read_buffer)
198
+
199
+ return output
200
+
201
+ def query(self, data : Union[bytes, str], timeout=None, stop_condition=None) -> bytes:
67
202
  """
68
203
  Shortcut function that combines
69
204
  - flush_read
70
205
  - write
71
206
  - read
72
207
  """
73
- pass
208
+ pass
209
+
210
+ def __del__(self):
211
+ self.close()