forked from scottbez1/splitflap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
splitflap.py
146 lines (124 loc) · 4.63 KB
/
splitflap.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
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
import json
from contextlib import contextmanager
import serial
import serial.tools.list_ports
import six
_ALPHABET = {
' ',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'.',
',',
'\'',
}
class Splitflap(object):
def __init__(self, serial_instance):
self.serial = serial_instance
self.has_inited = False
self.num_modules = 0
self.character_list = ""
self.last_command = None
self.last_status = None
self.exception = None
def _loop_for_status(self):
while True:
line = self.serial.readline().lstrip(b'\0').rstrip(b'\n')
if not len(line):
continue
try:
data = json.loads(line)
except:
print('Failed to parse', line)
raise
t = data['type']
if t == 'init':
if self.has_inited:
raise RuntimeError('Unexpected re-init!')
self.has_inited = True
self.num_modules = data['num_modules']
try:
self.character_list = data['character_list']
except KeyError:
self.character_list = _ALPHABET # for compatibility
elif t == 'move_echo':
if not self.has_inited:
raise RuntimeError('Got move_echo before init!')
if self.last_command is None:
raise RuntimeError('Unexpected move_echo response from controller')
if self.last_command != data['dest']:
raise RuntimeError('Bad response from controller. Expected {!r} but got {!r}'.format(
self.last_command,
data['dest'],
))
elif t == 'status':
if not self.has_inited:
raise RuntimeError('Got status before init!')
if len(data['modules']) != self.num_modules:
raise RuntimeError('Wrong number of modules in status update. Expected {} but got {}'.format(
self.num_modules,
len(data['modules']),
))
self.last_status = data['modules']
return self.last_status
elif t == 'no_op':
pass
else:
raise RuntimeError('Unexpected message: {!r}'.format(data))
def in_character_list(self, letter):
return letter in self.character_list
def get_character_list(self):
return self.character_list
def set_text(self, text):
text = text[0:self.num_modules] # trim to number of modules available
for letter in text:
assert self.in_character_list(letter), 'Unexpected letter: {!r}. Must be one of {!r}'.format(
letter,
list(self.character_list),
)
self.last_command = text
self.serial.write(b'=' + text.encode() + b'\n')
return self._loop_for_status()
def recalibrate_all(self):
self.serial.write(b'@')
return self._loop_for_status()
def get_status(self):
return self.last_status
def get_num_modules(self):
return self.num_modules
def print_status(self, status=None):
if(status is None):
status = self.last_status
for module in status:
state = ''
if module['state'] == 'panic':
state = '!!!!'
elif module['state'] == 'look_for_home':
state = '...'
elif module['state'] == 'sensor_error':
state = '????'
elif module['state'] == 'normal':
state = module['flap']
print('{:4} {: 4} {: 4}'.format(state, module['count_missed_home'], module['count_unexpected_home']))
@contextmanager
def splitflap(serial_port):
with serial.Serial(serial_port, 38400) as ser:
s = Splitflap(ser)
s._loop_for_status()
yield s
def ask_for_serial_port():
print('Available ports:')
ports = sorted(
filter(
lambda p: p.description != 'n/a',
serial.tools.list_ports.comports(),
),
key=lambda p: p.device,
)
for i, port in enumerate(ports):
print('[{: 2}] {} - {}'.format(i, port.device, port.description))
print()
value = six.moves.input('Use which port? ')
port_index = int(value)
assert 0 <= port_index < len(ports)
return ports[port_index].device