-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsend_to_serial.py
executable file
·72 lines (65 loc) · 1.68 KB
/
send_to_serial.py
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
#!/usr/bin/python
# vim:et:sw=4:ts=4:sts=4
import sys
import time
import serial
import getopt
def print_usage():
print '''\
USAGE:
%s [-h | [-n number] [-b speed] serial]
OPTIONS:
serial write output to serial device
-b speed speed of the serial device
-n number number of controlled boxes
-h --help show this help
''' % sys.argv[0]
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 's:b:n:h', ['help'])
except getopt.GetOptError:
print_usage()
return 1
speed = 57600
number = 20
show_help = False
for k, v in opts:
if k == '-n':
if not v.isdigit():
print_usage()
return 1
number = int(v)
elif k == '-b':
if not v.isdigit():
print_usage()
return 1
speed = int(v)
elif k == '-h' or k == '--help': show_help = True
if show_help:
print_usage()
return 0
if len(args) != 1:
print_usage()
return 1
try:
output_stream = serial.Serial(args[0], speed)
except serial.serialutil.SerialException:
print 'Could not open the serial device'
return 1
time.sleep(2)
try:
while True:
data = '\xAC'
to_read = number*3
while to_read > 0:
read = sys.stdin.read(to_read)
if len(read) == 0: break
to_read -= len(read)
data += read
if len(read) == 0: break
output_stream.write(data)
output_stream.flush()
except IOError:
pass
return 0
sys.exit(main())