syndesi 0.1.4__tar.gz → 0.1.6__tar.gz

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 (58) hide show
  1. {syndesi-0.1.4/syndesi.egg-info → syndesi-0.1.6}/PKG-INFO +18 -14
  2. {syndesi-0.1.4 → syndesi-0.1.6}/README.md +17 -13
  3. syndesi-0.1.6/bin/syndesi +57 -0
  4. {syndesi-0.1.4 → syndesi-0.1.6}/setup.cfg +0 -0
  5. {syndesi-0.1.4 → syndesi-0.1.6}/setup.py +1 -1
  6. syndesi-0.1.6/syndesi/adapters/__init__.py +7 -0
  7. syndesi-0.1.6/syndesi/adapters/adapter.py +304 -0
  8. syndesi-0.1.6/syndesi/adapters/auto.py +45 -0
  9. syndesi-0.1.6/syndesi/adapters/ip.py +124 -0
  10. syndesi-0.1.6/syndesi/adapters/remote.py +18 -0
  11. syndesi-0.1.6/syndesi/adapters/serialport.py +128 -0
  12. syndesi-0.1.6/syndesi/adapters/stop_conditions.py +155 -0
  13. syndesi-0.1.6/syndesi/adapters/timed_queue.py +32 -0
  14. syndesi-0.1.6/syndesi/adapters/timeout.py +287 -0
  15. {syndesi-0.1.4 → syndesi-0.1.6}/syndesi/adapters/visa.py +12 -8
  16. syndesi-0.1.6/syndesi/protocols/__init__.py +5 -0
  17. syndesi-0.1.6/syndesi/protocols/delimited.py +101 -0
  18. syndesi-0.1.6/syndesi/protocols/protocol.py +17 -0
  19. syndesi-0.1.6/syndesi/protocols/raw.py +28 -0
  20. syndesi-0.1.6/syndesi/protocols/scpi.py +82 -0
  21. syndesi-0.1.6/syndesi/protocols/sdp.py +14 -0
  22. {syndesi-0.1.4/syndesi/descriptors/syndesi → syndesi-0.1.6/syndesi/tools}/__init__.py +0 -0
  23. syndesi-0.1.6/syndesi/tools/exceptions.py +10 -0
  24. syndesi-0.1.6/syndesi/tools/log.py +106 -0
  25. syndesi-0.1.6/syndesi/tools/others.py +10 -0
  26. syndesi-0.1.6/syndesi/tools/types.py +80 -0
  27. {syndesi-0.1.4 → syndesi-0.1.6/syndesi.egg-info}/PKG-INFO +18 -14
  28. syndesi-0.1.6/syndesi.egg-info/SOURCES.txt +30 -0
  29. syndesi-0.1.4/bin/syndesi +0 -1
  30. syndesi-0.1.4/syndesi/adapters/__init__.py +0 -4
  31. syndesi-0.1.4/syndesi/adapters/iadapter.py +0 -73
  32. syndesi-0.1.4/syndesi/adapters/ip.py +0 -82
  33. syndesi-0.1.4/syndesi/adapters/serial.py +0 -36
  34. syndesi-0.1.4/syndesi/descriptors/Serial.py +0 -10
  35. syndesi-0.1.4/syndesi/descriptors/__init__.py +0 -1
  36. syndesi-0.1.4/syndesi/descriptors/descriptor.py +0 -9
  37. syndesi-0.1.4/syndesi/descriptors/ip.py +0 -9
  38. syndesi-0.1.4/syndesi/descriptors/syndesi/Syndesi.py +0 -9
  39. syndesi-0.1.4/syndesi/descriptors/syndesi/_device.py +0 -25
  40. syndesi-0.1.4/syndesi/descriptors/syndesi/devices.py +0 -10
  41. syndesi-0.1.4/syndesi/descriptors/syndesi/frame.py +0 -133
  42. syndesi-0.1.4/syndesi/descriptors/syndesi/network.py +0 -41
  43. syndesi-0.1.4/syndesi/descriptors/syndesi/payload.py +0 -11
  44. syndesi-0.1.4/syndesi/descriptors/syndesi/sdid.py +0 -21
  45. syndesi-0.1.4/syndesi/descriptors/visa.py +0 -31
  46. syndesi-0.1.4/syndesi/protocols/__init__.py +0 -5
  47. syndesi-0.1.4/syndesi/protocols/delimited.py +0 -78
  48. syndesi-0.1.4/syndesi/protocols/iprotocol.py +0 -14
  49. syndesi-0.1.4/syndesi/protocols/raw.py +0 -79
  50. syndesi-0.1.4/syndesi/protocols/scpi.py +0 -62
  51. syndesi-0.1.4/syndesi/protocols/sdp.py +0 -14
  52. syndesi-0.1.4/syndesi/tools/__init__.py +0 -0
  53. syndesi-0.1.4/syndesi/tools/types.py +0 -47
  54. syndesi-0.1.4/syndesi.egg-info/SOURCES.txt +0 -35
  55. {syndesi-0.1.4 → syndesi-0.1.6}/LICENSE +0 -0
  56. {syndesi-0.1.4 → syndesi-0.1.6}/syndesi/__init__.py +0 -0
  57. {syndesi-0.1.4 → syndesi-0.1.6}/syndesi.egg-info/dependency_links.txt +0 -0
  58. {syndesi-0.1.4 → syndesi-0.1.6}/syndesi.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: syndesi
