serial-com 0.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.

Potentially problematic release.


This version of serial-com might be problematic. Click here for more details.

serial_com/__init__.py ADDED
File without changes
serial_com/ip_port.py ADDED
@@ -0,0 +1,124 @@
1
+ import socket
2
+ import select
3
+
4
+ from serial_com.serial_com import Port
5
+ from logger.logger import serial_logger as logger
6
+
7
+
8
+ class SocketClosedError(Exception):
9
+ ...
10
+
11
+
12
+ class IPPort(Port, socket.socket):
13
+
14
+ chunk_size = 1024
15
+
16
+ def __init__(self, *args, addr_port: tuple[str, int] = None,
17
+ read_timeout: float = 0.5, **kwargs):
18
+ """To intialize the object call IPPort()"""
19
+ super(IPPort, self).__init__(socket.AF_INET, socket.SOCK_STREAM, *args, **kwargs)
20
+ self.addr_port = addr_port
21
+ self.read_timeout = read_timeout
22
+
23
+ @property
24
+ def name(self):
25
+ return str(self.addr_port)
26
+
27
+ def apply_settings(self, data: dict):
28
+ self.read_timeout = data["timeout"]
29
+
30
+ def read(self, size=chunk_size, *args, **kwargs) -> bytes:
31
+ try:
32
+ ans = super().recv(size)
33
+ except TimeoutError:
34
+ logger.debug(f"{self} no answer")
35
+ ans = b""
36
+ except OSError as e:
37
+ if e.errno in (10038, 10054): # socket was closed
38
+ raise SocketClosedError("Socket was closed. A new one must be created")
39
+ return ans
40
+
41
+ def write(self, bl: bytes, *args, **kwargs) -> int:
42
+ try:
43
+ return super().send(bl)
44
+ except OSError as e:
45
+ if e.errno in (10038, 10054): # socket was closed
46
+ raise SocketClosedError("Socket was closed. A new one must be created")
47
+
48
+ def read_until(self):
49
+ buffer = []
50
+ is_carriage = False
51
+ while True:
52
+ chunk = self.read(1)
53
+ if not chunk:
54
+ break
55
+ if is_carriage:
56
+ if chunk == b"\n":
57
+ buffer.append(chunk)
58
+ break
59
+ else:
60
+ is_carriage = False
61
+ else:
62
+ if chunk == b"\r":
63
+ is_carriage = True
64
+ buffer.append(chunk)
65
+ return b"".join(buffer)
66
+
67
+ @property
68
+ def in_waiting(self) -> int:
69
+ sockets = select.select([self], [], [], 0.1)
70
+ if sockets[0]:
71
+ return self.chunk_size
72
+ return 0
73
+
74
+ @property
75
+ def out_waiting(self) -> int:
76
+ return 0
77
+
78
+ def reset_input_buffer(self) -> None:
79
+ if self.in_waiting:
80
+ self.read()
81
+
82
+ def reset_output_buffer(self) -> None:
83
+ ...
84
+
85
+ def open(self):
86
+ if self.fileno() == -1:
87
+ raise SocketClosedError
88
+ try:
89
+ self.connect(self.addr_port)
90
+ except OSError as e:
91
+ if e.errno == 10056:
92
+ # normal state: if the socket is opened it throws 10056
93
+ pass
94
+ else:
95
+ logger.debug(f"On trying to connect to {self} e")
96
+ raise e
97
+
98
+ def close(self):
99
+ self.close()
100
+
101
+ def is_open(self):
102
+ """As the socket can't be checked properly if it's connected
103
+ return False, assuming that .open method can be called easily"""
104
+ try:
105
+ sent = super().send(b"A")
106
+ except OSError as e:
107
+ if e.errno in (10038, 10054): # socket was closed
108
+ return False
109
+ raise e
110
+ if sent:
111
+ return True
112
+ return False
113
+
114
+
115
+
116
+ def is_closed(self):
117
+ ...
118
+
119
+ def __call__(self):
120
+ return IPPort(addr_port=self.addr_port, read_timeout=self.read_timeout)
121
+
122
+
123
+
124
+
@@ -0,0 +1,604 @@
1
+ from signal import signal, SIGPIPE, SIG_DFL
2
+ signal(SIGPIPE, SIG_DFL)
3
+
4
+ import socket
5
+ import time
6
+ from typing import Iterator
7
+ import select
8
+ from sys import platform
9
+ from abc import ABC, abstractmethod
10
+ import re
11
+ from dataclasses import dataclass
12
+ import serial
13
+ from time import sleep
14
+ from threading import Event
15
+ from threading import Event, Lock
16
+ import socket
17
+ # from custom_types import Device
18
+
19
+ import crcmod
20
+
21
+ import logging
22
+ from logger.logger import Logger
23
+ logger = Logger("serial_com", logging.DEBUG)
24
+
25
+ SERIAL_PORT = "serial"
26
+ NETWORK_PORT = "network"
27
+ PORT_ACCESS = Event()
28
+ PORT_ACCESS.clear()
29
+ MIN_TIMEOUT = 0.05
30
+
31
+ class SocketClosedError(Exception):
32
+ ...
33
+
34
+
35
+ class Port(ABC):
36
+
37
+ @abstractmethod
38
+ def read(self, size=-1, *args, **kwargs) -> bytes:
39
+ ...
40
+
41
+ @property
42
+ @abstractmethod
43
+ def name(self) -> str:
44
+ ...
45
+
46
+ @abstractmethod
47
+ def write(self, bl: bytes, *args, **kwargs) -> int:
48
+ ...
49
+
50
+ @abstractmethod
51
+ def read_until(self, *args, **kwargs) -> None:
52
+ """Read until new line"""
53
+ ...
54
+
55
+ @property
56
+ @abstractmethod
57
+ def in_waiting(self) -> int:
58
+ ...
59
+
60
+ @property
61
+ def read_timeout(self) -> float:
62
+ ...
63
+
64
+ @property
65
+ @abstractmethod
66
+ def out_waiting(self) -> int:
67
+ ...
68
+
69
+ @abstractmethod
70
+ def reset_input_buffer(self) -> None:
71
+ ...
72
+
73
+ @abstractmethod
74
+ def reset_output_buffer(self) -> None:
75
+ ...
76
+
77
+ @abstractmethod
78
+ def open(self):
79
+ ...
80
+
81
+ @abstractmethod
82
+ def close(self):
83
+ ...
84
+
85
+ @abstractmethod
86
+ def is_open(self):
87
+ ...
88
+
89
+ @abstractmethod
90
+ def is_closed(self):
91
+ ...
92
+
93
+
94
+ class SerialPort(serial.Serial):
95
+
96
+ def __call__(self):
97
+ return SerialPort(port=self.port, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity,
98
+ stopbits=self.stopbits, timeout=self.timeout, write_timeout=self.write_timeout)
99
+
100
+ def read_until(self, eol: bytes):
101
+ if eol == b"\r\n":
102
+ return self.readline()
103
+ leneol = len(eol)
104
+ response = bytearray()
105
+ while True:
106
+ ans = self.read(1)
107
+ if not ans:
108
+ logger.info(
109
+ "Was waiting for %s but stopped reading on timeout and received %s" % (
110
+ eol.__repr__(), response.__repr__()))
111
+ return
112
+ if ans not in eol:
113
+ continue
114
+ response.append(ans)
115
+ if response[-leneol:] == eol:
116
+ return response
117
+
118
+
119
+ class IPPort(socket.socket):
120
+
121
+ chunk_size = 1024
122
+
123
+ def __init__(self, *args, addr_port: tuple[str, int]|None = None,
124
+ read_timeout: float = 0.5, **kwargs):
125
+ """To intialize the object call IPPort()"""
126
+ super(IPPort, self).__init__(socket.AF_INET, socket.SOCK_STREAM, *args, **kwargs)
127
+ self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
128
+ self.addr_port = addr_port
129
+ self._read_timeout = read_timeout
130
+
131
+ @property
132
+ def name(self):
133
+ return str(self.addr_port)
134
+
135
+ def apply_settings(self, data: dict):
136
+ self.read_timeout = data["timeout"]
137
+
138
+ @property
139
+ def read_timeout(self) -> float|None:
140
+ return self.gettimeout()
141
+
142
+ @read_timeout.setter
143
+ def read_timeout(self, value: float):
144
+ self.settimeout(value)
145
+
146
+ def read(self, size=chunk_size, *args, **kwargs) -> bytes:
147
+ try:
148
+ ans = super().recv(size)
149
+ except TimeoutError:
150
+ logger.debug(f"{self} no answer")
151
+ ans = b""
152
+ except OSError as e:
153
+ if e.errno in (10038, 10054): # socket was closed
154
+ raise SocketClosedError("Socket was closed. A new one must be created")
155
+ return ans
156
+
157
+ def write(self, bl: bytes, *args, **kwargs) -> int:
158
+ try:
159
+ return super().send(bl)
160
+ except OSError as e:
161
+ if platform == "win32":
162
+ if e.errno in (10038, 10054): # socket was closed
163
+ raise SocketClosedError("Socket was closed. A new one must be created")
164
+ elif platform == "linux":
165
+ if e.errno == 104:
166
+ raise SocketClosedError("Socket was closed. A new one must be created")
167
+ raise e
168
+
169
+ def read_until(self, eol:bytes=b"\r\n"):
170
+ leneol = len(eol)
171
+ response = bytearray()
172
+ while True:
173
+ try:
174
+ ans = self.recv(1)
175
+ except TimeoutError:
176
+ ans = b""
177
+ if not ans:
178
+ logger.info(
179
+ "Was waiting for %s but stopped reading on timeout and received %s" % (
180
+ eol.__repr__(), response.__repr__()))
181
+ return
182
+ response.extend(ans)
183
+ if ans not in eol:
184
+ continue
185
+ if response[-leneol:] == eol:
186
+ return response
187
+
188
+ @property
189
+ def in_waiting(self) -> int:
190
+ sockets = select.select([self], [], [], 0.01)
191
+ if sockets[0]:
192
+ return self.chunk_size
193
+ return 0
194
+
195
+ @property
196
+ def out_waiting(self) -> int:
197
+ return 0
198
+
199
+ def reset_input_buffer(self) -> None:
200
+ if self.in_waiting:
201
+ self.read()
202
+
203
+ def reset_output_buffer(self) -> None:
204
+ ...
205
+
206
+ def open(self):
207
+ if self.fileno() == -1:
208
+ raise SocketClosedError("Can't open closed socket")
209
+ try:
210
+ self.connect(self.addr_port)
211
+ except OSError as e:
212
+ if platform == "win32":
213
+ if e.errno == 10056:
214
+ # normal state: if the socket is opened it throws 10056
215
+ pass
216
+ else:
217
+ logger.debug(f"On trying to connect to {self} e")
218
+ raise e
219
+ elif platform == "linux":
220
+ if e.errno == 106:
221
+ # normal state: if the socket is opened it throws 10056
222
+ pass
223
+ else:
224
+ logger.debug(f"On trying to connect to {self} e")
225
+ raise e
226
+ else:
227
+ raise SystemError("The platform is not supported")
228
+
229
+ def close(self):
230
+ super().close()
231
+
232
+ def is_open(self):
233
+ """As the socket can't be checked properly if it's connected
234
+ return False, assuming that .open method can be called easily"""
235
+ try:
236
+ sent = super().send(b"A")
237
+ except OSError as e:
238
+ if e.errno in (10038, 10054): # socket was closed
239
+ return False
240
+ raise e
241
+ if sent:
242
+ return True
243
+ return False
244
+
245
+
246
+
247
+ def is_closed(self):
248
+ ...
249
+
250
+ def __call__(self):
251
+ return IPPort(addr_port=self.addr_port, read_timeout=self.read_timeout)
252
+
253
+
254
+ @dataclass
255
+ class WorkerProperty:
256
+ """
257
+ params:
258
+ port_type: can be "serial" or "network"
259
+ listener: any unique string that is needed to validate listeners of the port
260
+ timeout: maximum time in seconds during which the port block
261
+ name: for "serial" it is "COM1", ""COM13", etc. For "network" - "123.123.123.123:3455"
262
+
263
+ """
264
+
265
+ port_type: str
266
+ name: str
267
+
268
+ def __init__(self, port_type: str = SERIAL_PORT|NETWORK_PORT, name: str = "", listener: str = "", baudrate: int = 19200): #TODO: stopbits etc.
269
+ if port_type not in (SERIAL_PORT, NETWORK_PORT):
270
+ raise ValueError(f"Invalid port type for PortProperty {port_type}")
271
+ if port_type == SERIAL_PORT:
272
+ if not re.match(r"COM\d{1,3}", name) and not name.startswith("/dev/"):
273
+ raise ValueError(f"Invalid port name {name}")
274
+
275
+ # if int(name.replace("COM", "")) not in range(0, 256):
276
+ # raise ValueError(f"Invalid port name {name}")
277
+
278
+ self.port_type = port_type
279
+ self.name = name
280
+ self.listener = listener
281
+ self.baudrate = baudrate
282
+
283
+
284
+ class PortsUsed:
285
+ """
286
+ Attrs:
287
+ self._port: dict
288
+ A dictionary that contains ports in the way
289
+ {port_name: serial.Serial}
290
+ """
291
+
292
+ def __init__(self):
293
+ self._ports = {
294
+ }
295
+
296
+ def add_port(self, worker_property: WorkerProperty):
297
+ """If there is no port with the given worker_property.name - create a new one
298
+ and add it to self._ports. Don't open it
299
+ Sometime all devices that uses a port will stop polling. But the port
300
+ will still be in the list in closed state. So it must be reusable."""
301
+ if worker_property.name in self._ports:
302
+ logger.debug(f"Port {worker_property.name} was already created")
303
+ self._add_listener(worker_property)
304
+ return
305
+ if worker_property.port_type == SERIAL_PORT:
306
+ if worker_property.name not in find_com_ports():
307
+ logger.info(f"{worker_property.name} is not ready")
308
+ return
309
+ port = SerialPort(
310
+ rtscts=False, dsrdtr=False, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS,
311
+ baudrate=worker_property.baudrate, port=worker_property.name, stopbits=serial.STOPBITS_ONE, write_timeout=0)
312
+ logger.info(f"new port is created for {worker_property}")
313
+ sleep(0.05)
314
+ elif worker_property.port_type == NETWORK_PORT:
315
+ addr, port = worker_property.name.split(":")
316
+ port = int(port)
317
+ port = IPPort(addr_port=(addr, port))
318
+ try:
319
+ self._ports[worker_property.name] = {
320
+ "port": port,
321
+ "port_type": worker_property.port_type,
322
+ "listeners": [],
323
+ "lock": Lock()
324
+ }
325
+ except NameError as e:
326
+ logger.exception(f"Unsupported port type worker_property.port_type")
327
+ raise e
328
+ self._add_listener(worker_property)
329
+ logger.info(f"Port is prepared {WorkerProperty}")
330
+
331
+ def close_port(self, port_name: str, dev_id):
332
+ port_data = self._ports.get(port_name)
333
+ if port_data is None:
334
+ message = f"Can't close port with {port_name=} because there is no such port"
335
+ logger.exception(message)
336
+ raise KeyError(message)
337
+ listeners: list = port_data["listeners"]
338
+ try:
339
+ listeners.pop(listeners.index(dev_id))
340
+ except ValueError:
341
+ logger.warning(f"{dev_id} was not among the {port_name} {listeners=}")
342
+ except IndexError:
343
+ logger.warning(f"Couldn't pop {dev_id} from list, {port_name} listeneres was empty")
344
+ if not listeners:
345
+ if port_data["port_type"] == SERIAL_PORT:
346
+ port: serial.Serial = port_data["port"]
347
+ if port.is_open:
348
+ port.close()
349
+ if port_data["port_type"] == NETWORK_PORT:
350
+ port: IPPort = port_data["port"]
351
+ port.close()
352
+ try:
353
+ del self._ports[port_name]
354
+ except Exception as e:
355
+ logger.error(f"{e} on closing {port_name}")
356
+
357
+
358
+ def remove_port(self):
359
+ raise NotImplementedError()
360
+
361
+ def get_handle(self, port_name: str, timeout: float) -> tuple[Port, Lock]:
362
+ if port_name not in self._ports:
363
+ raise KeyError(f"Port name is not found {port_name=}")
364
+ self._open_port(port_name)
365
+ port = self._ports[port_name]["port"]
366
+ lock = self._ports[port_name]["lock"]
367
+ try:
368
+ timeout = float(timeout)
369
+ except ValueError:
370
+ timeout = 0.35
371
+ port.apply_settings({"timeout": timeout})
372
+ if not port.is_open:
373
+ port.open()
374
+ return port, lock
375
+
376
+ def list_active_ports(self):
377
+ return list(self._ports.keys())
378
+
379
+ def _add_listener(self, worker_property: WorkerProperty):
380
+ if worker_property.listener in self._ports[worker_property.name]["listeners"]:
381
+ return
382
+ self._ports[worker_property.name]["listeners"].append(worker_property.listener)
383
+ logger.info(f"New listener {worker_property.listener} is added to {self._ports[worker_property.name]}")
384
+
385
+ def _open_port(self, port_name: str):
386
+ """Prepare the port to write and read data.
387
+ If throws serial.SerialException - handle it yourself"""
388
+ port_data = self._ports.get(port_name)
389
+ if port_data is None:
390
+ message = f"Can't open port with {port_name=}"
391
+ logger.error(message)
392
+ raise KeyError(message)
393
+ if port_data["port_type"] == SERIAL_PORT:
394
+ port: serial.Serial = port_data["port"]
395
+ if not port.is_open:
396
+ port.open()
397
+ elif port_data["port_type"] == NETWORK_PORT:
398
+ port: IPPort = port_data["port"]
399
+ try:
400
+ port.open()
401
+ except SocketClosedError:
402
+ port_data["port"] = port()
403
+ port = port_data["port"]
404
+ port.open()
405
+
406
+ def recreate_port(self, port_name):
407
+ self._ports[port_name]["port"] = self._ports[port_name]["port"]()
408
+
409
+
410
+ def listen_port(dev_id: str,
411
+ timeout: float,
412
+ length: int|None,
413
+ request: bytes,
414
+ port_name: str,
415
+ read_until=None) -> bytearray:
416
+ port, lock = get_port(port_name, timeout)
417
+ with lock:
418
+ logger.debug(f"Lock of port is acquire by {dev_id} {port} ")
419
+ try:
420
+ if request:
421
+ buffered_bytes = port.in_waiting
422
+ if buffered_bytes:
423
+ data = port.read(buffered_bytes)
424
+ logger.debug(f"On {port} unexpected data was received and not processed, packet_length={len(data)}")
425
+ logger.debug(f"{data.hex()}")
426
+ port.reset_output_buffer()
427
+ if buffered_bytes:
428
+ port.reset_input_buffer()
429
+ attempt = 0
430
+ logger.debug(f"{request.__repr__()} to {dev_id} will be sent on {port}")
431
+ ans = ser_request(request, attempt, port, length=length, read_until=read_until)
432
+ except (serial.SerialException, ) as e:
433
+ if "ClearCommError" in str(e):
434
+ CONNECTOR.recreate_port(port_name)
435
+ logger.debug(e)
436
+ raise e
437
+ except SocketClosedError as e:
438
+ CONNECTOR.recreate_port(port_name)
439
+ raise e
440
+ except Exception as e:
441
+ logger.debug(e)
442
+ raise e
443
+ finally:
444
+ logger.debug(F"lock of port is released de {dev_id} {port}")
445
+
446
+ return ans
447
+
448
+
449
+ def get_port(port_name: str, timeout: float) -> tuple[Port, Lock]:
450
+ port, lock = CONNECTOR.get_handle(port_name, timeout)
451
+ return port, lock
452
+
453
+
454
+ def ser_request(request: bytearray|bytes, attempt: int, port: Port, length=None, read_until: bytes|None=None):
455
+ """If length is not None - read given amount of bytes
456
+ if length is None, but read_until is not None - read until given bytes"""
457
+ max_retries = 10
458
+ if attempt <= max_retries:
459
+ try:
460
+ if request:
461
+ port.write(request)
462
+ if length is None:
463
+ if read_until is not None:
464
+ ser_ans = port.read_until(read_until)
465
+ else:
466
+ timeout = port.read_timeout
467
+ ans = bytearray()
468
+ init_time = time()
469
+ end_time = init_time + float(timeout)
470
+ while True:
471
+ try:
472
+ if not port.in_waiting:
473
+ if ans: # answer was recieved completely
474
+ break
475
+ continue
476
+ ans.extend(port.read(port.in_waiting))
477
+ finally:
478
+ sleep(MIN_TIMEOUT)
479
+ if time() > end_time:
480
+ break
481
+ ser_ans = bytes(ser_ans)
482
+ else:
483
+ ser_ans = port.read(length)
484
+ # make sure there is no trailing data, e.g. in passive reading
485
+ # if so - clear the buffer
486
+ trailing_data_count = port.in_waiting
487
+ if trailing_data_count:
488
+ trailing_data = port.read(trailing_data_count)
489
+ logger.debug(f"On request '{request.hex()}' unexpected data after the expected was received: {trailing_data.hex()}. It wasn't saved to DB")
490
+ sleep(0.1)
491
+ return ser_ans
492
+ except SocketClosedError as e:
493
+ raise e
494
+ except Exception as e:
495
+ sleep(1)
496
+ logger.info(f"Unsuccessful attempt to poll device{e}")
497
+ ser_request(request, attempt + 1, port, length, read_until)
498
+ else:
499
+ raise ConnectionError(f"Couldn't read serial data after {max_retries} unsuccessful attempts")
500
+
501
+
502
+ def tcp_exchange(tn, bl: bytes):
503
+ tn.write(bl)
504
+ return tn.read_until(b'\x0D\x0A', timeout=300)
505
+
506
+
507
+ def find_com_ports() -> list:
508
+ from serial.tools import list_ports
509
+ ports = list_ports.comports()
510
+ logger.debug(f'Found ports {ports}')
511
+ available_ports = []
512
+ available_ports.extend(CONNECTOR.list_active_ports())
513
+
514
+ for port in ports:
515
+ logger.debug(f"{port.device=}{available_ports=}")
516
+ if port.device in available_ports:
517
+ continue
518
+ try:
519
+ uart = serial.Serial(port=port.device, rtscts=False, dsrdtr=False)
520
+ logger.debug(f"Trying to open port {port}")
521
+ if uart.is_open:
522
+ sleep(0.2)
523
+ uart.close()
524
+ available_ports.append(port.device)
525
+ except serial.serialutil.SerialException:
526
+ continue
527
+ except Exception as e:
528
+ logger.error(e)
529
+
530
+ ports = sorted(set([i for i in available_ports]))
531
+
532
+ return ports
533
+
534
+ def change_netw_addr_n_crc(request: str, netw_addr: int) -> str:
535
+ """Convert request to one with correct network address
536
+ and CRC. netw_addr must be in range(0, 256)"""
537
+
538
+ netw_addr_hex = bytearray(int.to_bytes(netw_addr, 1, "big"))
539
+
540
+ request_body = bytearray.fromhex(request[2:-4])
541
+ netw_addr_hex.extend(request_body)
542
+ request_body = netw_addr_hex
543
+ crc = get_crc_bytes(request_body)
544
+ request_body.extend(crc)
545
+ request = request_body.hex()
546
+ return request
547
+
548
+
549
+ def get_crc(response: bytes) -> int:
550
+ """ if crc in response is correct return 0, else crc int"""
551
+ crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
552
+ return crc16(response)
553
+
554
+
555
+
556
+ def get_crc_bytes(bl: bytes) -> bytes:
557
+ """return reversed crc16 modbus"""
558
+ crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
559
+ crc = crc16(bl)
560
+ crc = hex(crc).replace("0x", "")
561
+ missing_zeroes = "0" * (4 - len(crc))
562
+ crc = missing_zeroes + crc
563
+ return bytes.fromhex(crc[2:]) + bytes.fromhex(crc[:2])
564
+
565
+
566
+ def is_crc_correct(bl: bytearray):
567
+ if get_crc(bl):
568
+ return False
569
+ return True
570
+
571
+
572
+ def find_connected_mbs_devices(device, pause_event: Event, stop_event: Event) -> Iterator:
573
+ """poll RS485 bus to find all modbus devices, return list of available addresses
574
+ device is Device"""
575
+
576
+ request, request_info = list(device.protocol.requests.items())[0]
577
+ serial_timeout = request_info.timeout
578
+ packet_length = request_info.expected_length
579
+ read_until = request_info.read_until
580
+ port_name = device.port_name
581
+ logger.debug(f"Start searching network address of {device.dev_id} with {serial_timeout=} {request=}")
582
+
583
+ for i in range(0, 256):
584
+ pause_event.wait()
585
+ if stop_event.is_set():
586
+ logger.Info("Network search was stopped")
587
+ return
588
+
589
+ ans = listen_port(
590
+ device.dev_id,
591
+ serial_timeout,
592
+ packet_length,
593
+ device.change_network_address_in_request(request, i),
594
+ port_name,
595
+ read_until)
596
+ if ans:
597
+ logger.debug(f'{i} address is online {ans=}')
598
+ yield i
599
+ else:
600
+ logger.debug(f'{i} address is offline')
601
+
602
+
603
+
604
+ CONNECTOR = PortsUsed()
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.3
2
+ Name: serial-com
3
+ Version: 0.1
4
+ Summary:
5
+ Author: Andrey Linyushin
6
+ Author-email: 89202979894@mail.ru
7
+ Requires-Python: >=3.12
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Requires-Dist: crcmod (>=1.7,<2.0)
12
+ Requires-Dist: pyserial (>=3.5,<4.0)
13
+ Description-Content-Type: text/markdown
14
+
15
+ ## Tech-automatics package for operations with com ports
@@ -0,0 +1,6 @@
1
+ serial_com/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ serial_com/ip_port.py,sha256=PwCCsK2_mK3ssN0zFw3Azpc1-nQfnF8-5VaKTHRpdlw,3353
3
+ serial_com/serial_com.py,sha256=6EgqQcCt4H82Af8h_jtlhDlTkgX01W8x1cXUBtwy7IQ,20010
4
+ serial_com-0.1.dist-info/METADATA,sha256=Ka0VHX9rwX3tLCHqjgivksZPpyIf9KS7W9RCTNdSVzQ,465
5
+ serial_com-0.1.dist-info/WHEEL,sha256=RaoafKOydTQ7I_I3JTrPCg6kUmTgtm4BornzOqyEfJ8,88
6
+ serial_com-0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.0.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any