-
Notifications
You must be signed in to change notification settings - Fork 0
/
messages.py
255 lines (206 loc) · 6.07 KB
/
messages.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
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
import time
import datetime
import atexit
MSGID = 0
MAX_RETRIES = 400
try:
with open("msgid.txt") as id_file:
MSGID = int(id_file.readline())
except:
pass
def store_id():
global MSGID
with open("msgid.txt","w") as id_file:
id_file.write(str(MSGID))
atexit.register(store_id)
def get_new_message_id():
global MSGID
MSGID = (MSGID+1)%256;
return MSGID
class generic_request(object):
def __init__(self, msg_type, data):
self.id = get_new_message_id()
self.type = msg_type
self.data = data
def set_data(data):
self.data = data
def to_bytes(self):
return [self.id, self.type] + self.data
class time_req(generic_request):
msg_type = 1
def __init__(self, timestamp = 0):
self.timestamp = timestamp
data = []
t = self.timestamp
for i in range(4):
data.append(t & 0xff)
t >>= 8
super(time_req,self).__init__(time_req.msg_type, data)
class analog_read_req(generic_request):
msg_type = 2
def __init__(self, pin):
self.pin = pin
super(analog_read_req,self).__init__(analog_read_req.msg_type, [self.pin])
class blink_req(generic_request):
msg_type = 3
def __init__(self, pin, ms):
self.pin = pin
self.ms = ms
data = [
pin,
ms & 0xff,
(ms >> 8) & 0xff
]
super(blink_req,self).__init__(blink_req.msg_type, data)
class dht22_req(generic_request):
msg_type = 4
def __init__(self):
super(dht22_req,self).__init__(dht22_req.msg_type, [])
class PacketTooShort(Exception):
pass
class WrongDataLength(Exception):
pass
class generic_response(object):
msg_type = 0 # always 0 for response
def __init__(self, packet):
if len(packet) < 2:
raise PacketTooShort
self.id = packet[0]
self.type = packet[1]
self.data = packet[2:]
class time_resp(generic_response):
data_length = 4
def __init__(self, msg):
self.id = msg.id
self.type = msg.type
self.data = msg.data
if len(self.data) != time_resp.data_length:
raise WrongDataLength
self.timestamp = 0;
for i in range(time_resp.data_length):
self.timestamp >>= 8
self.timestamp |= (self.data[i] << 24)
def __str__(self):
df = datetime.datetime.fromtimestamp(self.timestamp)
return df.strftime('%Y-%m-%d %H:%M:%S')
class analog_read_resp(generic_request):
data_length = 4
def to_ohm(self, m):
if m == 0:
return 0
return 10.0 / (1024.0 / m - 1)
def __init__(self, msg):
self.id = msg.id
self.type = msg.type
self.data = msg.data
if len(self.data) != analog_read_resp.data_length:
raise WrongDataLength
self.value = 0
for i in range(2):
self.value >>= 8
self.value |= (self.data[i] << 8)
self.sigma = 0;
for i in range(2,4):
self.sigma >>= 8
self.sigma |= (self.data[i] << 8)
def __str__(self):
return "%d sigma %d [%.2f %.2f %.2f]" % (
self.value,
self.sigma,
self.to_ohm(self.value - self.sigma),
self.to_ohm(self.value),
self.to_ohm(self.value + self.sigma)
)
class blink_resp(generic_request):
data_length = 0
def __init__(self, msg):
self.id = msg.id
self.type = msg.type
self.data = msg.data
if len(self.data) != blink_resp.data_length:
raise WrongDataLength
def __str__(self):
return "OK"
class dht22_resp(generic_request):
data_length = 4
def __init__(self, msg):
self.id = msg.id
self.type = msg.type
self.data = msg.data
if len(self.data) != dht22_resp.data_length:
raise WrongDataLength
self.temperature = self.data[0]
self.humidity = self.data[1]
def __str__(self):
return "%d %d" % (
self.temperature,
self.humidity
)
import vw_conf as vw
def send_bytes(b):
while not vw.tx.ready():
time.sleep(0.02)
print("Sending "+repr(b))
vw.rx.pause()
vw.tx.put(b)
while not vw.tx.ready(): # Wait for transmission to finish
time.sleep(0.02)
vw.rx.resume()
class ResponseTimeout(Exception):
pass
class BadResponseId(Exception):
pass
class BadResponseType(Exception):
pass
def create_response_object(packet, req):
resp = generic_response(packet)
if resp.id != req.id:
raise BadResponseId
if resp.type != 0:
raise BadResponseType
if req.type == time_req.msg_type:
return time_resp(resp)
elif req.type == analog_read_req.msg_type:
return analog_read_resp(resp)
elif req.type == blink_req.msg_type:
return blink_resp(resp)
elif req.type == dht22_req.msg_type:
return dht22_resp(resp)
return None
def send_and_receive(req):
b = req.to_bytes()
retries = 0
while retries < MAX_RETRIES:
if retries > 0:
print("Retrying")
retries += 1
send_bytes(b)
try:
wait_iteration = 0
while not vw.rx.ready():
time.sleep(0.02)
wait_iteration += 1
if wait_iteration > 100:
raise ResponseTimeout
resp = vw.rx.get()
print("Resonse "+repr(resp))
resp = create_response_object(resp, req)
if resp != None:
return resp
except ResponseTimeout:
print("ResponseTimeout")
continue
except PacketTooShort:
print("PacketTooShort")
continue
except WrongDataLength:
print("WrongDataLength")
continue
except BadResponseId:
print("BadResponseId")
continue
except BadResponseType:
print("BadResponseType")
continue
# All retries failed
raise ResponseTimeout