communications.py
27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
# -*- coding: utf-8 -*-
import time
import socket
import serial
import serial.tools.list_ports
import traceback
import sys
try:
from .guitastrotools import GuitastroException
except:
from guitastrotools import GuitastroException
# #####################################################################
# #####################################################################
# #####################################################################
# Class communication
# #####################################################################
# #####################################################################
# #####################################################################
class CommunicationException(GuitastroException):
ERR_FILE_NOT_EXISTS = 0
ERR_CHAN_OPEN = 1
ERR_CHAN_UNKNOWN = 2
ERR_CHAN_PORT_NOT_FOUND = 3
ERR_CHAN_CLOSE = 4
ERR_CHAN_NOT_OPENED = 5
ERR_CHAN_PORT_NOT_DEFINED = 6
ERR_CHAN_EVER_OPENED = 7
ERR_CHAN_HOSTNAME_NOT_DEFINED = 8
ERR_CHAN_TCP_RECV_TIMEOUT = 9
ERR_CHAN_PUTREAD_LOCKED = 10
errors = [""]*11
errors[ERR_FILE_NOT_EXISTS] = "The named file was not found"
errors[ERR_CHAN_OPEN] = ""
errors[ERR_CHAN_UNKNOWN] = ""
errors[ERR_CHAN_PORT_NOT_FOUND] = ""
errors[ERR_CHAN_CLOSE] = ""
errors[ERR_CHAN_PORT_NOT_DEFINED] = ""
errors[ERR_CHAN_EVER_OPENED] = "Channel already opened"
errors[ERR_CHAN_HOSTNAME_NOT_DEFINED] = ""
errors[ERR_CHAN_TCP_RECV_TIMEOUT] = ""
errors[ERR_CHAN_PUTREAD_LOCKED] = "Channel is locked. See "
class Communication(CommunicationException):
"""Communication channel manager
This class allows to open and close TCP or SERIAL communications.
There are methods to put and read messages.
:Example:
To get only informations on communication channels SERIAL and TCP:
::
>>> chan = Communication("INFOS")
>>> available_serial_ports = chan.get_available_serial_ports()
>>> my_ip_address = chan.get_ip()
To open a SERIAL port:
::
>>> chan = Communication("SERIAL", port="//./COM1", baud_rate=9600)
To open a TCP port:
::
>>> chan = Communication("TCP", hostname="192.168.0.4", port="8080")
To close an opened port:
::
>>> chan.close()
To send a message through an opened port:
::
>>> chan.put("Hello")
To read a message through an opened port:
::
>>> result = chan.read()
Very often protocols need to add suffix characters to the messages.
The following optional keys can be added to Communication:
* END_OF_COMMAND_TO_SEND (str): Suffix systematically added at the end of messages sent.
* END_OF_COMMAND_TO_RECEIVE (str): Suffix systematically suppressed at the end of messages received.
* DELAY_INIT_CHAN (float): Delay (seconds) executed just after the communication opening because some devices cannot be joined before.
* DELAY_PUT_READ (float): Delay (seconds) between put and read commands.
:Example:
Open a serial port with many parameters, send a message a wait for a response:
::
chan = Communication("SERIAL", port="//./COM1", baud_rate=9600, end_of_command_to_send="\\n", delay_ini_chan=1.8, delay_put_read=0.2)
result = chan.putread("Hello")
It is possible to open a simulation of the communication channel .
To do that the following optional keys can be added to Communication:
* REAL (bool): Default value is True
"""
# === Constant for error codes
NO_ERROR = 0
# --- main communication
_fid_chan = None
_port_chan = None
_delay_put_read = 0.05 ; # seconds between put-get communication
_delay_init_chan = 1.5 ; # seconds to wait after open communication
_end_of_message = ""
_verbose_chan = False
_lock_putread = False
_real = True
# =====================================================================
# methods
# =====================================================================
def _set_last_error_msg(self):
self._error_msg = sys.exc_info()[1]
#traceback.print_exc(file=sys.stdout)
def get_last_error_msg(self):
return self._error_msg
def set_channel_params(self, *args, **kwargs):
#argc = len(args)
#kwargc = len(kwargs)
#self.log.print("3.*args={} argc={}".format(args,argc))
#self.log.print("3.**kwargs={} kwargc={}".format(kwargs,kwargc))
# --- Dico of optional parameters for all axis_types
param_optionals = {}
param_optionals["END_OF_COMMAND_TO_SEND"] = (str, "")
param_optionals["END_OF_COMMAND_TO_RECEIVE"] = (str, "")
param_optionals["DELAY_INIT_CHAN"] = (float, 0.0)
param_optionals["END_OF_MESSAGE"] = (str, "")
param_optionals["DELAY_PUT_READ"] = (float, 0.05)
param_optionals["REAL"] = (bool, True)
# --- Dico of axis_types and their parameters
channel_types = {}
channel_types["SERIAL"]= {"MANDATORY" : {"PORT":[str,"//./COM1"]}, "OPTIONAL" : {"BAUD_RATE":[int,9600]} }
channel_types["TCP"]= {"MANDATORY" : {"PORT":[int,"5000"], "HOSTNAME":[str,"127.0.0.1"]}, "OPTIONAL" : {} }
channel_types["INFOS"]= {"MANDATORY" : {}, "OPTIONAL" : {} }
# ---
argc = len(args)
# kwargc = len(kwargs)
# ========= valid *args
valid = 1
if (argc==0):
valid = 0
msg = "No channel type specified ({})".format(channel_types.keys())
else:
# --- Identify the selected type
selected_channel_type = args[0].upper()
if selected_channel_type in channel_types:
parameters = channel_types[selected_channel_type]
else:
valid = 0
msg = "{} not found amongst channel types ({})".format(selected_channel_type,channel_types.keys())
if valid==0:
raise CommunicationException(CommunicationException.ERR_CHAN_PORT_NOT_FOUND, msg)
# ========= valid **kwargs
valid = 0
# ====== change keys into upper strings
dics = dict()
for k,v in kwargs.items():
ku = str(k).upper()
if (type(v) is str):
v = v.strip()
dic = { ku : v }
dics.update(dic)
selected_parameters = dics
#self.log.print("dics={}".format(dics))
# ====== decode **kwargs
valid = 0
self._channel_params = {}
# --- input values of mandatory parameters
params = parameters["MANDATORY"]
for param_key in params:
if param_key in selected_parameters:
raw_value = selected_parameters[param_key]
type_conv = params[param_key][0]
if type_conv==float:
value = float(raw_value)
elif type_conv==int:
value = int(raw_value)
else:
value = raw_value
self._channel_params[param_key] = value
else:
msg = "{} not found amongst mandatory parameters ({})".format(param_key,params.keys())
raise Exception(msg)
# --- input or default values of optional parameters
params = param_optionals
for parameter_key in parameters["OPTIONAL"]:
params[parameter_key] = parameters["OPTIONAL"][parameter_key]
for param_key in params:
if param_key in selected_parameters:
raw_value = selected_parameters[param_key]
type_conv = params[param_key][0]
else:
raw_value = params[param_key][1]
type_conv = params[param_key][0]
if type_conv==float:
value = float(raw_value)
elif type_conv==int:
value = int(raw_value)
else:
value = raw_value
self._channel_params[param_key] = value
# ===
self._channel_type = selected_channel_type
self._end_of_command_to_send = self._channel_params["END_OF_COMMAND_TO_SEND"]
if type(self._end_of_command_to_send)==bytes:
self._end_of_command_to_send = self._end_of_command_to_send.decode()
self._end_of_command_to_receive = self._channel_params["END_OF_COMMAND_TO_RECEIVE"]
if type(self._end_of_command_to_receive)==bytes:
self._end_of_command_to_receive = self._end_of_command_to_receive.decode()
self._delay_init_chan = self._channel_params["DELAY_INIT_CHAN"]
self._delay_put_read = self._channel_params["DELAY_PUT_READ"]
if self._channel_type=="SERIAL":
self._port_chan = self._channel_params["PORT"]
self._baud_rate = self._channel_params["BAUD_RATE"]
if self._channel_type=="TCP":
self._port_chan = self._channel_params["PORT"]
self._hostname_chan = self._channel_params["HOSTNAME"]
self._real = self._channel_params["REAL"]
self._method_before_put = None
self._method_after_read = None
def get_ip(self)->str:
"""Tool to return the IP of this computer
Returns:
The IP addresse of the local machine.
:Example:
To get the IP of the computer:
::
>>> chan = Communication("INFOS")
>>> my_ip_address = chan.get_ip()
"""
ip = '127.0.0.1'
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
valid = False
try:
s.connect(('10.255.255.255', 1))
valid = True
except:
try:
s.connect(('255.255.255.255', 1))
valid = True
except:
pass
if valid==True:
ip = s.getsockname()[0]
except Exception:
pass
finally:
s.close()
return ip
def get_available_serial_ports(self):
"""Return a list of available serial ports of the local computer
Returns:
The list of serial port names of the local machine
:Example:
To get the IP of the computer:
::
>>> chan = Communication("INFOS")
>>> available_serial_ports = chan.get_available_serial_ports()
"""
# --
prefix_myserial_ports = ""
if sys.platform.startswith('win'):
prefix_myserial_ports = "//./"
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
prefix_myserial_ports = ""
elif sys.platform.startswith('darwin'):
prefix_myserial_ports = ""
# --
serial_ports = serial.tools.list_ports.comports(include_links=False)
# --
available_serial_ports = []
for serial_port in serial_ports:
available_serial_port = prefix_myserial_ports + serial_port.device
available_serial_ports.append(available_serial_port)
return available_serial_ports
def _set_port_chan(self, port:str):
self._port_chan = port
return self._port_chan
def _get_port_chan(self):
return self._port_chan
def _set_hostname_chan(self, hostname:str):
self._hostname_chan = hostname
return self._hostname_chan
def _get_hostname_chan(self):
return self._hostname_chan
def _my_open_chan(self):
# --- abstract method
# --- Please overload it according your language protocol
return self.NO_ERROR
def open_chan(self):
"""Open the channel
"""
err = self.NO_ERROR
if self._real == False:
fid = "simulation"
self._fid_chan = fid
return err, fid
if self._channel_type=="SERIAL":
fid = self._fid_chan
port = self._port_chan
if self._port_chan == None:
raise CommunicationException(CommunicationException.ERR_CHAN_PORT_NOT_DEFINED)
if self._fid_chan != None:
raise CommunicationException(CommunicationException.ERR_CHAN_EVER_OPENED)
# --- pass here only if the port was closed
try:
fid = serial.Serial(
port=port,
baudrate = self._baud_rate,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 0
)
if fid.isOpen():
err = self.NO_ERROR
else:
err = self.ERR_CHAN_OPEN
except:
self._set_last_error_msg()
msg = str(self._error_msg)
msg += f". List of available ports {self.get_available_serial_ports()}"
raise CommunicationException(CommunicationException.ERR_CHAN_UNKNOWN, msg)
# --- some inits
if err == self.NO_ERROR:
self._fid_chan = fid
time.sleep(self._delay_init_chan)
fid.flush()
self._lock_putread = False
elif self._channel_type=="TCP":
fid = self._fid_chan
port = self._port_chan
if self._port_chan == None:
raise CommunicationException(CommunicationException.ERR_CHAN_PORT_NOT_DEFINED)
hostname = self._hostname_chan
if self._hostname_chan == None:
raise CommunicationException(CommunicationException.ERR_CHAN_HOSTNAME_NOT_DEFINED)
if self._fid_chan != None:
raise CommunicationException(CommunicationException.ERR_CHAN_EVER_OPENED)
# --- pass here only if the port was closed
try:
fid = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
fid.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Connect to server and send data
fid.connect((hostname, port))
fid.settimeout(1)
except:
self._set_last_error_msg()
msg = self._error_msg
raise CommunicationException(CommunicationException.ERR_CHAN_UNKNOWN, msg)
# --- some inits
if err == self.NO_ERROR:
self._fid_chan = fid
self._lock_putread = False
err = self._my_open_chan()
return err, fid
def _my_close_chan(self):
# --- abstract method
# --- Please overload it according your language protocol
return self.NO_ERROR
def close_chan(self):
"""Close the channel
"""
err = self.NO_ERROR
fid = self._fid_chan
if self._fid_chan == None:
raise CommunicationException(CommunicationException.ERR_CHAN_NOT_OPENED)
if self._real == False:
self._fid_chan = None
else:
try:
err = self._my_close_chan()
fid.close()
self._fid_chan = None
except:
self._set_last_error_msg()
msg = self._error_msg
raise CommunicationException(CommunicationException.ERR_CHAN_CLOSE, msg)
return (err, fid)
def check_chan(self):
"""Check if the channel is opened. If not, try to open it.
"""
err = self.NO_ERROR
fid = self._fid_chan
if fid == None:
err, fid = self.open_chan()
return (err, fid)
def put_chan(self, cmd: str):
""" Send a message into the opened channel
Args:
cmd: Message to send. Suffix defined by the option key END_OF_COMMAND_TO_SEND is added inside the method.
"""
# --- check the opening of the serial port
err, fid = self.check_chan()
if self._method_before_put != None:
cmd = self._method_before_put(cmd)
if self._real == False:
pass
elif self._channel_type=="SERIAL":
# --- serial port buffer reset for the next read
fid.reset_input_buffer()
# --- serial port is ready to put message
cmd = cmd + self._end_of_command_to_send
#print(f"cmd={cmd}")
fid.write(cmd.encode())
fid.flush()
elif self._channel_type=="TCP":
cmd = cmd + self._end_of_command_to_send
fid.sendall(cmd.encode())
return (err, cmd)
def read_chan(self):
""" Receive a message from the opened channel
Returns:
The string of the message read.
"""
# --- check the opening of the serial port
err, fid = self.check_chan()
lignes = "" ; # fid.readlines()
t0 = time.time()
dt = 0
nn = 0
if self._real == False:
lignes = ""
elif self._channel_type=="SERIAL":
while True:
n = 0
for car in fid.read():
n += 1
car = chr(car)
lignes += car
nn = 0
t0 = time.time()
#self.log.print("car={} n={} nn={}".format(car,n,nn))
if n==0:
nn += 1
if nn==2:
#self.log.print("n={} nn={} Time out".format(n,nn))
break
time.sleep(0.05)
dt = time.time()-t0
if dt>10.0:
break
elif self._channel_type=="TCP":
try:
lignes = fid.recv(1024)
except:
err = self.ERR_CHAN_TCP_RECV_TIMEOUT
#print("dt={} lignes={} type={}".format(dt,lignes,type(lignes)))
# --- format la sortie
if type(lignes)==bytes:
# --- TCP case (the try is useful for a pickle data)
try:
lignes = lignes.decode("utf-8")
except:
pass
if self._end_of_command_to_receive!="":
res = lignes.split(self._end_of_command_to_receive)
else:
res = lignes
# print("READ {} = {}".format(self._port_chan,res))
if self._method_after_read != None:
res = self._method_after_read(res)
return (err, res)
def _set_delay_chan(self, delay_s:float):
if delay_s<=0:
raise Exception("delay must be strictly positive")
self._delay_chan = delay_s
return self.NO_ERROR
def _get_delay_chan(self):
return self._delay_chan
def _set_delay_init_chan(self, delay_s:float):
if delay_s<=0:
raise Exception("delay must be strictly positive")
self._delay_init_chan = delay_s
return self.NO_ERROR
def _get_delay_init_chan(self):
return self._delay_init_chan
def _set_verbose_chan(self, verbose:bool):
if type(verbose) is not bool:
raise Exception("verbose must be boolean")
self._verbose_chan = verbose
return self.NO_ERROR
def _get_verbose_chan(self):
return self._verbose_chan
def _get_method_before_put(self):
return self._method_before_put
def _set_method_before_put(self, method:object):
self._method_before_put = method
def _del_method_before_put(self):
self._method_before_put = None
def _get_method_after_read(self):
return self._method_after_read
def _set_method_after_read(self, method:object):
self._method_after_read = method
def _del_method_after_read(self):
self._method_after_read = None
# =====================================================================
# =====================================================================
# Methods for users
# =====================================================================
# =====================================================================
port_chan = property(_get_port_chan, _set_port_chan)
delay_chan = property(_get_delay_chan, _set_delay_chan)
delay_init_chan = property(_get_delay_init_chan, _set_delay_init_chan)
verbose_chan = property(_get_verbose_chan, _set_verbose_chan)
method_before_put = property(_get_method_before_put, _set_method_before_put, _del_method_before_put)
method_after_read = property(_get_method_after_read, _set_method_after_read, _del_method_after_read)
def putread_chan(self, cmd:str, index:int=-1):
""" Send and Receive a message from the opened channel
Args:
cmd: The message to send
index: >0 to extract only the word returned at the index position
Returns:
A string containing the response received.
"""
return self.putread_chan_check(cmd, index)
def putread_chan_nocheck(self, cmd:str, index:int=-1):
""" Send and Receive a message from the opened channel
No lock version. See comments of the putread_chan_check
Args:
cmd: The message to send
index: >0 to extract only the word returned at the index position
Returns:
A string containing the response received.
"""
if self.verbose_chan==True:
#self.log.self.log.print("Putread: "+cmd)
pass
self._lock_putread = True
self.put_chan(cmd)
time.sleep(self._delay_put_read)
err, res = self.read_chan()
if err != self.NO_ERROR:
self._lock_putread = False
return (err, res)
if index>=0:
n = len(res)
if index>n-1:
index = n-1
self._lock_putread = False
return (err, res[index])
self._lock_putread = False
return (err, res)
#def putread_chan_lock_verify(self, cmd, index=-1):
def putread_chan_check(self, cmd, index=-1):
""" Send and Receive a message from the opened channel
Same as putread_chan but a lock is added to avoid multiple calls to the controller.
Args:
cmd: The message to send
index: >0 to extract only the word returned at the index position
Returns:
A string containing the response received.
"""
if self.verbose_chan==True:
#print("Putread: "+cmd)
pass
err = self.NO_ERROR
res = ""
# --- verify the lock state
if self._lock_putread == True:
# --- Case the lock state = True, the com is occupied
t0 = time.time()
while self._lock_putread == True:
# --- Loop until the com is freed
time.sleep(0.05)
dt = time.time() - t0
if dt>3.0:
print("Serial port locked timeout for {}".format(cmd))
break
# --- verify the lock state
if self._lock_putread == False:
# --- Case the lock state = False, the com is free
# --- lock during com operations
self._lock_putread = True
#print("Serial port is locked 0 normaly by {}".format(cmd))
self.put_chan(cmd)
time.sleep(self._delay_put_read)
err, res = self.read_chan()
if err != self.NO_ERROR:
self._lock_putread = False
#print("Serial port is unlocked 1 err={} res={} by {}".format(err,res,cmd))
return (err, res)
if index>=0:
n = len(res)
if index>n-1:
index = n-1
self._lock_putread = False
#print("Serial port is unlocked 2 err={} res={} by {}".format(err,res,cmd))
return (err, res[index])
self._lock_putread = False
#print("Serial port is unlocked 3 err={} res={} by {}".format(err,res,cmd))
else:
#print("Pb serial port is locked for {}".format(cmd))
err = self.ERR_CHAN_PUTREAD_LOCKED
return (err, res)
# =====================================================================
# =====================================================================
# Special methods
# =====================================================================
# =====================================================================
def __init__(self, *args, **kwargs):
self._error_msg = ""
self.set_channel_params(*args, **kwargs)
self.verbose_chan = False
self._lock_putread = False
def __del__(self):
"""
Clean procedure when a channel is closed
"""
try:
fid = self._fid_chan
#self.log.print(f"CHAN Just before close the serial channel: fid={fid}")
err, fid = self.close_chan()
#self.log.print(f"CHAN Just after close the serial channel: err={err} fid={fid}")
except:
pass
def __repr__(self):
msg = ""
# ------------------------
msg += f"=== Communication channel of type {self._channel_type} ==="
msg += "\n--- Channel parameters:"
for key, val in self._channel_params.items():
msg += f"\n * {key} = {val}"
return msg
# #####################################################################
# #####################################################################
# #####################################################################
# Main
# #####################################################################
# #####################################################################
# #####################################################################
if __name__ == "__main__":
default = 2
example = input(f"Select the example (0 to 2) ({default}) ")
try:
example = int(example)
except:
example = default
print("Example = {}".format(example))
if example == 0:
chan = Communication("INFOS")
# --- serial ports
available_serial_ports = chan.get_available_serial_ports()
print("Available com ports:")
k = 0
for available_serial_port in available_serial_ports:
print("Available com port [{}]: {}".format(k,available_serial_port))
k+=1
# --- IP of this computer
print(f"IP = {chan.get_ip()}")
if example == 1:
host = '192.168.20.30'
port = 1025
real = False
chan = Communication("TCP", HOSTNAME = host, PORT = port, DELAY_PUT_READ = 0.1, REAL = real)
if example == 2:
"""
Example Esatto
"""
import ast
import shlex
def esatto_decode_serial(result:str) -> list:
dico = ast.literal_eval(result[:-2])
return dico
param = {}
param["PORT"] = "//./COM5"
param["BAUD_RATE"] = 115200
param["DELAY_INIT_CHAN"] = 0.1
param["DELAY_PUT_READ"] = 0.5
param["END_OF_COMMAND_TO_SEND"] = "".encode('utf8')
param["END_OF_COMMAND_TO_RECEIVE"] = "".encode('utf8')
param["REAL"] = True
chan = Communication("SERIAL", **param)
chan.method_after_read = esatto_decode_serial
print(chan)
cmd = shlex.quote('{"req":{"get": ""}}}')
err, res = chan.putread_chan(cmd)
del chan