1
1
from io import BlockingIOError
2
2
from os import openpty , read , set_blocking , ttyname , write
3
3
from serial import serial_for_url
4
- from sys import stderr
4
+ from sys import stderr , stdout
5
5
from time import sleep , time
6
6
from tty import setcbreak
7
7
8
8
9
+ _commands = {
10
+ 'get_ports' : 0 ,
11
+ 'enable' : 1 ,
12
+ 'disable' : 2 }
13
+
9
14
10
15
class Mux ():
11
16
""""""
@@ -68,14 +73,29 @@ def update(self):
68
73
self ._write (data )
69
74
70
75
71
- def serialmux (name , number ):
76
+ def _control (connection , cmd ):
77
+ connection .write (bytes ([0 , _commands [cmd ]]))
78
+
79
+ if ord (connection .read ()):
80
+ raise IOError ('Invalid control response.' )
81
+
82
+ return ord (connection .read ())
83
+
84
+
85
+ def serialmux (handle , log_handle , name ):
72
86
""""""
73
87
connection = serial_for_url (name )
88
+ sleep (2 )
89
+
90
+ number_of_ports = _control (connection , 'get_ports' )
91
+ handle .write ('Virtual ports detected: {}\n ' .format (number_of_ports ))
74
92
75
93
muxs = []
76
- for i in range (1 , number + 1 ):
77
- muxs .append (Mux (connection , i , stderr ))
78
- print ('mux {} is on {}' .format (muxs [- 1 ].id , muxs [- 1 ].name ))
94
+ for i in range (1 , number_of_ports + 1 ):
95
+ muxs .append (Mux (connection , i , log_handle ))
96
+ handle .write (' Mux{}: {}\n ' .format (muxs [- 1 ].id , muxs [- 1 ].name ))
97
+
98
+ _control (connection , 'enable' )
79
99
80
100
while True :
81
101
for mux in muxs :
@@ -85,7 +105,7 @@ def serialmux(name, number):
85
105
86
106
def main ():
87
107
"""Main entry point."""
88
- serialmux ('/dev/ttyUSB0' , 2 )
108
+ serialmux (stdout , None , '/dev/ttyUSB0' )
89
109
90
110
91
111
if __name__ == '__main__' :
0 commit comments