-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwiimote_node.py
178 lines (143 loc) · 5.52 KB
/
wiimote_node.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
#!/usr/bin/env python3
# coding: utf-8
# -*- coding: utf-8 -*-
from pyqtgraph.flowchart import Flowchart, Node
from pyqtgraph.flowchart.library.common import CtrlNode
import pyqtgraph.flowchart.library as fclib
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
import wiimote
class BufferNode(CtrlNode):
"""
Buffers the last n samples provided on input and provides them as a list of
length n on output.
A spinbox widget allows for setting the size of the buffer.
Default size is 32 samples.
"""
nodeName = "Buffer"
uiTemplate = [
('size', 'spin', {'value': 32.0, 'step': 1.0, 'bounds': [0.0, 128.0]}),
]
def __init__(self, name):
terminals = {
'dataIn': dict(io='in'),
'dataOut': dict(io='out'),
}
self._buffer = np.array([])
CtrlNode.__init__(self, name, terminals=terminals)
def process(self, **kwds):
size = int(self.ctrls['size'].value())
self._buffer = np.append(self._buffer, kwds['dataIn'])
self._buffer = self._buffer[-size:]
output = self._buffer
return {'dataOut': output}
fclib.registerNodeType(BufferNode, [('Data',)])
class WiimoteNode(Node):
"""
Outputs sensor data from a Wiimote.
Supported sensors: accelerometer (3 axis)
Text input box allows for setting a Bluetooth MAC address.
Pressing the "connect" button tries connecting to the Wiimote.
Update rate can be changed via a spinbox widget. Setting it to "0"
activates callbacks every time a new sensor value arrives (which is
quite often -> performance hit)
"""
nodeName = "Wiimote"
def __init__(self, name):
terminals = {
'accelX': dict(io='out'),
'accelY': dict(io='out'),
'accelZ': dict(io='out'),
}
self.wiimote = None
self._acc_vals = []
# Configuration UI
self.ui = QtGui.QWidget()
self.layout = QtGui.QGridLayout()
label = QtGui.QLabel("Bluetooth MAC address:")
self.layout.addWidget(label)
self.text = QtGui.QLineEdit()
self.btaddr = "b8:ae:6e:18:5d:ab" # set some example
self.text.setText(self.btaddr)
self.layout.addWidget(self.text)
label2 = QtGui.QLabel("Update rate (Hz)")
self.layout.addWidget(label2)
self.update_rate_input = QtGui.QSpinBox()
self.update_rate_input.setMinimum(0)
self.update_rate_input.setMaximum(60)
self.update_rate_input.setValue(20)
self.update_rate_input.valueChanged.connect(self.set_update_rate)
self.layout.addWidget(self.update_rate_input)
self.connect_button = QtGui.QPushButton("connect")
self.connect_button.clicked.connect(self.connect_wiimote)
self.layout.addWidget(self.connect_button)
self.ui.setLayout(self.layout)
# update timer
self.update_timer = QtCore.QTimer()
self.update_timer.timeout.connect(self.update_all_sensors)
# super()
Node.__init__(self, name, terminals=terminals)
def update_all_sensors(self):
if self.wiimote is None:
return
self._acc_vals = self.wiimote.accelerometer
# todo: other sensors...
self.update()
def update_accel(self, acc_vals):
self._acc_vals = acc_vals
self.update()
def ctrlWidget(self):
return self.ui
def connect_wiimote(self):
self.btaddr = str(self.text.text()).strip()
if self.wiimote is not None:
self.wiimote.disconnect()
self.wiimote = None
self.connect_button.setText("connect")
return
if len(self.btaddr) == 17:
self.connect_button.setText("connecting...")
self.wiimote = wiimote.connect(self.btaddr)
if self.wiimote is None:
self.connect_button.setText("try again")
else:
self.connect_button.setText("disconnect")
self.set_update_rate(self.update_rate_input.value())
def set_update_rate(self, rate):
if rate == 0: # use callbacks for max. update rate
self.update_timer.stop()
self.wiimote.accelerometer.register_callback(self.update_accel)
else:
self.wiimote.accelerometer.unregister_callback(self.update_accel)
self.update_timer.start(1000.0/rate)
def process(self, **kwdargs):
x, y, z = self._acc_vals
return {'accelX': np.array([x]), 'accelY': np.array([y]), 'accelZ': np.array([z])}
fclib.registerNodeType(WiimoteNode, [('Sensor',)])
if __name__ == '__main__':
import sys
app = QtGui.QApplication([])
win = QtGui.QMainWindow()
win.setWindowTitle('WiimoteNode demo')
cw = QtGui.QWidget()
win.setCentralWidget(cw)
layout = QtGui.QGridLayout()
cw.setLayout(layout)
# Create an empty flowchart with a single input and output
fc = Flowchart(terminals={
})
w = fc.widget()
layout.addWidget(fc.widget(), 0, 0, 2, 1)
pw1 = pg.PlotWidget()
layout.addWidget(pw1, 0, 1)
pw1.setYRange(0, 1024)
pw1Node = fc.createNode('PlotWidget', pos=(0, -150))
pw1Node.setPlot(pw1)
wiimoteNode = fc.createNode('Wiimote', pos=(0, 0), )
bufferNode = fc.createNode('Buffer', pos=(150, 0))
fc.connectTerminals(wiimoteNode['accelX'], bufferNode['dataIn'])
fc.connectTerminals(bufferNode['dataOut'], pw1Node['In'])
win.show()
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()