/
KuBo.py
435 lines (333 loc) · 11.4 KB
/
KuBo.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
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
#!/usr/bin/python
from __future__ import division
from omxplayer import OMXPlayer
import threading
import pigpio
import time
import sys
import numpy as np
class KuBo():
def __init__(self, servoPin = 19, lowerReedPin = 17, higherReedPin = 22, start_pos = 900, plate_dist = 0.02, plate_weight = 5):
self.servoPin = servoPin
self.lowerReedPin = lowerReedPin
self.higherReedPin = higherReedPin
self.start_pos = start_pos #The servo position at boot up
self.plate_dist = plate_dist
self.plate_weight = plate_weight
self.pi = pigpio.pi()
# Configure Pin Mode
self.pi.set_mode(self.servoPin, pigpio.OUTPUT)
self.pi.set_mode(self.lowerReedPin, pigpio.INPUT)
self.pi.set_mode(self.higherReedPin, pigpio.INPUT)
# Set position of servo to start position
self.pi.set_servo_pulsewidth(self.servoPin, self.start_pos)
# Parameters for the thread need to be lists to change their values
# during thread execution
self.end_pos_list = [0]
self.freq_list = [0]
# Start Audio Player process
self.audiopath = '/home/pi/Documents/GitKubo/kubo/sounds/'
self.omx = OMXPlayer(self.audiopath + 'ku.mp3')
self.omx.pause()
# Initiallize edge listener
self.cb_lower = self.pi.callback(self.lowerReedPin, pigpio.RISING_EDGE, self._callback_lower)
self.cb_higher = self.pi.callback(self.higherReedPin, pigpio.RISING_EDGE, self._callback_higher)
# zero count parameters
self.max_zero_count = 10
#self.max_zero_count = 1000
self.min_zero_count = 5
# one count parameters
self.min_one_count = 3
# polling period
self.T_poll = 0.001
# lower reed contact data
self.lower_speed = 0
self.lower_weight = 0
self.lower_flag = 0
self.lower_timestamp = 0
# higher reed contact data
self.higher_speed = 0
self.higher_weight = 0
self.higher_flag = 0
self.higher_timestamp = 0
# Locks
self.lock_lower = threading.Lock()
self.lock_higher = threading.Lock()
self.data = []
def start_jumping(self, end_pos, freq):
# check if thread is allready running
if hasattr(self, 't_jump'):
if self.t_jump.isAlive():
print "Kubo is allready jumping... Let him take a break :D"
return
self.end_pos_list[0] = end_pos
self.freq_list[0] = freq
# Set Servo to starting value
self.pi.set_servo_pulsewidth(self.servoPin, self.start_pos)
# Create lock for thread values
self.jump_lock = threading.Lock()
# Create event that is triggered when thread should be stopped
self.jump_stop = threading.Event()
# Define thread
self.t_jump = threading.Thread(target=self._jump_thread, args=(self.end_pos_list, self.freq_list, self.jump_stop))
self.t_jump.start()
def _jump_thread(self, end_pos_list, freq_list, stop_event):
print "Thread started"
while(not stop_event.is_set()):
with self.jump_lock:
print "End position: ", end_pos_list[0]
print "Frequency: ", freq_list[0]
# Calculate the settle time the servo needs for moving
# Convert pulsewidth to degrees
degree = (end_pos_list[0]-self.start_pos) / 10
# Servo speed is 0.15s/60deg
# Safety factor of 1.1
settle = 0.15/60*degree*1.1
self.pi.set_servo_pulsewidth(self.servoPin, end_pos_list[0])
time.sleep(settle)
self.pi.set_servo_pulsewidth(self.servoPin, self.start_pos)
time.sleep(settle)
if freq_list[0] != 0:
sleep_time = 1/freq_list[0]-2*settle
else:
break
if sleep_time > 0:
time.sleep(sleep_time)
elif sleep_time < 0:
print "Frequency too high"
print "Thread stopped"
def stop_jumping(self):
if not hasattr(self, 't_jump'):
print "Kubo needs to start jumping first"
return
else:
if not self.t_jump.isAlive():
print "Kubo needs to start jumping first"
return
self.jump_stop.set()
def change_jumping(self, end_pos, freq):
if not hasattr(self, 't_jump'):
print "Kubo needs to start jumping first"
return
else:
if not self.t_jump.isAlive():
print "Kubo needs to start jumping first"
return
with self.jump_lock:
self.end_pos_list[0] = end_pos
self.freq_list[0] = freq
def is_jumping(self):
if not hasattr(self, 't_jump'):
return False
else:
return self.t_jump.isAlive()
def say(self, filename):
#self.omx.quit()
return self.omx.load(self.audiopath + filename)
def init_voice(self, audiopath = '/home/pi/Documents/Audio/'):
self.audiopath = audiopath
self.omx = OMXPlayer(self.audiopath + 'gangsta.mp3')
return self.omx.pause()
def stop_voice(self):
return self.omx.quit()
def _callback_lower(self, gpio, level, tick):
t = time.time()
# stop interrupts
self.cb_lower.cancel()
# self.data.append('...')
#print "==== Callback lower reed contact ===="
timestamps = []
magnet_count = 0
one_count = 0
while True:
inter_flag = False
input = 1
while input:
input = self.pi.read(gpio)
# debug
# self.data.append(input)
one_count = one_count + 1
time.sleep(self.T_poll)
if one_count < self.min_one_count:
# Interference if no valey interference compensates for it
# print "Peak Interference suspicion"
inter_flag = True
zero_count = 0
input = 0
while input == 0:
input = self.pi.read(gpio)
# debug
# self.data.append(input)
zero_count = zero_count + 1
time.sleep(self.T_poll)
if zero_count > self.max_zero_count:
# No more consecutive magnets --> activate
# interrupts again for next passing of weights
break
elif inter_flag and zero_count >= self.min_zero_count:
# No valey interference to compensate for peak interference
# check if interference is isolated
# print "Peak interference detected on lower contact"
if magnet_count == 0:
# isolated interference
self.cb_lower = self.pi.callback(gpio, pigpio.RISING_EDGE, self._callback_lower)
#print "Interference detected"
return
else:
# interference between magnets --> treet ones as zeros
zero_count = zero_count + one_count
if zero_count < self.min_zero_count:
pass
# Interference --> continue with first while loop
# print "Valey Interference detected on lower contact"
# if inter_flag:
# print "No peak interference"
elif zero_count > self.max_zero_count:
# No more consecutive magnets --> calculate values of one repetition
magnet_count = magnet_count + 1
#print "Magnet Count: ", magnet_count
timestamps.append(t) # save old timestamp
#print " Timestamps: ", timestamps
v = 0
if magnet_count > 1:
for i in range(magnet_count-1):
v = v + self.plate_dist / (timestamps[i+1] - timestamps[i])
else:
print "Only one magnet detected --> cannot determine speed"
with self.lock_lower: # save values of one repetition
self.lower_weight = self.plate_weight*magnet_count
self.lower_speed = v / magnet_count
if self.lower_flag:
print "flag wasn't read or properly set back to 0"
self.lower_flag = 1
self.lower_timestamp = timestamps[magnet_count-1]
print "End of consecutive magnets"
# Reactivate interrupt listener
self.cb_lower = self.pi.callback(gpio, pigpio.RISING_EDGE, self._callback_lower)
break
else:
# start of next magnet
timestamps.append(t) # save old timestamp
t = time.time()
one_count = 0
magnet_count = magnet_count + 1
#print "Magnet Count: ", magnet_count
def _callback_higher(self, gpio, level, tick):
t = time.time()
# stop interrupts
self.cb_higher.cancel()
self.data.append('...')
#print "==== Callback higher reed contact ===="
timestamps = []
magnet_count = 0
one_count = 0
while True:
inter_flag = False
input = 1
while input:
input = self.pi.read(gpio)
# debug
# self.data.append(input)
one_count = one_count + 1
time.sleep(self.T_poll)
if one_count < self.min_one_count:
# Interference if no valey interference compensates for it
# print "Peak Interference suspicion"
inter_flag = True
zero_count = 0
input = 0
while input == 0:
input = self.pi.read(gpio)
# debug
# self.data.append(input)
zero_count = zero_count + 1
time.sleep(self.T_poll)
if zero_count > self.max_zero_count:
# No more consecutive magnets --> activate
# interrupts again for next passing of weights
break
elif inter_flag and zero_count >= self.min_zero_count:
# No valey interference to compensate for peak interference
# check if interference is isolated
# print "Peak interference detected on higher contact"
if magnet_count == 0:
# isolated interference
self.cb_higher = self.pi.callback(gpio, pigpio.RISING_EDGE, self._callback_higher)
#print "Interference detected"
return
else:
# interference between magnets --> treet ones as zeros
zero_count = zero_count + one_count
if zero_count < self.min_zero_count:
pass
# Interference --> continue with first while loop
# print "Valey Interference detected on higher contact"
# if inter_flag:
# print "No peak interference"
elif zero_count > self.max_zero_count:
# No more consecutive magnets --> calculate values of one repetition
magnet_count = magnet_count + 1
#print "Magnet Count: ", magnet_count
timestamps.append(t) # save old timestamp
#print " Timestamps: ", timestamps
v = 0
if magnet_count > 1:
for i in range(magnet_count-1):
v = v + self.plate_dist / (timestamps[i+1] - timestamps[i])
else:
print "Only one magnet detected --> cannot determine speed"
with self.lock_higher: # save values of one repetition
self.higher_weight = self.plate_weight*magnet_count
self.higher_speed = v / magnet_count
if self.higher_flag:
print "flag wasn't read or properly set back to 0"
self.higher_flag = 1
self.higher_timestamp = timestamps[magnet_count-1]
#print "End of consecutive magnets"
# Reactivate interrupt listener
self.cb_higher = self.pi.callback(gpio, pigpio.RISING_EDGE, self._callback_higher)
break
else:
# start of next magnet
timestamps.append(t) # save old timestamp
t = time.time()
one_count = 0
magnet_count = magnet_count + 1
#print "Magnet Count: ", magnet_count
def stop_listening(self):
if hasattr(self, 'cb_lower') and hasattr(self, 'cb_higher'):
self.cb_lower.cancel()
self.cb_higher.cancel()
elif hasattr(self, 'cb_lower'):
self.cb_lower.cancel()
elif hasattr(self, 'cb_higher'):
self.cb_higher.cancel()
else:
print "No listeners to close"
def start_listening(self, lowerReedPin = 17, higherReedPin = 22):
self.cb_lower = self.pi.callback(self.lowerReedPin, pigpio.RISING_EDGE, self._callback_lower)
self.cb_higher = self.pi.callback(self.higherReedPin, pigpio.RISING_EDGE, self._callback_higher)
def get_lower_data(self):
data = [None]*4
with self.lock_lower:
if self.lower_flag:
data[0] = True
data[1] = self.lower_timestamp
data[2] = self.lower_weight
data[3] = self.lower_speed
self.lower_flag = 0
else:
data[0] = False
return data
def get_higher_data(self):
data = [None]*4
with self.lock_higher:
if self.higher_flag:
data[0] = True
data[1] = self.higher_timestamp
data[2] = self.higher_weight
data[3] = self.higher_speed
self.higher_flag = 0
else:
data[0] = False
return data