-
Notifications
You must be signed in to change notification settings - Fork 0
/
ble.py
308 lines (271 loc) · 11 KB
/
ble.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
# (c) 2014 Productize <[email protected]>
import serial, time
import bglib
from PySide import QtCore
# https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile
GAP_AD_TYPE_FLAGS = 0x01
GAP_AD_TYPE_16BIT_UUIDS = 0x03
GAP_AD_TYPE_LOCALNAME_COMPLETE = 0x09
GAP_AD_TYPE_TX_POWER = 0x0A
GAP_AD_TYPE_SLAVE_CON_INTERVAL_RANGE = 0x12
GAP_AD_TYPE_APPEARANCE = 0x19
GAP_AD_TYPE_VENDOR = 0xFF
_event_type = ["IND", "DIRECT_IND", "SCAN_IND", "NONCONN_IND", "SCAN_RSP"]
def event_type(n):
try:
return _event_type[n]
except:
return "RESERVED"
class ActivityThread(QtCore.QThread):
def __init__(self, ble, parent=None):
super(ActivityThread, self).__init__(parent)
self._stop = False
self.ble = ble
def run(self):
while not self._stop:
self.ble.check_activity()
time.sleep(0.01)
def stop(self):
self._stop = True
class BLE(QtCore.QObject):
scan_response = QtCore.Signal(dict)
connection_status = QtCore.Signal(int, str, int)
timeout = QtCore.Signal()
service_result = QtCore.Signal(int, list, int, int)
procedure_completed = QtCore.Signal(int)
info_found = QtCore.Signal(int, int, list)
attr_value = QtCore.Signal(int, int, int, list)
CONNECTED = 0
DISCONNECTED = 1
def __init__(self, baud_rate, packet_mode = False):
import data
super(BLE, self).__init__()
self.led = False
self.port = None
self.baud_rate = baud_rate
self.packet_mode = packet_mode
self.address = None
self.uuid = data.UUID()
self.handles_to_read = []
def address_response(self, sender, args):
self.address = ':'.join(['%02X' % b for b in args['address'][::-1]])
self.auto_detected = True
def auto_detect_serial(self):
import glob
glist = glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/cu.usbmodem*')
self.auto_detected = False
for port in glist:
print "trying", port
ble = None
ble = bglib.BGLib()
ble.package_mode = self.packet_mode
ble.ble_rsp_system_address_get += self.address_response
ser = serial.Serial(port, self.baud_rate, timeout=1)
ser.flushInput()
ser.flushOutput()
ble.send_command(ser, ble.ble_cmd_system_address_get())
time.sleep(0.1)
try:
ble.check_activity(ser, 1)
except:
pass
if self.auto_detected:
self.port = port
self.ser = ser
self.ble = ble
print "Using serial:", port
return
else:
ser.close()
raise Exception("Serial port not found")
def start(self, port = None):
if port is None:
self.auto_detect_serial()
else:
self.ble = bglib.BGLib()
self.ble.packet_mode = self.packet_mode
self.ble.ble_rsp_system_address_get += self.address_response
ble = self.ble
ble.on_timeout += self.on_timeout
ble.ble_evt_gap_scan_response += self.handle_scan_response
self.ser = serial.Serial(port=self.port, baudrate=self.baud_rate, timeout=1)
self.ser.flushInput()
self.ser.flushOutput()
ser = self.ser
# disconnect if we are connected already
self.send_command(ble.ble_cmd_connection_disconnect(0))
ble.check_activity(ser, 1)
# stop advertising if we are advertising already
self.send_command(ble.ble_cmd_gap_set_mode(0, 0))
ble.check_activity(ser, 1)
# stop scanning if we are scanning already
self.send_command(ble.ble_cmd_gap_end_procedure())
ble.check_activity(ser, 1)
# set scan parameters
self.send_command(ble.ble_cmd_gap_set_scan_parameters(0xC8, 0xC8, 1))
ble.check_activity(ser, 1)
# start scanning now
self.send_command(ble.ble_cmd_gap_discover(2))
ble.check_activity(ser, 1)
# IO port stuff for LED; doesn't work currently
self.send_command(ble.ble_cmd_hardware_io_port_config_pull(0, 0, 0))
self.send_command(ble.ble_cmd_hardware_io_port_config_direction(0, 1))
self.send_command(ble.ble_cmd_hardware_io_port_config_function(0, 0))
self.send_command(ble.ble_cmd_hardware_io_port_write(0, 1, 0))
# handle connections
self.ble.ble_evt_connection_status += self.handle_connection_status
self.ble.ble_evt_connection_disconnected += self.handle_connection_disconnected
# handle service info
self.ble.ble_evt_attclient_group_found += self.handle_attclient_group_found
# get local address
ble.send_command(ser, ble.ble_cmd_system_address_get())
ble.check_activity(ser, 1)
print "local device:", self.address
self.ble.ble_evt_attclient_procedure_completed += self.handle_attclient_procedure_completed
self.ble.ble_evt_attclient_find_information_found += self.handle_attclient_information_found
self.ble.ble_evt_attclient_attribute_value += self.handle_attclient_attribute_value
self.ble.ble_evt_attclient_read_multiple_response += self.handle_attclient_read_multiple_response
def send_command(self, cmd):
return self.ble.send_command(self.ser, cmd)
def on_timeout(self, sender, args):
# might want to try the following lines to reset, though it probably
# wouldn't work at this point if it's already timed out:
#ble.send_command(ser, ble.ble_cmd_system_reset(0))
#ble.check_activity(ser, 1)
print "BGAPI parser timed out. Make sure the BLE device is in a known/idle state."
self.timeout.emit()
def handle_scan_response(self, sender, args):
#print args
if self.led == False:
self.send_command(self.ble.ble_cmd_hardware_io_port_write(0, 1, 1))
self.led = True
else:
self.send_command(self.ble.ble_cmd_hardware_io_port_write(0, 1, 0))
self.led = False
self.scan_response.emit(args)
def handle_connection_status(self, sender, args):
#print sender, args
if (args['flags'] & 0x05) == 0x05:
f = ':'.join(['%02X' % b for b in args['address'][::-1]])
h = args['connection']
print "Connected to %d %s" % (h, f)
self.connection_status.emit(h, f, self.CONNECTED)
def handle_connection_disconnected(self, sender, args):
h = args['connection']
reason = args['reason']
print "Disconnected to %d because %s" % (h, reason)
self.connection_status.emit(h, "", self.DISCONNECTED)
def handle_attclient_group_found(self, sender, args):
#uuid = ''.join(["%02X" % c for c in reversed(args['uuid'])])
#print "Found attribute group for service: %s start=%d, end=%d" % (uuid, args['start'], args['end'])
handle = args['connection']
uuid = args['uuid'][::-1]
self.service_result.emit(handle, uuid, args['start'], args['end'])
def handle_attclient_information_found(self, sender, args):
#print args
handle = args['connection']
char = args['chrhandle']
uuid = args['uuid'][::-1]
self.info_found.emit(handle, char, uuid)
def handle_attclient_procedure_completed(self, sender, args):
handle = args['connection']
self.procedure_completed.emit(handle)
def check_activity(self):
return self.ble.check_activity(self.ser)
def connect_direct(self, target):
(target, addr_type) = target
f = ':'.join(['%02X' % b for b in target[::-1]])
print "connecting to", f
address = target
# addr_type = 0 # public
# addr_type = 1 # random
timeout = 30 # 3 sec
slave_latency = 0 # disabled
conn_interval_min = 100/1.25 # in ms
conn_interval_max = 1000/1.25 # in ms
#self.send_command(self.ble.ble_cmd_sm_set_bondable_mode(True))
self.send_command(self.ble.ble_cmd_gap_connect_direct(
address, addr_type, conn_interval_min,
conn_interval_max, timeout, slave_latency))
def disconnect(self, handle):
return self.send_command(self.ble.ble_cmd_connection_disconnect(handle))
def primary_service_discovery(self, handle):
# print "service discovery for %d ..." % handle
self.send_command(self.ble.ble_cmd_attclient_read_by_group_type(handle, 0x0001, 0xFFFF, list(reversed(self.uuid.attr_by_name['Primary'].uuid))))
def find_information(self, handle, start, end):
self.send_command(self.ble.ble_cmd_attclient_find_information(handle, start, end))
def flags_to_string(self, val):
flags = []
if val & (2**0) > 0:
flags.append('LE_lim')
if val & (2**1) > 0:
flags.append('LE_gen')
if val & (2**2) > 0:
flags.append('no_BR/EDR')
if val & (2**3) > 0:
flags.append('sim1')
if val & (2**4) > 0:
flags.append('sim2')
return '|'.join(flags)
def data_to_string(self, data):
pos = 0
dl = []
name = ''
while pos < len(data):
field_len = data[pos]
field_type = data[pos+1]
field_data = data[pos+2:(pos+2+field_len-1)]
if field_type == GAP_AD_TYPE_FLAGS:
dl.append("flags:%s" % self.flags_to_string(field_data[0]))
elif field_type == GAP_AD_TYPE_16BIT_UUIDS:
dl.append("uuids:")
num = (field_len-1)/2
for i in range(num):
uuid = field_data[i*2] + 256*field_data[i*2+1]
dl.append("%04x" % uuid)
if i < num-1:
dl.append(",")
elif field_type == GAP_AD_TYPE_LOCALNAME_COMPLETE:
name = ''.join(['%c' % b for b in field_data])
# dl.append("name:%s" % name)
elif field_type == GAP_AD_TYPE_TX_POWER:
dl.append("tx:%ddB" % (field_data[0]))
elif field_type == GAP_AD_TYPE_SLAVE_CON_INTERVAL_RANGE:
x1 = (field_data[0] + 256*field_data[1])*1.25
x2 = (field_data[2] + 256*field_data[3])*1.25
dl.append('slv_con_int_ran:%d-%dms' % (x1, x2))
elif field_type == GAP_AD_TYPE_APPEARANCE:
num = field_data[0] + 256*field_data[1]
# see https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml
dl.append("appearance:%d" % num)
elif field_type == GAP_AD_TYPE_VENDOR:
dl.append(self.uuid.vendor_to_string(field_data))
else:
dl.append("unknown_field:0x%x" % field_type)
pos += field_len + 1
return (name, ' '.join(dl))
def read_handle(self, handle, chandle):
self.send_command(self.ble.ble_cmd_attclient_read_by_handle(handle, chandle))
def read_handles(self, handle, h1, h2):
self.handles_to_read = range(h1, h2+1)
self.send_command(self.ble.ble_cmd_attclient_read_by_handle(handle, h1))
def handle_attclient_attribute_value(self, sender, args):
print "attribute_value:", args
chandle = args['atthandle']
handle = args['connection']
t = args['type']
value = args['value']
res = ''.join(["%c" % x for x in value if x != 0])
print "show string:", value, res
self.attr_value.emit(handle, chandle, t, value)
if self.handles_to_read == []: return
if chandle in self.handles_to_read:
self.handles_to_read.remove(chandle)
if self.handles_to_read == []: return
self.send_command(self.ble.ble_cmd_attclient_read_by_handle(handle, self.handles_to_read[0]))
def handle_attclient_read_multiple_response(self, sender, args):
print "read_multiple", args
def write_handle(self, handle, chandle, value):
self.send_command(self.ble.ble_cmd_attclient_write_command(handle, chandle, value))
time.sleep(0.1)
self.send_command(self.ble.ble_cmd_attclient_read_by_handle(handle, chandle))