-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathscratch-wedo2.py
executable file
·275 lines (220 loc) · 8.83 KB
/
scratch-wedo2.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
#!/usr/bin/env python
import sys
import random
import traceback
import logging
import binascii
from gattlib import GATTRequester
from time import sleep
from threading import Timer
from struct import pack, unpack
from flask import Flask
HANDLE_PORT = 0x15
HANDLE_BUTTON = 0x11
HANDLE_SENSOR_VALUE = 0x32
HANDLE_INPUT_COMMAND = 0x3a
HANDLE_OUTPUT_COMMAND = 0x3d
HANDLE_BATTERY_LEVEL = 0x48
HANDLE_CCC_BUTTON = 0x12
HANDLE_CCC_PORT = 0x16
HANDLE_CCC_SENSOR_VALUE = 0x33
HANDLE_CCC_BATTERY_LEVEL = 0x49
TYPE_MOTOR = 0x1
TYPE_VOLTAGE = 0x14
TYPE_CURRENT = 0x15
TYPE_PIEZO_TONE = 0x16
TYPE_RGB_LIGHT = 0x17
TYPE_TILT = 0x22
TYPE_MOTION = 0x23
COMMAND_ID_INPUT_VALUE = 0
COMMAND_ID_INPUT_FORMAT = 1
COMMAND_TYPE_READ = 1
COMMAND_TYPE_WRITE = 2
INPUT_FORMAT_UNIT_RAW = 0
INPUT_FORMAT_UNIT_PERCENT = 1
INPUT_FORMAT_UNIT_SI = 2
TILT_SENSOR_MODE_TILT = 1
TILT_NEUTRAL = 0
TILT_BACKWARD = 3
TILT_RIGHT = 5
TILT_LEFT = 7
TILT_FORWARD = 9
TILT_UNKNOWN = 10
class Requester(GATTRequester):
def __init__(self, address, connect = True):
super(Requester, self).__init__(address, connect)
self.motor = 0
self.piezoTone = 0
self.sensor = [0] * 7
self.button = 0
self.direction = 0
self.distance = 10
self.voltage = 0
self.current = 0
self.battery_level = 100
def on_notification(self, handle, data):
data = data[3:]
if handle == HANDLE_PORT:
port, attach = unpack("<BB", data[0:2])
if attach:
print("Notification on handle: {} {} {}".format(hex(handle), len(data), binascii.hexlify(data)))
hubIndex, type = unpack("<BB", data[2:4])
self.sensor[port] = type
if type == TYPE_TILT:
self.write_without_response_by_handle(HANDLE_INPUT_COMMAND, pack("<BBBBBIBB", COMMAND_ID_INPUT_FORMAT, COMMAND_TYPE_WRITE, port, TYPE_TILT, TILT_SENSOR_MODE_TILT, 1, INPUT_FORMAT_UNIT_RAW, 1))
elif type == TYPE_MOTION:
self.write_without_response_by_handle(HANDLE_INPUT_COMMAND, pack("<BBBBBIBB", COMMAND_ID_INPUT_FORMAT, COMMAND_TYPE_WRITE, port, TYPE_MOTION, 0, 1, INPUT_FORMAT_UNIT_RAW, 1))
elif type == TYPE_MOTOR:
self.motor = port
elif type == TYPE_VOLTAGE:
self.write_without_response_by_handle(HANDLE_INPUT_COMMAND, pack("<BBBBBIBB", COMMAND_ID_INPUT_FORMAT, COMMAND_TYPE_WRITE, port, TYPE_VOLTAGE, 0, 30, INPUT_FORMAT_UNIT_SI, 1))
elif type == TYPE_CURRENT:
self.write_without_response_by_handle(HANDLE_INPUT_COMMAND, pack("<BBBBBIBB", COMMAND_ID_INPUT_FORMAT, COMMAND_TYPE_WRITE, port, TYPE_CURRENT, 0, 30, INPUT_FORMAT_UNIT_SI, 1))
elif type == TYPE_PIEZO_TONE:
self.piezoTone = port
elif handle == HANDLE_SENSOR_VALUE:
revision = unpack("<B", data[0:1])
data = data[1:]
while data:
port = unpack("<B", data[0:1])[0]
if self.sensor[port] == TYPE_TILT:
self.direction = unpack("<B", data[1:2])[0]
data = data[2:]
elif self.sensor[port] == TYPE_MOTION:
print("Notification on handle: {} {} {}".format(hex(handle), len(data), binascii.hexlify(data)))
self.distance = unpack("<B", data[1:2])[0]
print "distance " + str(self.distance)
data = data[2:]
elif self.sensor[port] == TYPE_VOLTAGE:
self.voltage = unpack("<f", data[1:5])[0]
data = data[5:]
elif self.sensor[port] == TYPE_CURRENT:
self.current = unpack("<f", data[1:5])[0]
data = data[5:]
else:
break
elif handle == HANDLE_BUTTON:
self.button = unpack("<B", data[0])[0]
elif handle == HANDLE_BATTERY_LEVEL:
self.battery_level = unpack("<B", data[0])[0]
else:
print("Notification on handle: {} {} {}".format(handle, len(data), binascii.hexlify(data)))
app = Flask(__name__)
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
ADDRESS = sys.argv[1]
motorDirection = {}
motorPower = {}
busy = {}
req = Requester(ADDRESS, False)
req.connect(True)
req.write_without_response_by_handle(HANDLE_CCC_BUTTON, pack("<h", 0x0001))
req.write_without_response_by_handle(HANDLE_CCC_PORT, pack("<h", 0x0001))
req.write_without_response_by_handle(HANDLE_CCC_SENSOR_VALUE, pack("<h", 0x0001))
req.write_without_response_by_handle(HANDLE_CCC_BATTERY_LEVEL, pack("<h", 0x0001))
@app.route("/crossdomain.xml")
def crossdomain():
return '''
<cross-domain-policy>
<allow-access-from domain="*" to-ports="<yourPort>"/>
</cross-domain-policy>
'''
@app.route("/reset_all")
def reset():
motorDirection = {}
motorPower = {}
busy = {}
# Stop motors
req.write_without_response_by_handle(HANDLE_OUTPUT_COMMAND, "\x06\x04\x01\x00")
req.write_without_response_by_handle(HANDLE_OUTPUT_COMMAND, "\x06\x04\x02\x00")
# Stop piezo tone generator
req.write_without_response_by_handle(HANDLE_OUTPUT_COMMAND, pack("<bb", req.piezoTone, 0x03))
setLight("off")
return ""
@app.route("/setLight/<color>")
def setLight(color):
COLORS = ( "off", "pink", "purple", "blue", "sky blue", "teal", "green", "yellow", "orange", "red", "white")
if color == "random":
color = random.randint(1,10)
else:
color = COLORS.index(color)
print("Set light color to " + str(color))
req.write_without_response_by_handle(HANDLE_OUTPUT_COMMAND, "\x06\x04\x01" + chr(color))
return ""
@app.route("/setMotorDirection/<motor>/<direction>")
def setMotorDirection(motor, direction):
DIRECTION = ["that way", "other way", "this way"]
try:
motorDirection[motor] = DIRECTION.index(direction) - 1
except Exception as e:
logging.error(traceback.format_exc())
print("Set motor direction of " + motor + " to " + direction)
return ""
@app.route("/startMotorPower/<motor>/<power>")
def startMotorPower(motor, power):
try:
motorPower[motor] = int(power)
except Exception as e:
logging.error(traceback.format_exc())
print("Set motor power of " + motor + " to " + power)
return ""
@app.route("/motorOn/<motor>")
def motorOn(motor):
print "motor on " + str(motorDirection.get(motor, 1) * motorPower.get(motor, 50))
sleep(1.0/30.0)
print "go"
req.write_without_response_by_handle(HANDLE_OUTPUT_COMMAND, pack("<bbbb", req.motor, 0x01, 0x01, motorDirection.get(motor, 1) * motorPower.get(motor, 50)))
return ""
@app.route("/motorOff/<motor>")
def motorOff(motor):
req.write_without_response_by_handle(HANDLE_OUTPUT_COMMAND, pack("<bbbb", req.motor, 0x01, 0x01, 0))
print
return ""
@app.route("/motorOnFor/<id>/<motor>/<duration>")
def motorOnFor(id, motor, duration):
busy[id] = True
#print("Start " + motorPower.get(motor, 50) + " " + duration)
print "motor " + str(req.motor)
motorOn(motor)
Timer(float(duration), endMotorOnFor, [id, motor]).start()
return ""
def endMotorOnFor(id, motor):
motorOff(motor)
del busy[id]
print "Stop"
@app.route("/playSound/<id>/<note>/<octave>/<duration>")
def playSound(id, note, octave, duration):
NOTES = [ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" ]
octave = float(octave)
note = float(NOTES.index(note))
# https://en.wikipedia.org/wiki/Equal_temperament
frequency = round(440.0 * 2 ** (((octave - 4) * 12 + note - 9) / 12))
duration = float(duration)
print str(note) + " " + str(octave) + " " + str(frequency) + " " + str(duration)
req.write_without_response_by_handle(HANDLE_OUTPUT_COMMAND, pack("<bbbhh", req.piezoTone, 0x02, 0x04, frequency, round(duration * 1000.0)))
busy[id] = True
Timer(duration - 1.0/30.0, endPlaySound, [id]).start()
return ""
def endPlaySound(id):
del busy[id]
@app.route("/poll")
def poll():
BOOL = ('false', 'true')
TILT_STR = ( "any", "any", "any", "up", "any", "right", "any", "left", "any", "down", "any" )
result = []
result.append("button1 " + BOOL[req.button])
result.append("tilt " + TILT_STR[req.direction])
result.append("isTilted up " + BOOL[req.direction == TILT_BACKWARD])
result.append("distance " + str(req.distance))
result.append("voltage1 " + str(int(req.voltage)))
result.append("current1 " + str(int(req.current)))
result.append("battery1 " + str(req.battery_level))
for id in busy:
result.append("_busy " + id)
return "\n".join(result)
@app.errorhandler(Exception)
def all_exception_handler(error):
logging.error(traceback.format_exc())
return 'Error', 500
if __name__ == "__main__":
app.run(port=17311, threaded=True)