-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscale.py
298 lines (226 loc) · 7.46 KB
/
scale.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import time
from select import poll, POLLIN
import subprocess
import numpy
import xwiimote
import util
import asyncoro
import random
#import pysqlite2
#import sqlite3
#import sqlalqchemy
# global bars
conn = None
_iface = None
class RingBuffer():
def __init__(self, length):
self.length = length
self.reset()
self.filled = False
def extend(self, x):
x_index = (self.index + numpy.arange(x.size)) % self.data.size
self.data[x_index] = x
self.index = x_index[-1] + 1
if self.filled == False and self.index == (self.length-1):
self.filled = True
def append(self, x):
x_index = (self.index + 1) % self.data.size
self.data[x_index] = x
self.index = x_index
if self.filled == False and self.index == (self.length-1):
self.filled = True
def get(self):
idx = (self.index + numpy.arange(self.data.size)) %self.data.size
return self.data[idx]
def reset(self):
self.data = numpy.zeros(self.length, dtype=numpy.int)
self.index = 0
def dev_is_balanceboard(dev):
time.sleep(2) # if we check the devtype to early it is reported as 'unknown' :(
iface = xwiimote.iface(dev)
return iface.get_devtype() == 'balanceboard'
def wait_for_balanceboard():
print("Waiting for balanceboard to connect..")
mon = xwiimote.monitor(True, False)
dev = None
while True:
mon.get_fd(True) # blocks
connected = mon.poll()
if connected == None:
continue
elif dev_is_balanceboard(connected):
print("Found balanceboard:", connected)
dev = connected
break
else:
print("Found non-balanceboard device:", connected)
print("Waiting..")
return dev
def format_measurement(x):
return "{0:.2f}".format(x / 100.0)
def print_bboard_measurements(*args):
sm = format_measurement(sum(args))
tl, tr, bl, br = map(format_measurement, args)
print("┌","─" * 21, "┐", sep="")
print("│"," " * 8, "{:>5}".format(sm)," " * 8, "│", sep="")
print("├","─" * 10, "┬", "─" * 10, "┤", sep="")
print("│{:^10}│{:^10}│".format(tl, tr))
print("│"," " * 10, "│", " " * 10, "│", sep="")
print("│"," " * 10, "│", " " * 10, "│", sep="")
print("│{:^10}│{:^10}│".format(bl, br))
print("└","─" * 10, "┴", "─" * 10, "┘", sep="")
print()
print()
def store_bboard_measurements(*args):
sm = format_measurement(sum(args))
tl, tr, bl, br = map(format_measurement, args)
#
print("┌","─" * 21, "┐", sep="")
print("│"," " * 8, "{:>5}".format(sm)," " * 8, "│", sep="")
print("├","─" * 10, "┬", "─" * 10, "┤", sep="")
print("│tl {:^10}│tr {:^10}│".format(tl, tr))
print("│"," " * 10, "│", " " * 10, "│", sep="")
print("│"," " * 10, "│", " " * 10, "│", sep="")
print("│bl {:^10}│ br {:^10}│".format(bl, br))
print("└","─" * 10, "┴", "─" * 10, "┘", sep="")
print()
print()
def measurements(iface):
p = select.epoll.fromfd(iface.get_fd())
print("measurements def iface")
while True:
p.poll() # blocks
event = xwiimote.event()
iface.dispatch(event)
tl = event.get_abs(2)[0]
#print("tl")
#print(tl)
tr = event.get_abs(0)[0]
br = event.get_abs(3)[0]
bl = event.get_abs(1)[0]
yield (tl,tr,br,bl)
def average_mesurements(ms, max_stddev=55):
last_measurements = RingBuffer(800)
#print("average_meaurements called")
while True:
weight = sum(ms.next())
#print("weight {}".format(weight))
last_measurements.append(weight)
mean = numpy.mean(last_measurements.data)
stddev = numpy.std(last_measurements.data)
if stddev < max_stddev and last_measurements.filled:
print("yield of average_measurements called")
yield numpy.array((mean, stddev))
##
def server_proc(coro=None):
coro.set_daemon()
while True:
msg = yield coro.receive()
print("Message received: {}"),format(msg)
def client_proc(server, n, coro=None):
#global msg_id
ready = True
global _iface
p = select.epoll.fromfd(_iface.get_fd())
#while ready:
p.poll() # blocks
event = xwiimote.event()
_iface.dispatch(event)
tl = event.get_abs(2)[0]
#print("tl")
#print(tl)
tr = event.get_abs(0)[0]
br = event.get_abs(3)[0]
bl = event.get_abs(1)[0]
yield (tl,tr,br,bl) # if not error this is not a generator
server.send('tl: {} tr: {} br: {} bl: {}'.format(tl, tr, br, bl))
# for x in range(3):
# yield coro.suspend(random.uniform(0.5,3))
# msg_id += 1
# print("client_proc send: {}"),format(msg_id)
# server.send('%d: %d / %d' % (msg_id, n, x))
# server.send('{} {}'.format(msg_id, 'two'))
##
def main():
global _iface
if len(sys.argv) == 2:
device = sys.argv[1]
else:
device = wait_for_balanceboard()
_iface = xwiimote.iface(device)
print("iface.open balanceboard")
fd = _iface.get_fd()
print("fd: {}"),format(fd)
print("opened mask: {}"),format(_iface.opened)
_iface.open(xwiimote.IFACE_BALANCE_BOARD)
#_iface.open(devi.available() | xwiimote.IFACE_WRITABLE)
print("opened mask: {}"),format(_iface.opened)
p = poll()
p.register(fd, POLLIN)
evt = xwiimote.event()
n = 0
readValues = []
myCount = 0
#while True:
while True:
p.poll()
try:
_iface.dispatch(evt)
if evt.type == xwiimote.EVENT_KEY:
code, state = evt.get_key()
print("key: {}"),format(code)
print("state: {}"),format(state)
n+=1
elif evt.type == xwiimote.EVENT_GONE:
print("Gone")
n = 2
elif evt.type == xwiimote.EVENT_WATCH:
print("Watch")
else:
#print("event type: {}"),format(evt.type)
#print(evt.type)
tl = evt.get_abs(2)[0]
if tl != 0:
#print(tl)
readValues.append(tl)
if myCount == 5:
break
myCount += 1
except IOError as e:
if e.errno != errno.EAGAIN:
print("Bad")
#time.sleep(2)
#print(_iface.get_fd())
print(readValues)
# test asyncoro
#server = asyncoro.Coro(server_proc)
#for i in range(10):
#asyncoro.Coro(client_proc, server, 1)
# end asyncoro
#exit = False
# while not exit:
# print("exit: {}", exit)
# try:
# for m in measurements(iface):
# print_bboard_measurements(*m)
# print("q to exit else to continue")
# c = sys.stdin.read(1)
# if c == 'q':
# exit = True
# break
# try:
# except KeyboardInterrupt:
# print("Bye!")
print("closing device iface")
_iface.close(xwiimote.IFACE_BALANCE_BOARD)
print("bt disconnect device")
subprocess.call(["bt-device", "-d", "Nintendo RVL-WBC-01"])
#subprocess.call(arg1)
# poll unregisterp.unregister(mon_fd)
# device
if __name__ == '__main__':
main()