3
- Version: 0.1.4
3
+ Version: 0.1.6
4
4
  Summary: Syndesi
5
5
  Author: Sebastien Deriaz
6
6
  Author-email: sebastien.deriaz1@gmail.com
@@ -16,6 +16,8 @@ License-File: LICENSE
16
16
 
17
17
  # Syndesi Python Implementation
18
18
 
19
+ Syndesi description is available [here](https://github.com/syndesi-project/Syndesi/README.md)
20
+
19
21
  ## Installation
20
22
 
21
23
  The syndesi Python package can be installed through pip
@@ -25,14 +27,16 @@ The syndesi Python package can be installed through pip
25
27
  The package can also be installed locally by cloning this repository
26
28
 
27
29
  ```bash
28
- git clone ...
30
+ git clone https://github.com/syndesi-project/Syndesi
29
31
  cd Syndesi/Python
30
32
  pip install .
31
33
  ```
32
34
 
33
35
  ## Usage
34
36
 
35
- To instantiate a device / testbench, one must import the device and a suitable adapter
37
+
38
+
39
+ To instantiate a device, one must import the device and a suitable adapter
36
40
 
37
41
  ```python
38
42
  # 1) Import the device
@@ -46,16 +50,6 @@ mm = SDM3055(IP("192.168.1.123"))
46
50
  ## 4) Use
47
51
  voltage = mm.measure_dc_voltage()
48
52
  ```
49
-
50
- The Syndesi Python package provides the user with the necessary tools to control compatible devices
51
-
52
- - drivers : device-specific implementation
53
- - descriptors : Each class represents a particular way of connecting to a device, the user must provide que necessary information (IP, com port, ID, etc...)
54
- - communication wrapper (wrappers) : Wrappers for low-level communication (TCP, UDP, UART, etc...)
55
- - IP (TCP / UDP)
56
- - UART
57
- - USB (?)
58
-
59
53
  ## Layers
60
54
 
61
55
  The first layer is the "Device" base class
@@ -88,4 +82,14 @@ The Syndesi Device Protocol is a light-weight and easy interface to send / recei
88
82
 
89
83
  ## Notes
90
84
 
91
- 15.08.2023 : The adapters must work with bytearray data only
85
+ 06.09.2023 : bytearray is changed to bytes everywhere
86
+
87
+ 23.10.2023 : continuation timeout isn't suitable for TCP, but it can work for UDP as a UDP server can send multiple response packets after a single packet from the client. This can be handled in different ways by firewalls. Thankfull that's none of our business so continuation timeout can be implemented
88
+
89
+ 22.11.2023 : The timeout and stop conditions strategy is a bit complicated :
90
+
91
+ - What if we receive the message b'ACK\nNCK\n' using a termination stop condition but we receive b'ACK', then a timeout, then b'\nNCK\n' ?
92
+ - Should the first part be kept ? should an error be raised at the timeout because nothing was read ?
93
+ - Two kinds of timeouts ?
94
+ - One where "we read as much as possible during the available time"
95
+ - One where "we expect a response within X otherwise it's trash"
@@ -1,5 +1,7 @@
1
1
  # Syndesi Python Implementation
2
2
 
3
+ Syndesi description is available [here](https://github.com/syndesi-project/Syndesi/README.md)
4
+
3
5
  ## Installation
4
6
 
5
7
  The syndesi Python package can be installed through pip
@@ -9,14 +11,16 @@ The syndesi Python package can be installed through pip
9
11
  The package can also be installed locally by cloning this repository
10
12
 
11
13
  ```bash
12
- git clone ...
14
+ git clone https://github.com/syndesi-project/Syndesi
13
15
  cd Syndesi/Python
14
16
  pip install .
15
17
  ```
16
18
 
17
19
  ## Usage
18
20
 
19
- To instantiate a device / testbench, one must import the device and a suitable adapter
21
+
22
+
23
+ To instantiate a device, one must import the device and a suitable adapter
20
24
 
21
25
  ```python
22
26
  # 1) Import the device
@@ -30,16 +34,6 @@ mm = SDM3055(IP("192.168.1.123"))
30
34
  ## 4) Use
31
35
  voltage = mm.measure_dc_voltage()
32
36
  ```
33
-
34
- The Syndesi Python package provides the user with the necessary tools to control compatible devices
35
-
36
- - drivers : device-specific implementation
37
- - descriptors : Each class represents a particular way of connecting to a device, the user must provide que necessary information (IP, com port, ID, etc...)
38
- - communication wrapper (wrappers) : Wrappers for low-level communication (TCP, UDP, UART, etc...)
39
- - IP (TCP / UDP)
40
- - UART
41
- - USB (?)
42
-
43
37
  ## Layers
44
38
 
45
39
  The first layer is the "Device" base class
@@ -72,4 +66,14 @@ The Syndesi Device Protocol is a light-weight and easy interface to send / recei
72
66
 
73
67
  ## Notes
74
68
 
75
- 15.08.2023 : The adapters must work with bytearray data only
69
+ 06.09.2023 : bytearray is changed to bytes everywhere
70
+
71
+ 23.10.2023 : continuation timeout isn't suitable for TCP, but it can work for UDP as a UDP server can send multiple response packets after a single packet from the client. This can be handled in different ways by firewalls. Thankfull that's none of our business so continuation timeout can be implemented
72
+
73
+ 22.11.2023 : The timeout and stop conditions strategy is a bit complicated :
74
+
75
+ - What if we receive the message b'ACK\nNCK\n' using a termination stop condition but we receive b'ACK', then a timeout, then b'\nNCK\n' ?
76
+ - Should the first part be kept ? should an error be raised at the timeout because nothing was read ?
77
+ - Two kinds of timeouts ?
78
+ - One where "we read as much as possible during the available time"
79
+ - One where "we expect a response within X otherwise it's trash"
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env python
2
+
3
+ # Syndesi CLI
4
+ import argparse
5
+ from cmd import Cmd
6
+ from enum import Enum
7
+
8
+ class MyPrompt(Cmd):
9
+ prompt = '❯ '
10
+ intro = "Welcome! Type ? to list commands"
11
+
12
+ def do_exit(self, inp):
13
+ print("Bye !")
14
+ return True
15
+
16
+ def do_connect(self, inp):
17
+ print("Device")
18
+
19
+ def default(self, inp):
20
+ print(f"Entered : {inp}")
21
+
22
+
23
+ do_EOF = do_exit # Allow CTRL+d to exit
24
+
25
+
26
+ class SubCommands(Enum):
27
+ SHELL = 'shell'
28
+
29
+
30
+
31
+
32
+ def connect():
33
+ print("Entering connect subcommand...")
34
+
35
+ p = MyPrompt()
36
+ p.cmdloop()
37
+
38
+
39
+
40
+
41
+ def main():
42
+ parser = argparse.ArgumentParser(
43
+ prog='syndesi',
44
+ description='Syndesi command line interface',
45
+ epilog='')
46
+ # Parse subcommand
47
+ parser.add_argument('subcommand', choices=[SubCommands.SHELL.value])
48
+
49
+ args = parser.parse_args()
50
+
51
+ if args.subcommand == SubCommands.SHELL.value:
52
+ connect()
53
+
54
+
55
+
56
+ if __name__ == '__main__':
57
+ main()
File without changes
@@ -1,6 +1,6 @@
1
1
  from setuptools import setup, find_packages
2
2
 
3
- VERSION = '0.1.4'
3
+ VERSION = '0.1.6'
4
4
  DESCRIPTION = 'Syndesi'
5
5
 
6
6
  with open("README.md", "r", encoding="utf-8") as fh:
@@ -0,0 +1,7 @@
1
+ from .adapter import Adapter
2
+ from .ip import IP
3
+ from .serialport import SerialPort
4
+ from .visa import VISA
5
+
6
+ from .timeout import Timeout
7
+ from .stop_conditions import Termination, Length, StopCondition
@@ -0,0 +1,304 @@
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_argument, is_default_argument
33
+
34
+ DEFAULT_TIMEOUT = default_argument(Timeout(response=1, continuation=100e-3, total=None))
35
+ DEFAULT_STOP_CONDITION = default_argument(StopCondition())
36
+
37
+ STOP_DESIGNATORS = {
38
+ 'timeout' : {
39
+ Timeout.TimeoutType.RESPONSE : 'TR',
40
+ Timeout.TimeoutType.CONTINUATION : 'TC',
41
+ Timeout.TimeoutType.TOTAL : 'TT'
42
+ },
43
+ 'stop_condition' : {
44
+ Termination : 'ST',
45
+ Length : 'SL'
46
+ },
47
+ 'previous-read-buffer' : 'RB'
48
+ }
49
+
50
+ class Origin(Enum):
51
+ TIMEOUT = 'timeout'
52
+ STOP_CONDITION = 'stop_condition'
53
+
54
+ @dataclass
55
+ class ReturnMetrics:
56
+ read_duration : float
57
+ origin : Origin
58
+ timeout_type : Timeout.TimeoutType
59
+ stop_condition : StopCondition
60
+ previous_read_buffer_used : bool
61
+ n_fragments : int
62
+ response_time : float
63
+ continuation_times : list
64
+ total_time : float
65
+
66
+ class Adapter(ABC):
67
+ class Status(Enum):
68
+ DISCONNECTED = 0
69
+ CONNECTED = 1
70
+
71
+ def __init__(self,
72
+ alias : str = '',
73
+ timeout : Union[float, Timeout] = DEFAULT_TIMEOUT,
74
+ stop_condition : Union[StopCondition, None] = DEFAULT_STOP_CONDITION):
75
+ """
76
+ Adapter instance
77
+
78
+ Parameters
79
+ ----------
80
+ alias : str
81
+ The alias is used to identify the class in the logs
82
+ timeout : float or Timeout instance
83
+ Default timeout is Timeout(response=1, continuation=0.1, total=None)
84
+ stop_condition : StopCondition or None
85
+ Default to None
86
+ """
87
+
88
+ if is_number(timeout):
89
+ self._timeout = Timeout(response=timeout, continuation=100e-3)
90
+ elif isinstance(timeout, Timeout):
91
+ self._timeout = timeout
92
+ else:
93
+ raise ValueError(f"Invalid timeout type : {type(timeout)}")
94
+
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
+ # Buffer for data that has been pulled from the queue but
100
+ # not used because of termination or length stop condition
101
+ self._previous_read_buffer = b''
102
+
103
+ self._alias = alias
104
+ self._logger = logging.getLogger(LoggerAlias.ADAPTER.value)
105
+
106
+ def set_default_timeout(self, default_timeout : Union[Timeout, tuple, float]):
107
+ """
108
+ Set the default timeout for this adapter. If a previous timeout has been set, it will be fused
109
+
110
+ Parameters
111
+ ----------
112
+ default_timeout : Timeout or tuple or float
113
+ """
114
+ self._timeout = timeout_fuse(self._timeout, default_timeout)
115
+
116
+ def set_default_stop_condition(self, stop_condition):
117
+ """
118
+ Set the default stop condition for this adapter.
119
+
120
+ Parameters
121
+ ----------
122
+ stop_condition : StopCondition
123
+ """
124
+ if is_default_argument(self._stop_condition):
125
+ self._stop_condition = stop_condition
126
+
127
+
128
+ def flushRead(self):
129
+ """
130
+ Flush the input buffer
131
+ """
132
+ self._read_queue.clear()
133
+ self._previous_read_buffer = b''
134
+
135
+ @abstractmethod
136
+ def open(self):
137
+ """
138
+ Start communication with the device
139
+ """
140
+ pass
141
+
142
+ @abstractmethod
143
+ def close(self):
144
+ """
145
+ Stop communication with the device
146
+ """
147
+ pass
148
+
149
+ @abstractmethod
150
+ def write(self, data : Union[bytes, str]):
151
+ """
152
+ Send data to the device
153
+
154
+ Parameters
155
+ ----------
156
+ data : bytes or str
157
+ """
158
+ pass
159
+
160
+ @abstractmethod
161
+ def _start_thread(self):
162
+ """
163
+ Initiate the read thread
164
+ """
165
+ pass
166
+
167
+ def read(self, timeout=None, stop_condition=None, return_metrics : bool = False) -> bytes:
168
+ """
169
+ Read data from the device
170
+
171
+ Parameters
172
+ ----------
173
+ timeout : Timeout or None
174
+ Set a custom timeout, if None (default), the adapter timeout is used
175
+ stop_condition : StopCondition or None
176
+ Set a custom stop condition, if None (Default), the adapater stop condition is used
177
+ return_metrics : ReturnMetrics class
178
+ """
179
+ read_start = time()
180
+ if self._status == self.Status.DISCONNECTED:
181
+ self.open()
182
+
183
+ # Use adapter values if no custom value is specified
184
+ if timeout is None:
185
+ timeout = self._timeout
186
+ elif isinstance(timeout, float):
187
+ timeout = Timeout(timeout)
188
+
189
+
190
+ if stop_condition is None:
191
+ stop_condition = self._stop_condition
192
+
193
+ # If the adapter is closed, open it
194
+ if self._status == self.Status.DISCONNECTED:
195
+ self.open()
196
+
197
+ if self._thread is None or not self._thread.is_alive():
198
+ self._start_thread()
199
+
200
+ timeout_ms = timeout.initiate_read(len(self._previous_read_buffer) > 0)
201
+
202
+ if stop_condition is not None:
203
+ stop_condition.initiate_read()
204
+
205
+ deferred_buffer = b''
206
+
207
+ # Start with the deferred buffer
208
+ # TODO : Check if data could be lost here, like the data is put in the previous_read_buffer and is never
209
+ # read back again because there's no stop condition
210
+ if len(self._previous_read_buffer) > 0 and stop_condition is not None:
211
+ stop, output, self._previous_read_buffer = stop_condition.evaluate(self._previous_read_buffer)
212
+ previous_read_buffer_used = True
213
+ else:
214
+ stop = False
215
+ output = b''
216
+ previous_read_buffer_used = False
217
+
218
+ n_fragments = 0
219
+ # If everything is used up, read the queue
220
+ if not stop:
221
+ while True:
222
+ (timestamp, fragment) = self._read_queue.get(timeout_ms)
223
+ n_fragments += 1
224
+
225
+ # 1) Evaluate the timeout
226
+ stop, timeout_ms = timeout.evaluate(timestamp)
227
+ if stop:
228
+ data_strategy, origin = timeout.dataStrategy()
229
+ if data_strategy == Timeout.OnTimeoutStrategy.DISCARD:
230
+ # Trash everything
231
+ output = b''
232
+ elif data_strategy == Timeout.OnTimeoutStrategy.RETURN:
233
+ # Return the data that has been read up to this point
234
+ output += deferred_buffer
235
+ if fragment is not None:
236
+ output += fragment
237
+ elif data_strategy == Timeout.OnTimeoutStrategy.STORE:
238
+ # Store the data
239
+ self._previous_read_buffer = output
240
+ output = b''
241
+ elif data_strategy == Timeout.OnTimeoutStrategy.ERROR:
242
+ raise TimeoutException(origin)
243
+ break
244
+ else:
245
+ origin = None
246
+
247
+
248
+
249
+ # Add the deferred buffer
250
+ if len(deferred_buffer) > 0:
251
+ fragment = deferred_buffer + fragment
252
+
253
+ # 2) Evaluate the stop condition
254
+ if stop_condition is not None:
255
+ stop, kept_fragment, deferred_buffer = stop_condition.evaluate(fragment)
256
+ output += kept_fragment
257
+ if stop:
258
+ self._previous_read_buffer = deferred_buffer
259
+ else:
260
+ output += fragment
261
+ if stop:
262
+ break
263
+
264
+ if origin is not None:
265
+ # The stop originates from the timeout
266
+ designator = STOP_DESIGNATORS['timeout'][origin]
267
+ else:
268
+ designator = STOP_DESIGNATORS['stop_condition'][type(stop_condition)]
269
+ else:
270
+ designator = STOP_DESIGNATORS['previous-read-buffer']
271
+
272
+ read_duration = time() - read_start
273
+ if self._previous_read_buffer:
274
+ self._logger.debug(f'Read [{designator}, {read_duration*1e3:.3f}ms] : {output} , previous read buffer : {self._previous_read_buffer}')
275
+ else:
276
+ self._logger.debug(f'Read [{designator}, {read_duration*1e3:.3f}ms] : {output}')
277
+
278
+ if return_metrics:
279
+ return output, ReturnMetrics(
280
+ read_duration=read_duration,
281
+ origin=Origin.TIMEOUT if origin is not None else Origin.STOP_CONDITION,
282
+ timeout_type=origin if origin is not None else None,
283
+ stop_condition=type(stop_condition) if origin is None else None,
284
+ previous_read_buffer_used=previous_read_buffer_used,
285
+ n_fragments=n_fragments,
286
+ response_time=timeout.response_time,
287
+ continuation_times=timeout.continuation_times,
288
+ total_time=timeout.total_time
289
+ )
290
+ else:
291
+ return output
292
+
293
+ @abstractmethod
294
+ def query(self, data : Union[bytes, str], timeout=None, stop_condition=None, return_metrics : bool = False) -> bytes:
295
+ """
296
+ Shortcut function that combines
297
+ - flush_read
298
+ - write
299
+ - read
300
+ """
301
+ pass
302
+
303
+ def __del__(self):
304
+ self.close()
@@ -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}")
@@ -0,0 +1,124 @@
1
+ import socket
2
+ from enum import Enum
3
+ from .adapter import Adapter
4
+ from ..tools.types import to_bytes
5
+ from .timeout import Timeout
6
+ from threading import Thread
7
+ from .timed_queue import TimedQueue
8
+ from typing import Union
9
+ from time import time
10
+
11
+ DEFAULT_RESPONSE_TIMEOUT = 1
12
+ DEFAULT_CONTINUATION_TIMEOUT = 1e-3
13
+ DEFAULT_TOTAL_TIMEOUT = 5
14
+
15
+ DEFAULT_BUFFER_SIZE = 1024
16
+
17
+ DEFAULT_TIMEOUT = Timeout(
18
+ response=DEFAULT_RESPONSE_TIMEOUT,
19
+ continuation=DEFAULT_CONTINUATION_TIMEOUT,
20
+ total=DEFAULT_TOTAL_TIMEOUT)
21
+
22
+ class IP(Adapter):
23
+ class Protocol(Enum):
24
+ TCP = 'TCP'
25
+ UDP = 'UDP'
26
+ def __init__(self,
27
+ address : str,
28
+ port : int = None,
29
+ transport : str = 'TCP',
30
+ timeout : Union[Timeout, float] = DEFAULT_TIMEOUT,
31
+ stop_condition = None,
32
+ alias : str = '',
33
+ buffer_size : int = DEFAULT_BUFFER_SIZE):
34
+ """
35
+ IP stack adapter
36
+
37
+ Parameters
38
+ ----------
39
+ address : str
40
+ IP description
41
+ port : int
42
+ IP port
43
+ transport : str
44
+ 'TCP' or 'UDP'
45
+ timeout : Timeout | float
46
+ Specify communication timeout
47
+ stop_condition : StopCondition
48
+ Specify a read stop condition (None by default)
49
+ alias : str
50
+ Specify an alias for this adapter, '' by default
51
+ buffer_size : int
52
+ Socket buffer size, may be removed in the future
53
+ """
54
+ super().__init__(alias=alias, timeout=timeout, stop_condition=stop_condition)
55
+ self._transport = self.Protocol(transport)
56
+ if self._transport == self.Protocol.TCP:
57
+ self._logger.info("Setting up TCP IP adapter")
58
+ self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
59
+ elif self._transport == self.Protocol.UDP:
60
+ self._logger.info("Setting up UDP IP adapter")
61
+ self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
62
+ else:
63
+ raise ValueError("Invalid protocol")
64
+ self._address = address
65
+ self._port = port
66
+ self._buffer_size = buffer_size
67
+
68
+ def set_default_port(self, port):
69
+ """
70
+ Sets IP port if no port has been set yet.
71
+
72
+ This way, the user can leave the port empty
73
+ and the driver/protocol can specify it later
74
+
75
+ Parameters
76
+ ----------
77
+ port : int
78
+ """
79
+ if self._port is None:
80
+ self._port = port
81
+
82
+ def open(self):
83
+ if self._port is None:
84
+ raise ValueError(f"Cannot open adapter without specifying a port")
85
+ self._socket.connect((self._address, self._port))
86
+ self._status = self.Status.CONNECTED
87
+ self._logger.info("Adapter opened !")
88
+
89
+ def close(self):
90
+ if hasattr(self, '_socket'):
91
+ self._socket.close()
92
+ self._logger.info("Adapter closed !")
93
+
94
+ def write(self, data : Union[bytes, str]):
95
+ data = to_bytes(data)
96
+ if self._status == self.Status.DISCONNECTED:
97
+ self._logger.info("Adapter is closed, opening...")
98
+ self.open()
99
+ write_start = time()
100
+ self._socket.send(data)
101
+ write_duration = time() - write_start
102
+ self._logger.debug(f"Written [{write_duration*1e3:.3f}ms]: {repr(data)}")
103
+
104
+ def _read_thread(self, socket : socket.socket, read_queue : TimedQueue):
105
+ while True:
106
+ try:
107
+ payload = socket.recv(self._buffer_size)
108
+ if len(payload) == self._buffer_size and self._transport == self.Protocol.UDP:
109
+ self._logger.warning("Warning, inbound UDP data may have been lost (max buffer size attained)")
110
+ except OSError:
111
+ break
112
+ if not payload:
113
+ break
114
+ read_queue.put(payload)
115
+
116
+ def _start_thread(self):
117
+ self._logger.debug("Starting read thread...")
118
+ self._thread = Thread(target=self._read_thread, daemon=True, args=(self._socket, self._read_queue))
119
+ self._thread.start()
120
+
121
+ def query(self, data : Union[bytes, str], timeout=None, stop_condition=None, return_metrics : bool = False):
122
+ self.flushRead()
123
+ self.write(data)
124
+ return self.read(timeout=timeout, stop_condition=stop_condition, return_metrics=return_metrics)
@@ -0,0 +1,18 @@
1
+ # remote.py
2
+ # Sébastien Deriaz
3
+ # 09.04.2024
4
+ #
5
+ # The remote adapter allows for commands to be issued on a different device through TCP
6
+ # The goal is to istanciate a class as such :
7
+ #
8
+ # Only adapter :
9
+ # # The remote computer is accessed with 192.168.1.1
10
+ # # The device (connected to the remote computer) is accessed with 192.168.2.1
11
+ # my_adapter = Remote('192.168.1.1', IP('192.168.2.1'))
12
+ #
13
+ # Protocol :
14
+ # my_protocol = SCPI(Remote('192.168.1.1', Serial('/dev/ttyUSB0')))
15
+ #
16
+ #
17
+ # Driver :
18
+ # my_device = Driver(Remote('192.168.1.1', VISA('...')))