-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.py
666 lines (561 loc) · 20.8 KB
/
main.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.properties import DictProperty, StringProperty, \
NumericProperty, ListProperty, BooleanProperty, ObjectProperty,\
ConfigParserProperty
from kivy.clock import Clock, mainthread
from kivy.animation import Animation
import ddd # noqa
from kivy.lib.osc.OSC import OSCMessage
from kivy.utils import platform
from kivy.lang import Builder
from kivy.core.window import Window
Window.softinput_mode = 'resize'
from socket import socket, AF_INET, SOCK_DGRAM
from uuid import uuid4 as uuid
try:
from random import random, randint, gauss
NO_SIMULATE = False
except ImportError as e:
NO_SIMULATE = e
import sys
try:
import rtmidi2
except:
rtmidi2 = None
from time import time
from struct import pack, unpack
import gc
if platform == 'android':
from androidhelpers import AndroidScanner, start_scanning, stop_scanning
elif platform == 'macosx':
from osx_ble import Ble
elif platform == 'linux':
from linux_ble import LinuxBle
__version__ = '1.0'
PROFILE = False
MIDI_SIGNALS = {
176: 'Control',
128: 'Note Off',
144: 'Note On',
224: 'Note Aftertouch',
'Control': 176,
'Note Off': 128,
'Note On': 144,
'Note Aftertouch': 224,
}
def configbool(value):
if isinstance(value, basestring):
return value.lower() not in ('false', 'no', '')
return bool(value)
class ObjectView(GridLayout):
device = ObjectProperty(None, rebind=True)
class GraphZone(GridLayout):
device = ObjectProperty(None, rebind=True)
focus = StringProperty('accelero')
class MidiSensorLine(BoxLayout):
sensor = StringProperty('')
device = ObjectProperty(None, rebind=True)
active = BooleanProperty(False)
signal = StringProperty('')
chan = StringProperty('')
event_id = StringProperty('')
event_value = StringProperty('')
def __init__(self, **kwargs):
super(MidiSensorLine, self).__init__(**kwargs)
self.bind(
active=self.update,
chan=self.update,
signal=self.update,
event_id=self.update,
event_value=self.update
)
self.load_values()
def update(self, *args):
app.config.set(
self.device.name + '-midi',
self.sensor,
'%s,%s,%s,%s,%s' % (
1 if self.active else 0,
MIDI_SIGNALS.get(self.signal, ''),
self.chan,
self.event_id,
self.event_value
)
)
def load_values(self, *args):
if self.device and self.sensor:
section = self.device.name + '-midi'
values = app.config.get(section, self.sensor)
active, signal, chan, event_id, event_value = values.split(',')
self.active = True if active == '1' else False
self.signal = MIDI_SIGNALS.get(int(signal), 'Note On')
self.chan = chan
self.event_id = event_id
self.event_value = event_value
class OscConfigLine(BoxLayout):
key = StringProperty('')
ip = StringProperty('localhost')
port = StringProperty('')
address = StringProperty('/')
content = StringProperty('')
config = ObjectProperty(None)
def __init__(self, **kwargs):
super(OscConfigLine, self).__init__(**kwargs)
self.bind(ip=self.update,
port=self.update,
address=self.update,
content=self.update)
def update(self, *args):
app.config.set(
self.config.device.name + '-osc', self.key,
'%s,%s,%s,%s' %
(self.ip, self.port, self.address, self.content.replace(',', ' ')))
class ConfigPanel(GridLayout):
device = ObjectProperty(None)
class MidiConfig(ConfigPanel):
def on_device(self, *args):
if self.device:
self.ids.content.clear_widgets()
for s in app.sensor_list:
self.ids.content.add_widget(
MidiSensorLine(sensor=s, device=self.device))
class OscConfig(ConfigPanel):
device = ObjectProperty(None, rebind=True)
def on_device(self, *args):
if self.device:
self.load_config(self.device)
def load_config(self, device):
for k, v in app.config.items(self.device.name + '-osc'):
ip, port, address, content = v.split(',')
self.add_line(
key=k, ip=ip, port=port, address=address,
content=content.replace(' ', ','))
def add_line(self, **kwargs):
kwargs.setdefault('key', str(uuid()))
self.ids.content.add_widget(OscConfigLine(config=self, **kwargs))
def remove_line(self, line):
self.ids.content.remove_widget(line)
app.config.remove_option(self.device.name + '-osc', line.key)
def check_osc_values(self, *args):
return self.device.check_osc_values(*args)
class TwizDevice(FloatLayout):
active = BooleanProperty(False)
name = StringProperty('')
power = NumericProperty(0)
last_update = NumericProperty(0)
display = BooleanProperty(False)
rx = ListProperty([0, ])
ry = ListProperty([0, ])
rz = ListProperty([0, ])
cx = ListProperty([0, ])
cy = ListProperty([0, ])
cz = ListProperty([0, ])
ax = ListProperty([0, ])
ay = ListProperty([0, ])
az = ListProperty([0, ])
def update_data(self, data):
for d in data:
if d in ('name', 'power'):
setattr(self, d, data[d])
elif d == 'sensor':
d = data['sensor']
# XXX performances!
ax, ay, az, rx, ry, rz =\
self.ax, self.ay, self.az, self.rx, self.ry, self.rz
if len(ax) > 100:
ax.pop(0)
ay.pop(0)
az.pop(0)
rx.pop(0)
ry.pop(0)
rz.pop(0)
_ax, _ay, _az, _rz, _ry, _rx = d
ax.append(_ax)
ay.append(_ay)
az.append(_az)
rx.append(_rx)
ry.append(_ry)
rz.append(_rz)
self.last_update = time()
self.send_updates()
def on_active(self, *args):
if not self.display and not self.active:
if hasattr(app.scanner, 'disconnect'):
app.scanner.disconnect(app.scanner.peripherals[self.name][0])
if self.active:
app.ensure_sections(self)
if hasattr(app.scanner, 'connect'):
app.scanner.connect(app.scanner.peripherals[self.name][0], stop_scan=False)
else:
if hasattr(app.scanner, 'disconnect'):
app.scanner.disconnect(app.scanner.peripherals[self.name][0])
def send_updates(self):
if not self.active:
if app.auto_activate and app.config.items(self.name + '-osc'):
self.active = True
else:
return
self.send_osc_updates()
self.send_midi_updates()
def check_osc_values(self, ip, port, address, content):
try:
int(port)
except ValueError:
print "invalid port", port
return False
if not address.startswith('/'):
print "invalid address", address
return False
for c in content.split(' '):
if c.isdigit() or c.startswith("'") and c.endswith("'"):
continue
if c.split('_')[0] not in app.sensor_list + ['id']:
print "invalid sensor", c
return False
return True
def send_osc_updates(self):
sendto = app.osc_socket.sendto
# XXX potential performances killer, maybe cache these somewhere
app.ensure_sections(self)
for k, v in app.config.items(self.name + '-osc'):
ip, port, address, content = v.split(',')
if not self.check_osc_values(ip, port, address, content):
continue
data = OSCMessage()
data.setAddress(address)
for i in content.split(' '):
i = i.strip()
if i.isdigit():
data.append(int(i))
elif i.startswith("'"):
data.append(i.strip("'"))
else:
if '_' in i:
d, t = i.split('_')
i = d
if t == 'd':
func = lambda x: (float(x) / 0xffff) + .5
else:
func = lambda x: x % 0xffff
else:
func = lambda x: x
if i in app.sensor_list:
data.append(func(getattr(self, i)[-1]))
elif i == 'id':
data.append(self.name)
# print "osc sending data", data
sendto(data.getBinary(), (ip, int(port)))
def send_midi_updates(self):
if not rtmidi2:
return
port = app.midi_out
items = app.config.items(self.name + '-midi')
for k, v in items:
active, signal, chan, ev_id, ev_value = v.split(',')
if not active == '1':
continue
value = getattr(self, k)[-1] >> 9
message = (int(x) for x in (
signal, chan, ev_id.replace('v', '') or value,
ev_value.replace('v', '') or value))
message = tuple(message)
# print "sending message %s" % (message,)
port.send_message(message)
def on_display(self, *args):
if not self.display:
app.remove_visu(self)
if hasattr(app.scanner, 'disconnect') and not self.active:
app.scanner.disconnect(app.scanner.peripherals[self.name][0])
else:
app.add_visu(self)
if hasattr(app.scanner, 'connect'):
app.scanner.connect(app.scanner.peripherals[self.name][0], stop_scan=False)
class TwizSimulator(TwizDevice):
values = ListProperty([0, 0, 0, 0, 0, 0])
def __init__(self, **kwargs):
super(TwizSimulator, self).__init__(**kwargs)
self.simulate_values()
def simulate_values(self, *args):
a = Animation(
values=[randint(0, 0xffff) for x in app.sensor_list],
d=random() * 3,
t='in_out_sine')
a.bind(on_complete=self.simulate_values)
a.start(self)
def on_values(self, *args):
self.update_data(
{
'name': 'simulator',
'power': int(gauss(80, 5)),
'sensor': self.values
}
)
class Graph(Widget):
device = ObjectProperty(None, rebind=True)
line_x = ListProperty([], rebind=True)
line_y = ListProperty([], rebind=True)
line_z = ListProperty([], rebind=True)
data_len = NumericProperty(0)
class BLEApp(App):
scan_results = DictProperty({})
visus = DictProperty({})
error_log = StringProperty('')
sensor_list = ListProperty(
['rx', 'ry', 'rz', 'ax', 'ay', 'az'])
auto_activate = ConfigParserProperty(
False, 'general', 'auto_activate', 'app', val_type=configbool)
auto_display = ConfigParserProperty(
False, 'general', 'auto_display', 'app', val_type=configbool)
device_filter = ConfigParserProperty(
'', 'general', 'device_filter', 'app', val_type=str)
nexus4_fix = ConfigParserProperty(
False, 'android', 'nexus4_fix', 'app', val_type=configbool)
osx_queue_fix = ConfigParserProperty(
False, 'osx', 'osx_queue_fix', 'app', val_type=configbool)
display_timeout = ConfigParserProperty(
10, 'general', 'display_timeout', 'app', val_type=int)
def build(self):
# uncomment these lines to use profiling
# if __name__ != '__main__':
# self.root = Builder.load_file('ble.kv')
self.scanner = None
self.init_ble()
self.set_scanning(True)
self.osc_socket = socket(AF_INET, SOCK_DGRAM)
if rtmidi2:
self.midi_out = rtmidi2.MidiOut().open_virtual_port(':0')
Clock.schedule_interval(self.clean_results, 1)
if '--simulate' in sys.argv:
if NO_SIMULATE:
raise NO_SIMULATE
Clock.schedule_once(self.simulate_twiz, 0)
return super(BLEApp, self).build()
def on_pause(self, *args):
return True
def build_config(self, config):
config.setdefaults('general', {
'auto_activate': False,
'auto_display': False
})
config.setdefaults('android', {
'nexus4_fix': False,
})
config.setdefaults('osx', {
'osx_queue_fix': False,
})
def build_settings(self, settings):
settings.add_json_panel(
'Twiz-manager',
self.config,
'twiz_manager.json'
)
def on_stop(self, *args):
print "writing config"
self.config.write()
print "config written"
def open_content_dropdown(self, text_input):
options = {
'euler angles (0-0xffff)': 'rx,ry,rz',
'euler angles (0-1.0)': 'rx_d,ry_d,rz_d',
'accelerations (0-0xffff)': 'ax,ay,az',
'accelerations (0-1.0)': 'ax_d,ay_d,az_d',
'accelerations + euler (0-0xffff)': 'ax,ay,az,rx,ry,rz',
'accelerations + euler (0-1.0)': 'ax_d,ay_d,az_d,rx_d,ry_d,rz_d',
}
#d = DropDown(width=text_input.width)
#for o in options:
# b = Button(text=o, size_hint_y=None)
# b.bind(texture_size=b.setter('size'))
# b.bind(on_press=lambda x: text_input.setter('text')(options[o]))
# d.add_widget(b)
#d.open(text_input)
p = Popup(title='message content', size_hint=(.9, .9))
def callback(option):
text_input.text = options.get(option, option)
p.dismiss()
content = GridLayout(spacing=10, cols=1)
for o in options:
b = Button(text=o)
b.bind(on_press=lambda x: callback(x.text))
content.add_widget(b)
instructions = Label(
text='custom content:\n two types of sensors are '
'proposed, rotation (euler angles) and acceleration, each '
'in 3 axis: rx, ry and rz represent rotation values, ax, '
'ay and az represent acceleration values, any value can '
'take a "_d" suffix, to be casted to a value between 0 '
'and 1 instead of the default (from 0 to 0xffff', size_hint_y=None)
instructions.bind(
size=instructions.setter('text_size'),
texture_size=instructions.setter('size'))
content.add_widget(instructions)
ti = TextInput(
text=text_input.text,
multiline=False,
input_type='text',
keyboard_suggestions=False)
content.add_widget(ti)
b = Button(text='set custom')
b.bind(on_press=lambda x: callback(ti.text))
content.add_widget(b)
p.add_widget(content)
p.open()
def clean_results(self, dt):
# forget devices after N seconds without any update
if not self.display_timeout:
return
t = time() - self.display_timeout
for k, v in self.scan_results.items():
if v.last_update < t:
self.scan_results.pop(k)
self.root.ids.scan.ids.results.remove_widget(v)
self.remove_visu(v)
def on_osx_queue_fix(self, *args):
self.scanner.queue = [] if self.osx_queue_fix else None
def init_ble(self):
if platform == 'android':
self.scanner = AndroidScanner()
self.scanner.callback = self.android_parse_event
elif platform == 'macosx':
self.scanner = Ble()
self.scanner.create()
self.scanner.callback = self.osx_parse_event
self.scanner.queue = [] if self.osx_queue_fix else None
else:
try:
self.scanner = LinuxBle(callback=self.update_device)
except OSError:
print "unable to get a ble device, try using the simulator"
def simulate_twiz(self, dt):
self.root.ids.scan.add_widget(TwizSimulator())
def filter_scan_result(self, result):
return self.device_filter.strip().lower() in result.lower()
def restart_scanning(self, dt):
self.scanning_active = not self.scanning_active
if self.scanning_active:
stop_scanning(self.scanner)
else:
start_scanning(self.scanner)
def set_scanning(self, value):
if not self.scanner:
return
if platform == 'android':
if value:
start_scanning(self.scanner)
if app.nexus4_fix:
self.scanning_active = True
Clock.schedule_interval(self.restart_scanning, .05)
else:
stop_scanning(self.scanner)
Clock.unschedule(self.restart_scanning)
elif platform == 'macosx':
self.scanner.start_scan()
else:
if value:
# hci_le_set_scan_parameters(sock)
self.scanner.start()
else:
self.scanner.stop()
def ensure_sections(self, device):
section = device.name + '-osc'
if not self.config.has_section(section):
app.config.add_section(section)
app.config.setdefaults(section, {
})
section = device.name + '-midi'
if not self.config.has_section(section):
app.config.add_section(section)
app.config.setdefaults(section, {
k: '0,0,0,0,v'
for k in app.sensor_list
})
def add_visu(self, device):
self.ensure_sections(device)
w = ObjectView(device=device)
self.visus[device] = w
self.root.ids.visu.ids.content.add_widget(w)
def remove_visu(self, device):
w = self.visus.get(device)
if w and w in self.root.ids.visu.ids.content.children:
self.root.ids.visu.ids.content.remove_widget(w)
del(self.visus[device])
gc.collect()
@mainthread
def update_device(self, data):
name = data.get('name', '')
pd = self.scan_results.get(name)
if not pd:
pd = TwizDevice()
pd.update_data(data)
results = self.root.ids.scan.ids.results
if app.auto_display:
pd.display = True
if pd.name not in self.scan_results:
self.scan_results[pd.name] = pd
results.add_widget(pd)
def decode_data(self, pkt):
pkt = pack('<' + 'b' * len(pkt), *pkt.tolist())
local_name_len, = unpack("B", pkt[0])
dtype = 0
offset = 1 + local_name_len
sensor_data = None
while offset < len(pkt):
dlen, dtype = unpack(
'BB', pkt[offset:offset + 2])
if dtype == 0xff:
sensor_data = unpack(
'>' + 'h' * ((dlen - 3) // 2),
pkt[offset + 4:offset + dlen + 1])
break
offset += dlen + 1
return sensor_data
def android_parse_event(self, name, address, irssi, data):
if not name or not self.filter_scan_result(name):
return
device_data = {
'name': name,
'power': irssi,
}
try:
sensor = self.decode_data(data)
except:
self.error_log += 'error decoding data from %s:%s\n' % (
name,
unpack('<' + 'B' * len(data),
pack('<' + 'b' * len(data), data)))
if sensor:
device_data['sensor'] = sensor
self.update_device(device_data)
def osx_parse_event(self, rssi, name, values):
if len(values) > 12:
values = values[2:]
device_data = {
'name': name,
'power': rssi,
'sensor': unpack('>' + 'h' * (len(values) / 2), ''.join(values)),
}
self.update_device(device_data)
app = BLEApp()
if PROFILE:
import cProfile
from time import gmtime
from os.path import join, normpath, expanduser
from os import makedirs
profile_path = join(normpath(expanduser(app.user_data_dir)),
'profiling')
try:
makedirs(profile_path)
except:
pass
filename = 'ble_{t.tm_year}-{t.tm_mon}-{t.tm_mday}:{t.tm_hour}-{t.tm_min}-{t.tm_sec}.profile'.format(t=gmtime()) # noqa
cProfile.run('app.run()', join(profile_path, filename))
else:
app.run()