wasptool 0.1.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- wasptool/__init__.py +10 -0
- wasptool/__main__.py +4 -0
- wasptool/ble.py +206 -0
- wasptool/cli.py +476 -0
- wasptool/console.py +76 -0
- wasptool/dfu.py +200 -0
- wasptool/releases.py +82 -0
- wasptool/repl.py +130 -0
- wasptool/watch.py +243 -0
- wasptool-0.1.0a1.dist-info/METADATA +73 -0
- wasptool-0.1.0a1.dist-info/RECORD +13 -0
- wasptool-0.1.0a1.dist-info/WHEEL +4 -0
- wasptool-0.1.0a1.dist-info/entry_points.txt +3 -0
wasptool/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LGPL-3.0-or-later
|
|
2
|
+
"""Talk to a wasp-os smart watch over Bluetooth."""
|
|
3
|
+
|
|
4
|
+
# The one version is the one in pyproject.toml; this is what is installed.
|
|
5
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = version('wasptool')
|
|
9
|
+
except PackageNotFoundError: # run from a checkout without installing
|
|
10
|
+
__version__ = 'unknown'
|
wasptool/__main__.py
ADDED
wasptool/ble.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LGPL-3.0-or-later
|
|
2
|
+
"""Find a wasp-os watch and talk to its console over Bluetooth.
|
|
3
|
+
|
|
4
|
+
The console is the Nordic UART Service (NUS): the host writes to one
|
|
5
|
+
characteristic and the watch notifies on another. Both the old wasp-os
|
|
6
|
+
firmware and upstream MicroPython send and accept at most 20 bytes at a
|
|
7
|
+
time, and the watch keeps only 128 received bytes, so anything bigger
|
|
8
|
+
than a line needs flow control on top (see :mod:`wasptool.repl`).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import logging
|
|
13
|
+
|
|
14
|
+
from bleak import BleakClient, BleakScanner
|
|
15
|
+
from bleak.exc import BleakError
|
|
16
|
+
|
|
17
|
+
NUS_SERVICE = '6e400001-b5a3-f393-e0a9-e50e24dcca9e'
|
|
18
|
+
NUS_RX = '6e400002-b5a3-f393-e0a9-e50e24dcca9e' # host to watch
|
|
19
|
+
NUS_TX = '6e400003-b5a3-f393-e0a9-e50e24dcca9e' # watch to host
|
|
20
|
+
CHUNK = 20
|
|
21
|
+
# The name upstream MicroPython gives its console. BlueZ does not always
|
|
22
|
+
# pass on the service UUIDs it advertises (it can drop them after a
|
|
23
|
+
# connection), so the name is the fallback.
|
|
24
|
+
NAMES = ('mpus',)
|
|
25
|
+
|
|
26
|
+
log = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class NotFound(Exception):
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Stream:
|
|
34
|
+
"""Bytes from the watch, buffered until a reader asks for them."""
|
|
35
|
+
|
|
36
|
+
def __init__(self):
|
|
37
|
+
self._buf = bytearray()
|
|
38
|
+
self._more = asyncio.Event()
|
|
39
|
+
self.echo = None
|
|
40
|
+
self.connected = True
|
|
41
|
+
|
|
42
|
+
def feed(self, data):
|
|
43
|
+
if self.echo:
|
|
44
|
+
self.echo(bytes(data))
|
|
45
|
+
self._buf += data
|
|
46
|
+
self._more.set()
|
|
47
|
+
|
|
48
|
+
async def _wait(self, deadline):
|
|
49
|
+
if not self.connected:
|
|
50
|
+
raise ConnectionError('The watch disconnected')
|
|
51
|
+
timeout = deadline - asyncio.get_running_loop().time()
|
|
52
|
+
if timeout <= 0:
|
|
53
|
+
raise TimeoutError()
|
|
54
|
+
self._more.clear()
|
|
55
|
+
await asyncio.wait_for(self._more.wait(), timeout)
|
|
56
|
+
|
|
57
|
+
async def read_until(self, marker, timeout=10.0):
|
|
58
|
+
"""Return everything up to marker, and drop the marker itself."""
|
|
59
|
+
deadline = asyncio.get_running_loop().time() + timeout
|
|
60
|
+
while (i := self._buf.find(marker)) < 0:
|
|
61
|
+
try:
|
|
62
|
+
await self._wait(deadline)
|
|
63
|
+
except TimeoutError:
|
|
64
|
+
raise TimeoutError(f'Timed out waiting for {marker!r}, '
|
|
65
|
+
f'got {bytes(self._buf[-80:])!r}') from None
|
|
66
|
+
data = bytes(self._buf[:i])
|
|
67
|
+
del self._buf[:i + len(marker)]
|
|
68
|
+
return data
|
|
69
|
+
|
|
70
|
+
async def read(self, n, timeout=10.0):
|
|
71
|
+
"""Return exactly n bytes."""
|
|
72
|
+
deadline = asyncio.get_running_loop().time() + timeout
|
|
73
|
+
while len(self._buf) < n:
|
|
74
|
+
await self._wait(deadline)
|
|
75
|
+
data = bytes(self._buf[:n])
|
|
76
|
+
del self._buf[:n]
|
|
77
|
+
return data
|
|
78
|
+
|
|
79
|
+
def pending(self):
|
|
80
|
+
return len(self._buf)
|
|
81
|
+
|
|
82
|
+
async def settle(self, quiet=0.3, timeout=3.0):
|
|
83
|
+
"""Wait until the watch has stopped sending.
|
|
84
|
+
|
|
85
|
+
Hanging up while the watch is still sending output hangs the
|
|
86
|
+
watch: upstream MicroPython's nRF port then waits forever for
|
|
87
|
+
notifications to complete, and the watchdog resets it into the
|
|
88
|
+
bootloader. So let it finish first.
|
|
89
|
+
"""
|
|
90
|
+
loop = asyncio.get_running_loop()
|
|
91
|
+
deadline = loop.time() + timeout
|
|
92
|
+
while self.connected and loop.time() < deadline:
|
|
93
|
+
self._more.clear()
|
|
94
|
+
try:
|
|
95
|
+
await asyncio.wait_for(self._more.wait(), quiet)
|
|
96
|
+
except TimeoutError:
|
|
97
|
+
return
|
|
98
|
+
|
|
99
|
+
def discard(self):
|
|
100
|
+
self._buf.clear()
|
|
101
|
+
|
|
102
|
+
async def write(self, data, response=True):
|
|
103
|
+
raise NotImplementedError
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _is_address(target):
|
|
107
|
+
# A MAC address (Linux, Windows) or a CoreBluetooth UUID (macOS)
|
|
108
|
+
return target.count(':') == 5 or target.count('-') == 4
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def matches(device, adv, target=None):
|
|
112
|
+
"""True if the advertisement is a wasp-os console we are looking for."""
|
|
113
|
+
if target:
|
|
114
|
+
if _is_address(target):
|
|
115
|
+
return device.address.upper() == target.upper()
|
|
116
|
+
return target in (device.name, adv.local_name)
|
|
117
|
+
return NUS_SERVICE in adv.service_uuids or adv.local_name in NAMES
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
async def find(target=None, timeout=10.0):
|
|
121
|
+
"""Scan for a watch: by name or address, or else any wasp-os watch."""
|
|
122
|
+
device = await BleakScanner.find_device_by_filter(
|
|
123
|
+
lambda d, a: matches(d, a, target), timeout=timeout)
|
|
124
|
+
if device is None:
|
|
125
|
+
what = target or 'a wasp-os watch'
|
|
126
|
+
raise NotFound(f'Cannot find {what}: is it awake, and not '
|
|
127
|
+
'connected to a phone or another computer?')
|
|
128
|
+
return device
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
async def scan(timeout=5.0):
|
|
132
|
+
"""List the watches in range, as (device, advertisement) pairs."""
|
|
133
|
+
found = await BleakScanner.discover(timeout=timeout, return_adv=True)
|
|
134
|
+
return [(d, a) for d, a in found.values() if matches(d, a)]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class Console(Stream):
|
|
138
|
+
"""A connection to the console of a watch."""
|
|
139
|
+
|
|
140
|
+
def __init__(self, device):
|
|
141
|
+
super().__init__()
|
|
142
|
+
self.device = device
|
|
143
|
+
self._client = BleakClient(device, disconnected_callback=self._lost)
|
|
144
|
+
self.connected = False
|
|
145
|
+
self.on_lost = None
|
|
146
|
+
|
|
147
|
+
def _lost(self, client):
|
|
148
|
+
self.connected = False
|
|
149
|
+
self._more.set()
|
|
150
|
+
if self.on_lost:
|
|
151
|
+
self.on_lost()
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def address(self):
|
|
155
|
+
return self.device.address
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def name(self):
|
|
159
|
+
return self.device.name
|
|
160
|
+
|
|
161
|
+
async def open(self, timeout=10.0):
|
|
162
|
+
await self._client.connect(timeout=timeout)
|
|
163
|
+
self.connected = True
|
|
164
|
+
await self._client.start_notify(NUS_TX, lambda c, d: self.feed(d))
|
|
165
|
+
|
|
166
|
+
async def close(self):
|
|
167
|
+
if self._client.is_connected:
|
|
168
|
+
await self.settle()
|
|
169
|
+
await self._client.disconnect()
|
|
170
|
+
self.connected = False
|
|
171
|
+
|
|
172
|
+
async def write(self, data, response=True):
|
|
173
|
+
"""Write in 20 byte pieces.
|
|
174
|
+
|
|
175
|
+
With response, each piece waits until the watch has it, which paces
|
|
176
|
+
the writes. Without, they go out as fast as the link allows: only use
|
|
177
|
+
that when something else stops the watch's buffer overflowing.
|
|
178
|
+
"""
|
|
179
|
+
if not self.connected:
|
|
180
|
+
raise ConnectionError('The watch disconnected')
|
|
181
|
+
for i in range(0, len(data), CHUNK):
|
|
182
|
+
await self._client.write_gatt_char(NUS_RX, data[i:i + CHUNK],
|
|
183
|
+
response=response)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
async def connect(target=None, retries=3, timeout=10.0):
|
|
187
|
+
"""Find a watch and connect to its console, retrying on failure.
|
|
188
|
+
|
|
189
|
+
The first connection attempt fails now and again, more so on radios
|
|
190
|
+
that share their antenna with Wi-Fi. Each attempt scans again, since
|
|
191
|
+
BlueZ forgets devices it has not seen for a while.
|
|
192
|
+
"""
|
|
193
|
+
for attempt in range(1, retries + 1):
|
|
194
|
+
device = await find(target, timeout)
|
|
195
|
+
console = Console(device)
|
|
196
|
+
try:
|
|
197
|
+
log.debug('Connecting to %s (%s)', device.name, device.address)
|
|
198
|
+
await console.open(timeout)
|
|
199
|
+
return console
|
|
200
|
+
except (BleakError, TimeoutError, OSError) as e:
|
|
201
|
+
await console.close()
|
|
202
|
+
if attempt == retries:
|
|
203
|
+
raise ConnectionError(f'Cannot connect to {device.address} '
|
|
204
|
+
f'after {retries} attempts: {e}') from e
|
|
205
|
+
log.warning('Connecting failed (%s), retrying', e or type(e).__name__)
|
|
206
|
+
await asyncio.sleep(1)
|
wasptool/cli.py
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LGPL-3.0-or-later
|
|
2
|
+
"""The wasptool command."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import io
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
|
|
14
|
+
from bleak.exc import BleakError
|
|
15
|
+
|
|
16
|
+
from wasptool import __version__, ble, dfu, releases, watch
|
|
17
|
+
from wasptool.repl import Repl, ReplError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def progress_bar(label):
|
|
21
|
+
"""A progress callback that draws a bar on a terminal, or nothing."""
|
|
22
|
+
if not sys.stderr.isatty():
|
|
23
|
+
return None
|
|
24
|
+
print(label, file=sys.stderr)
|
|
25
|
+
|
|
26
|
+
def draw(done, total):
|
|
27
|
+
pct = 100 * done // total if total else 100
|
|
28
|
+
bar = '#' * (pct // 2) + '.' * (50 - pct // 2)
|
|
29
|
+
if total < 1024:
|
|
30
|
+
size = f'{done} of {total} bytes'
|
|
31
|
+
else:
|
|
32
|
+
size = f'{done // 1024} of {total // 1024} KB'
|
|
33
|
+
print(f'\r[{bar}] {pct:3d}% ({size})',
|
|
34
|
+
end='\n' if done >= total else '', file=sys.stderr, flush=True)
|
|
35
|
+
return draw
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@contextlib.asynccontextmanager
|
|
39
|
+
async def session(args, resume=True):
|
|
40
|
+
"""Connect, enter the raw REPL, and set the watch running afterwards."""
|
|
41
|
+
console = await ble.connect(args.device, args.retries, args.timeout)
|
|
42
|
+
if args.verbose:
|
|
43
|
+
console.echo = lambda d: print(f'<<< {d!r}', file=sys.stderr)
|
|
44
|
+
try:
|
|
45
|
+
repl = Repl(console)
|
|
46
|
+
await repl.enter()
|
|
47
|
+
yield repl
|
|
48
|
+
if resume:
|
|
49
|
+
await watch.resume(repl)
|
|
50
|
+
finally:
|
|
51
|
+
await console.close()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _duration(secs):
|
|
55
|
+
mins, secs = divmod(int(secs), 60)
|
|
56
|
+
hours, mins = divmod(mins, 60)
|
|
57
|
+
days, hours = divmod(hours, 24)
|
|
58
|
+
return (f'{days}d ' if days else '') + f'{hours:02d}:{mins:02d}:{secs:02d}'
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def cmd_scan(args):
|
|
62
|
+
found = await ble.scan(args.timeout)
|
|
63
|
+
for device, adv in sorted(found, key=lambda f: -f[1].rssi):
|
|
64
|
+
print(f'{device.address} {adv.rssi:4d} dBm {device.name or ""}')
|
|
65
|
+
if not found:
|
|
66
|
+
print('No wasp-os watches found', file=sys.stderr)
|
|
67
|
+
return 1
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def cmd_info(args):
|
|
71
|
+
async with session(args) as repl:
|
|
72
|
+
facts = await watch.info(repl)
|
|
73
|
+
facts['address'] = repl.stream.address
|
|
74
|
+
facts['name'] = repl.stream.name
|
|
75
|
+
if args.json:
|
|
76
|
+
print(json.dumps(facts, indent=2))
|
|
77
|
+
return
|
|
78
|
+
|
|
79
|
+
battery = f"{facts['battery']}% ({facts['voltage_mv'] / 1000:.2f} V)"
|
|
80
|
+
if facts['charging']:
|
|
81
|
+
battery += ', charging'
|
|
82
|
+
flash = facts['flash_free']
|
|
83
|
+
rows = (
|
|
84
|
+
('Version', facts['version'] or 'unknown (too old to say)'),
|
|
85
|
+
('Board', facts['board']),
|
|
86
|
+
('MicroPython', facts['micropython']),
|
|
87
|
+
('Bootloader', facts.get('bootloader') or '-'),
|
|
88
|
+
('Address', f"{facts['address']} ({facts['name']})"),
|
|
89
|
+
('Battery', battery),
|
|
90
|
+
('Uptime', _duration(facts['uptime'])),
|
|
91
|
+
('Time', facts['time'].replace('T', ' ')),
|
|
92
|
+
('RAM free', f"{facts['ram_free'] // 1024} KB"),
|
|
93
|
+
('Flash free', '-' if flash is None else f'{flash // 1024} KB'),
|
|
94
|
+
)
|
|
95
|
+
hang = facts.get('last_hang')
|
|
96
|
+
if hang:
|
|
97
|
+
pc, lr, xpsr, ms = hang
|
|
98
|
+
if xpsr == 0:
|
|
99
|
+
where = 'a fatal error'
|
|
100
|
+
elif xpsr & 0x1ff == 0:
|
|
101
|
+
where = 'not in an interrupt'
|
|
102
|
+
else:
|
|
103
|
+
where = f'in exception {xpsr & 0x1ff}'
|
|
104
|
+
rows += (('Last hang', f'pc {pc:#x}, lr {lr:#x}, {where}, '
|
|
105
|
+
f'{ms} ms after the last alive()'),)
|
|
106
|
+
for label, value in rows:
|
|
107
|
+
print(f'{label:<12} {value}')
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
async def cmd_rtc(args):
|
|
111
|
+
async with session(args) as repl:
|
|
112
|
+
if args.action == 'set':
|
|
113
|
+
await watch.set_time(repl)
|
|
114
|
+
drift = await watch.time_drift(repl)
|
|
115
|
+
if drift == 0:
|
|
116
|
+
print('The watch is on time')
|
|
117
|
+
else:
|
|
118
|
+
side = 'ahead' if drift > 0 else 'behind'
|
|
119
|
+
print(f'The watch is {abs(drift)} s {side}'
|
|
120
|
+
+ ('' if args.action == 'set' else ': use "wasptool rtc set"'))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
async def cmd_notify(args):
|
|
124
|
+
async with session(args) as repl:
|
|
125
|
+
await watch.notify(repl, args.title, args.body, args.id)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
DAYS = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
|
|
129
|
+
REPEATS = {'once': 0, 'daily': 0x7f, 'weekdays': 0x1f, 'weekends': 0x60}
|
|
130
|
+
ALARM_ON = 0x80
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def parse_time(text):
|
|
134
|
+
"""'7:30' as (7, 30)."""
|
|
135
|
+
try:
|
|
136
|
+
hour, minute = (int(t) for t in text.split(':'))
|
|
137
|
+
except ValueError:
|
|
138
|
+
raise argparse.ArgumentTypeError(f'{text!r} is not a time like 7:30')
|
|
139
|
+
if not (0 <= hour < 24 and 0 <= minute < 60):
|
|
140
|
+
raise argparse.ArgumentTypeError(f'{text!r} is not a time of day')
|
|
141
|
+
return hour, minute
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def parse_days(text):
|
|
145
|
+
"""'weekdays', or a list like 'mon,wed', as a mask of days."""
|
|
146
|
+
if text.lower() in REPEATS:
|
|
147
|
+
return REPEATS[text.lower()]
|
|
148
|
+
mask = 0
|
|
149
|
+
for day in text.lower().split(','):
|
|
150
|
+
found = [i for i, d in enumerate(DAYS)
|
|
151
|
+
if len(day) >= 2 and d.lower().startswith(day)]
|
|
152
|
+
if len(found) != 1:
|
|
153
|
+
raise argparse.ArgumentTypeError(
|
|
154
|
+
f'{day!r} is not a day: use for example mon,wed, '
|
|
155
|
+
'or one of ' + ', '.join(REPEATS))
|
|
156
|
+
mask |= 1 << found[0]
|
|
157
|
+
return mask
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def format_days(mask):
|
|
161
|
+
mask &= 0x7f
|
|
162
|
+
for name, m in REPEATS.items():
|
|
163
|
+
if mask == m:
|
|
164
|
+
return name
|
|
165
|
+
return ','.join(d for i, d in enumerate(DAYS) if mask & (1 << i))
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def print_alarms(alarms):
|
|
169
|
+
if not alarms:
|
|
170
|
+
print('No alarms')
|
|
171
|
+
for hour, minute, days in alarms:
|
|
172
|
+
state = 'on' if days & ALARM_ON else 'off'
|
|
173
|
+
print(f'{hour:2d}:{minute:02d} {state:<3} {format_days(days)}')
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
async def cmd_alarm(args):
|
|
177
|
+
async with session(args) as repl:
|
|
178
|
+
alarms = await watch.alarms(repl)
|
|
179
|
+
if args.action == 'set':
|
|
180
|
+
days = args.days | (0 if args.off else ALARM_ON)
|
|
181
|
+
same = [i for i, a in enumerate(alarms) if a[:2] == args.time]
|
|
182
|
+
if same:
|
|
183
|
+
alarms[same[0]] = (*args.time, days)
|
|
184
|
+
elif len(alarms) >= 4:
|
|
185
|
+
print('The watch has room for four alarms: '
|
|
186
|
+
'unset one first', file=sys.stderr)
|
|
187
|
+
return 1
|
|
188
|
+
else:
|
|
189
|
+
alarms.append((*args.time, days))
|
|
190
|
+
elif args.action == 'unset':
|
|
191
|
+
if args.time == 'all':
|
|
192
|
+
kept = []
|
|
193
|
+
else:
|
|
194
|
+
time = parse_time(args.time)
|
|
195
|
+
kept = [a for a in alarms if a[:2] != time]
|
|
196
|
+
if len(kept) == len(alarms):
|
|
197
|
+
print(f'There is no alarm at {args.time}', file=sys.stderr)
|
|
198
|
+
return 1
|
|
199
|
+
alarms = kept
|
|
200
|
+
if args.action != 'list':
|
|
201
|
+
await watch.set_alarms(repl, alarms)
|
|
202
|
+
print_alarms(alarms)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _face_key(name):
|
|
206
|
+
return name.lower().replace('_', '').replace('-', '').replace(' ', '')
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
async def cmd_face(args):
|
|
210
|
+
async with session(args) as repl:
|
|
211
|
+
faces, current = await watch.faces(repl)
|
|
212
|
+
if args.name:
|
|
213
|
+
found = [f for f in faces if _face_key(f) == _face_key(args.name)]
|
|
214
|
+
if not found:
|
|
215
|
+
print(f'There is no watch face {args.name!r}: choose from '
|
|
216
|
+
+ ', '.join(faces), file=sys.stderr)
|
|
217
|
+
return 1
|
|
218
|
+
await watch.set_face(repl, found[0])
|
|
219
|
+
current = found[0]
|
|
220
|
+
for face in faces:
|
|
221
|
+
print(('* ' if face == current else ' ') + face)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
async def _run(args, chunks):
|
|
225
|
+
async with session(args) as repl:
|
|
226
|
+
for chunk in chunks:
|
|
227
|
+
try:
|
|
228
|
+
out = await repl.exec(chunk, timeout=args.exec_timeout)
|
|
229
|
+
except ReplError as e:
|
|
230
|
+
print(e.traceback, end='', file=sys.stderr)
|
|
231
|
+
return 1
|
|
232
|
+
print(out, end='', flush=True)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
async def cmd_eval(args):
|
|
236
|
+
return await _run(args, [args.code])
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
async def cmd_exec(args):
|
|
240
|
+
with open(args.file) as f:
|
|
241
|
+
return await _run(args, watch.chunks(f.read()))
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
async def cmd_push(args):
|
|
245
|
+
with open(args.local, 'rb') as f:
|
|
246
|
+
data = f.read()
|
|
247
|
+
remote = args.remote or os.path.basename(args.local)
|
|
248
|
+
async with session(args) as repl:
|
|
249
|
+
await watch.push(repl, data, remote, progress_bar(f'{args.local} -> {remote}'))
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
async def cmd_pull(args):
|
|
253
|
+
local = args.local or os.path.basename(args.remote)
|
|
254
|
+
if os.path.exists(local) and not args.force:
|
|
255
|
+
print(f'{local} exists: use --force to overwrite it', file=sys.stderr)
|
|
256
|
+
return 1
|
|
257
|
+
async with session(args) as repl:
|
|
258
|
+
data = await watch.pull(repl, args.remote, progress_bar(f'{args.remote} -> {local}'))
|
|
259
|
+
with open(local, 'wb') as f:
|
|
260
|
+
f.write(data)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
async def cmd_console(args):
|
|
264
|
+
from wasptool.console import interact
|
|
265
|
+
console = await ble.connect(args.device, args.retries, args.timeout)
|
|
266
|
+
print(f'Connected to {console.name} ({console.address}). '
|
|
267
|
+
'Exit with Ctrl-X.', file=sys.stderr)
|
|
268
|
+
try:
|
|
269
|
+
await interact(console)
|
|
270
|
+
finally:
|
|
271
|
+
await console.close()
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
async def cmd_reset(args):
|
|
275
|
+
async with session(args, resume=False) as repl:
|
|
276
|
+
await watch.reset(repl, args.bootloader)
|
|
277
|
+
await asyncio.sleep(0.5)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
async def cmd_ota(args):
|
|
281
|
+
await _ota(args, args.file)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
async def _ota(args, package):
|
|
285
|
+
"""Update the firmware from a DFU zip (a path, or a file object)."""
|
|
286
|
+
image, init = dfu.read_package(package)
|
|
287
|
+
address = None
|
|
288
|
+
try:
|
|
289
|
+
async with session(args, resume=False) as repl:
|
|
290
|
+
address = repl.stream.address
|
|
291
|
+
print(f'Rebooting {repl.stream.name} ({address}) into the bootloader',
|
|
292
|
+
file=sys.stderr)
|
|
293
|
+
await watch.reset(repl, bootloader=True)
|
|
294
|
+
await asyncio.sleep(0.5)
|
|
295
|
+
except ble.NotFound:
|
|
296
|
+
# Perhaps it is in the bootloader already
|
|
297
|
+
print('No watch running wasp-os found, '
|
|
298
|
+
'looking for one in its bootloader', file=sys.stderr)
|
|
299
|
+
if args.device and args.device.count(':') == 5:
|
|
300
|
+
address = args.device
|
|
301
|
+
await asyncio.sleep(2)
|
|
302
|
+
|
|
303
|
+
updater = dfu.Updater(address, image, init, progress_bar('Updating'))
|
|
304
|
+
start = time.monotonic()
|
|
305
|
+
await updater.connect(args.retries, args.timeout)
|
|
306
|
+
try:
|
|
307
|
+
await updater.run()
|
|
308
|
+
finally:
|
|
309
|
+
await updater.close()
|
|
310
|
+
secs = int(time.monotonic() - start)
|
|
311
|
+
print(f'Updated in {secs // 60} min {secs % 60} s: the watch is restarting',
|
|
312
|
+
file=sys.stderr)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _confirm(question):
|
|
316
|
+
if not sys.stdin.isatty():
|
|
317
|
+
raise watch.NotAvailable('not updating without asking: '
|
|
318
|
+
'pass --yes to update anyway')
|
|
319
|
+
return input(question + ' [y/N] ').strip().lower() in ('y', 'yes')
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
async def cmd_update(args):
|
|
323
|
+
manifest = releases.fetch(args.url)
|
|
324
|
+
async with session(args) as repl:
|
|
325
|
+
current = await watch.version(repl)
|
|
326
|
+
name, address = repl.stream.name, repl.stream.address
|
|
327
|
+
target = releases.latest(manifest)
|
|
328
|
+
new = releases.newer(manifest, current)
|
|
329
|
+
print(f'{name} runs {current or "a version too old to say"}; '
|
|
330
|
+
f'the latest build is {target["version"]} ({target["date"]})')
|
|
331
|
+
if not args.force:
|
|
332
|
+
if current == target['version']:
|
|
333
|
+
print('The watch is up to date')
|
|
334
|
+
return
|
|
335
|
+
if not new:
|
|
336
|
+
print('The watch runs a newer build: nothing to update')
|
|
337
|
+
return
|
|
338
|
+
for r in new:
|
|
339
|
+
print(f'\n{r["version"]} ({r["date"]})')
|
|
340
|
+
for line in (r.get('notes') or 'No notes.').splitlines():
|
|
341
|
+
print(' ' + line)
|
|
342
|
+
if args.check:
|
|
343
|
+
return
|
|
344
|
+
print()
|
|
345
|
+
if not args.yes and not _confirm(f'Update to {target["version"]}?'):
|
|
346
|
+
return 1
|
|
347
|
+
|
|
348
|
+
data = releases.download(manifest, target)
|
|
349
|
+
print(f'Downloaded {releases.FIRMWARE} ({len(data) // 1024} KB), '
|
|
350
|
+
'its sha256 matches', file=sys.stderr)
|
|
351
|
+
# The watch we just talked to, without scanning again
|
|
352
|
+
args.device = args.device or address
|
|
353
|
+
await _ota(args, io.BytesIO(data))
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def parser():
|
|
357
|
+
p = argparse.ArgumentParser(
|
|
358
|
+
prog='wasptool',
|
|
359
|
+
description='Talk to a wasp-os watch over Bluetooth.')
|
|
360
|
+
p.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
|
|
361
|
+
|
|
362
|
+
def options(p, default):
|
|
363
|
+
"""The options that go before or after the command."""
|
|
364
|
+
p.add_argument('-d', '--device', metavar='NAME|ADDRESS',
|
|
365
|
+
default=default(None),
|
|
366
|
+
help='the watch to use (default: the first one found)')
|
|
367
|
+
p.add_argument('--retries', type=int, default=default(3),
|
|
368
|
+
help='connection attempts before giving up (default: 3)')
|
|
369
|
+
p.add_argument('--timeout', type=float, default=default(10.0),
|
|
370
|
+
help='seconds to scan, or to connect (default: 10)')
|
|
371
|
+
p.add_argument('-v', '--verbose', action='store_true',
|
|
372
|
+
default=default(False),
|
|
373
|
+
help='show what goes on, including the console traffic')
|
|
374
|
+
|
|
375
|
+
options(p, lambda d: d)
|
|
376
|
+
# After the command they must not reset what was given before it
|
|
377
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
378
|
+
options(common, lambda d: argparse.SUPPRESS)
|
|
379
|
+
sub = p.add_subparsers(dest='command', required=True, metavar='COMMAND')
|
|
380
|
+
|
|
381
|
+
def command(name, func, help):
|
|
382
|
+
c = sub.add_parser(name, help=help, description=help, parents=[common])
|
|
383
|
+
c.set_defaults(func=func)
|
|
384
|
+
return c
|
|
385
|
+
|
|
386
|
+
command('scan', cmd_scan, 'list the wasp-os watches in range')
|
|
387
|
+
|
|
388
|
+
c = command('info', cmd_info, 'show the version, battery, memory and more')
|
|
389
|
+
c.add_argument('--json', action='store_true', help='print it as JSON')
|
|
390
|
+
|
|
391
|
+
c = command('rtc', cmd_rtc, "check the watch's clock, or set it")
|
|
392
|
+
c.add_argument('action', nargs='?', choices=('check', 'set'), default='check')
|
|
393
|
+
|
|
394
|
+
c = command('alarm', cmd_alarm, 'show, set or unset alarms')
|
|
395
|
+
alarm = c.add_subparsers(dest='action', metavar='ACTION')
|
|
396
|
+
c.set_defaults(action='list')
|
|
397
|
+
alarm.add_parser('list', help='show the alarms (the default)', parents=[common])
|
|
398
|
+
a = alarm.add_parser('set', help='add an alarm, or change the one at that time',
|
|
399
|
+
description='Add an alarm, or change the one at that time.',
|
|
400
|
+
parents=[common])
|
|
401
|
+
a.add_argument('time', type=parse_time, help='for example 7:30')
|
|
402
|
+
a.add_argument('--days', type=parse_days, default=0,
|
|
403
|
+
help='when to repeat: ' + ', '.join(REPEATS)
|
|
404
|
+
+ ', or days like mon,wed (default: once)')
|
|
405
|
+
a.add_argument('--off', action='store_true',
|
|
406
|
+
help='keep it, but switched off')
|
|
407
|
+
a = alarm.add_parser('unset', help='remove the alarm at that time',
|
|
408
|
+
description='Remove the alarm at that time.',
|
|
409
|
+
parents=[common])
|
|
410
|
+
a.add_argument('time', help="for example 7:30, or 'all'")
|
|
411
|
+
|
|
412
|
+
c = command('face', cmd_face, 'show the watch faces, or choose one')
|
|
413
|
+
c.add_argument('name', nargs='?', help='the watch face to use')
|
|
414
|
+
|
|
415
|
+
c = command('notify', cmd_notify, 'show a notification on the watch')
|
|
416
|
+
c.add_argument('title')
|
|
417
|
+
c.add_argument('body')
|
|
418
|
+
c.add_argument('--id', type=int, default=1,
|
|
419
|
+
help='a new notification with the same id replaces it')
|
|
420
|
+
|
|
421
|
+
for name, func, help, arg in (
|
|
422
|
+
('eval', cmd_eval, 'run Python code on the watch', 'code'),
|
|
423
|
+
('exec', cmd_exec, 'run a Python file on the watch', 'file')):
|
|
424
|
+
c = command(name, func, help)
|
|
425
|
+
c.add_argument(arg)
|
|
426
|
+
c.add_argument('--exec-timeout', type=float, default=30.0, metavar='SECS',
|
|
427
|
+
help='seconds to wait for it to finish (default: 30)')
|
|
428
|
+
|
|
429
|
+
c = command('push', cmd_push, 'copy a file to the watch')
|
|
430
|
+
c.add_argument('local')
|
|
431
|
+
c.add_argument('remote', nargs='?', help='default: the same name, in /flash')
|
|
432
|
+
|
|
433
|
+
c = command('pull', cmd_pull, 'copy a file from the watch')
|
|
434
|
+
c.add_argument('remote')
|
|
435
|
+
c.add_argument('local', nargs='?', help='default: the same name, here')
|
|
436
|
+
c.add_argument('-f', '--force', action='store_true',
|
|
437
|
+
help='overwrite the local file')
|
|
438
|
+
|
|
439
|
+
command('console', cmd_console, 'open a MicroPython prompt on the watch')
|
|
440
|
+
|
|
441
|
+
c = command('reset', cmd_reset, 'reboot the watch')
|
|
442
|
+
c.add_argument('--bootloader', action='store_true',
|
|
443
|
+
help='into the bootloader, ready for an update')
|
|
444
|
+
|
|
445
|
+
c = command('ota', cmd_ota, 'update the firmware (micropython.zip)')
|
|
446
|
+
c.add_argument('file')
|
|
447
|
+
|
|
448
|
+
c = command('update', cmd_update,
|
|
449
|
+
'update the firmware to the latest published build')
|
|
450
|
+
c.add_argument('--check', action='store_true',
|
|
451
|
+
help="only show what's new, don't update")
|
|
452
|
+
c.add_argument('-y', '--yes', action='store_true',
|
|
453
|
+
help="don't ask before updating")
|
|
454
|
+
c.add_argument('--force', action='store_true',
|
|
455
|
+
help='install the latest build even if it is not newer')
|
|
456
|
+
c.add_argument('--url', default=releases.URL,
|
|
457
|
+
help=f'where the builds are listed (default: {releases.URL})')
|
|
458
|
+
return p
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def main(argv=None):
|
|
462
|
+
args = parser().parse_args(argv)
|
|
463
|
+
logging.basicConfig(format='wasptool: %(message)s',
|
|
464
|
+
level=logging.DEBUG if args.verbose else logging.INFO)
|
|
465
|
+
if not args.verbose:
|
|
466
|
+
# bleak logs its own retries and backend details at INFO
|
|
467
|
+
logging.getLogger('bleak').setLevel(logging.WARNING)
|
|
468
|
+
try:
|
|
469
|
+
sys.exit(asyncio.run(args.func(args)) or 0)
|
|
470
|
+
except KeyboardInterrupt:
|
|
471
|
+
sys.exit(130)
|
|
472
|
+
except (ble.NotFound, ConnectionError, TimeoutError, IOError,
|
|
473
|
+
BleakError, dfu.DfuError, ReplError, watch.NotAvailable,
|
|
474
|
+
releases.ReleaseError) as e:
|
|
475
|
+
print(f'wasptool: {e}', file=sys.stderr)
|
|
476
|
+
sys.exit(1)
|