-
Notifications
You must be signed in to change notification settings - Fork 1
/
blueterm.py
executable file
·148 lines (120 loc) · 4.76 KB
/
blueterm.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
#!/usr/bin/env python3
import cmd
import argparse
from bluepy.btle import Scanner, Peripheral, ADDR_TYPE_PUBLIC, UUID, DefaultDelegate
# global configuration
cfg = dict()
cfg['intro'] = "Welcome to blueterm - Type 'help' or '?'' to list commands.\n"
cfg['prompt'] = "(blueterm) "
cfg['uuid_riot_shell'] = UUID("00002a00-0000-1000-8000-00805f9b34fb")
# global state
# class ScanDelegate(DefaultDelegate):
# def __init__(self):
# DefaultDelegate.__init__(self)
# def handleDiscovery(self, dev, isNewDev, isNewData):
# if isNewDev:
# print("Discovered device", dev.addr)
# elif isNewData:
# print("Received new data from", dev.addr)
# scanner = Scanner().withDelegate(ScanDelegate())
# devices = scanner.scan(2.0)
# print("num of", len(devices))
# for dev in devices:
# print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
# print(dev.getScanData())
# for (adtype, desc, value) in dev.getScanData():
# print(" %s = %s" % (desc, value))
class ShellEventHandler(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
def handleNotification(self, handle, data):
print("Got notification: {}, {}".format(handle, data))
def handleDiscovery(scanEntry, isNewDev, isNewData):
print("new discovery: {}, {}".format(isNewDev, isNewData))
class Blueterm(cmd.Cmd):
intro = cfg['intro']
prompt = cfg['prompt']
def __init__(self, device_index, scan_timeout):
cmd.Cmd.__init__(self)
self.device_index = device_index
self.scan_timeout = scan_timeout
self.ble_devs = set()
self.ble_gatt = dict()
# setup Bluetooth
self.scanner = Scanner(device_index)
self.periph = Peripheral(None, ADDR_TYPE_PUBLIC, device_index)
self.periph.setDelegate(ShellEventHandler())
# Pla
def precmd(self, line):
return line
def do_scan(self, line):
"""Scan for available BLE RIOT shells.
Running this command will reset the cached list of available devices.
usage: scan <scan timeout in sec>
"""
args = line.strip().split(' ')
if len(args[0]) > 0:
try:
to = float(args[0])
except:
print("error: unable to parse timeout (must be a number)")
return
else:
to = self.scan_timeout
print("Scanning now (blocking for {} seconds)...".format(to))
try:
self.ble_devs = list(self.scanner.scan(to))
print("Scan complete:")
self.do_list("")
except:
print("error: failure while scanning")
return
def do_list(self, line):
"""List all available BLE devices offering a RIOT shell
"""
if len(self.ble_devs) == 0:
print("No BLE devices available")
return
for i, dev in enumerate(self.ble_devs):
print("[{:2}] {}".format(i, dev.addr), end='')
for (adtype, desc, value) in dev.getScanData():
if adtype == 9:
print(" (Name: '{}'')".format(value), end='')
print()
def do_connect(self, line):
args = line.strip().split(' ')
if len(args[0]) == 0:
print("usage: connect <device index>")
return
try:
dev = self.ble_devs[int(args[0])]
except:
print("error: unable to find given device index")
return
try:
self.periph.connect(dev.addr, dev.addrType)
services = self.periph.getServices()
for i, service in enumerate(services):
print("Service {:2} UUID: {} ({})".format(i, service.uuid,
service.uuid.getCommonName()))
chars = service.getCharacteristics()
type(chars)
for i, char in enumerate(chars):
print(" Char {:2} UUID: {} ({})".format(i, char.uuid,
char.uuid.getCommonName()))
# if char.supportsRead():
# tmp = char.read()
# print("Data: ", str(tmp))
except:
print("error: while conneting something was bad")
return
if __name__ == "__main__":
p = argparse.ArgumentParser(description="Blueterm - Access the RIOT "
"shell over BLE")
p.add_argument("-d", "--device_index", type=int,
help="Bluetooth device, default: 0:=/dev/hci0", default=0)
p.add_argument("-s", "--scan_timeout", type=float,
help="Number seconds to scan for BLE devices", default=3.0)
args = p.parse_args()
prompt = Blueterm(args.device_index, args.scan_timeout)
prompt.cmdloop()