-
Notifications
You must be signed in to change notification settings - Fork 0
/
powerpod-command
executable file
·419 lines (384 loc) · 15.8 KB
/
powerpod-command
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#!/usr/bin/python
import argparse
import datetime
import functools
import logging
import os
import os.path
import re
import simplejson
import sys
import time
import traceback
import urllib2
import powerpod
LOGGER = logging.getLogger(__name__)
CMD_SPLIT = re.compile(r'(?:[^\\\s]|\\.)+')
WHITESPACE_QUOTE = functools.partial(re.compile(r'(\\s)').sub, r'\\\1')
ACTIONS = {}
def add_action(cls):
ACTIONS[cls.PARSER.prog] = cls
class Action(object):
PARSER = NotImplemented
def __init__(self, extra):
self.extra = extra
@add_action
class GetAllRidesAction(Action):
PARSER = argparse.ArgumentParser('get_all_rides', description='Fetch all rides into ride_directory')
PARSER.add_argument('--no-clobber', dest='existing', action='store_const', const='no_clobber')
PARSER.add_argument('--force', dest='existing', action='store_const', const='force')
PARSER.add_argument(
'--directory',
dest='directory',
default='./rides',
)
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetFileListCommand())
LOGGER.debug(repr(response))
extra = []
if self.extra.existing == 'force':
extra.append('--force')
elif self.extra.existing == 'no_clobber':
extra.append('--no-clobber')
for i, header in enumerate(response.records):
filepath = os.path.join(self.extra.directory, header.to_filename())
args.actions.append(make_action("get_ride {} {} {}".format(i, WHITESPACE_QUOTE(filepath), ' '.join(extra))))
@add_action
class ListRidesAction(Action):
PARSER = argparse.ArgumentParser('list_rides', description='Print information about all rides on the device to stdout')
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetFileListCommand())
LOGGER.debug(repr(response))
for i, header in enumerate(response.records):
sys.stdout.write("{} {}\n".format(i, header.to_filename()))
@add_action
class GetRideAction(Action):
PARSER = argparse.ArgumentParser('get_ride')
PARSER.add_argument('index', type=int)
PARSER.add_argument('filename')
PARSER.add_argument('--no-clobber', dest='existing', action='store_const', const='no_clobber')
PARSER.add_argument('--force', dest='existing', action='store_const', const='force')
def run(self, protocol, args):
time.sleep(1)
response = protocol.do_command(powerpod.GetFileCommand(self.extra.index))
filename = self.extra.filename
if filename is sys.stdout:
out = sys.stdout
else:
if os.path.exists(filename):
if self.extra.existing == 'force':
pass
else:
if self.extra.existing is None:
LOGGER.warning('Will not overwrite {!r}; use --force or --no-clobber'.format(filename))
return
out = open(filename, 'w')
LOGGER.info("index=%s header=%s filename=%s", self.extra.index, response.ride_data.get_header(), filename)
out.write(response.ride_data.to_binary())
@add_action
class EraseAllCommand(Action):
PARSER = argparse.ArgumentParser('erase_all')
def run(self, protocol, args):
protocol.do_command(powerpod.EraseAllCommand())
rides = protocol.do_command(powerpod.GetFileListCommand())
assert not rides.size, rides
@add_action
class GetOdometerCommand(Action):
PARSER = argparse.ArgumentParser('get_odometer')
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetOdometerCommand())
sys.stdout.write('{} km\n'.format(response.distance_km))
@add_action
class SetOdometerCommand(Action):
PARSER = argparse.ArgumentParser('set_odometer')
PARSER.add_argument('distance', type=float, help='km rounded to 1 decimal place')
def run(self, protocol, args):
distance = round(self.extra.distance, 1)
if distance != self.extra.distance:
LOGGER.warning('rounding to one decimal place')
protocol.do_command(powerpod.SetOdometerCommand(distance))
response = protocol.do_command(powerpod.GetOdometerCommand())
assert response.distance_km == distance, response.distance_km
@add_action
class GetUnitsCommand(Action):
PARSER = argparse.ArgumentParser('get_units')
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetOdometerCommand())
sys.stdout.write("{}\n".format(powerpod.SetUnitsCommand.LOOKUP[response.units_type]))
@add_action
class SetUnitsCommand(Action):
PARSER = argparse.ArgumentParser('set_units')
PARSER.add_argument('units_type', type=powerpod.SetUnitsCommand.LOOKUP.index)
def run(self, protocol, args):
protocol.do_command(powerpod.SetUnitsCommand(self.extra.units_type))
response = protocol.do_command(powerpod.GetOdometerCommand())
assert response.units_type == self.extra.units_type, response.units_type
@add_action
class GetFirmwareVersionCommand(Action):
PARSER = argparse.ArgumentParser('get_firmware_version')
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetFirmwareVersionCommand())
sys.stdout.write('{} {}\n'.format(response.version_encoded, response.version))
@add_action
class GetFirmwareVersionCommand(Action):
PARSER = argparse.ArgumentParser('check_firmware_version', description="Exits with status 1 if not latest")
PARSER.add_argument('type', choices=('PwrPod', 'iBike'))
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetFirmwareVersionCommand())
# SUPER PORCELAIN!
# I think I'm actually meant to read FWstatus.txt, but that is huge and
# clearly includes much more than the latest version!
resp = urllib2.urlopen('http://ibikesports.com/iBike_update/')
resp_content = resp.read()
versions = re.compile(r'<a href="(PwrPod|iBike)(\d+)\.iBFW3.txt">').findall(resp_content)
best_version = max(int(version) for type, version in versions if type == self.extra.type)
if best_version != response.version_encoded:
sys.stdout.write('{!r} is not latest; {!r} is available\n'.format(response.version_encoded, best_version))
sys.exit(1)
@add_action
class SetTrainerWeightsCommand(Action):
PARSER = argparse.ArgumentParser('set_trainer_weights', description="""All coefficients are in terms of a polynomial in mph, outputting Watts.""")
PARSER.add_argument('constant', type=float)
PARSER.add_argument('linear', type=float)
PARSER.add_argument('quadratic', type=float)
PARSER.add_argument('cubic', type=float)
def run(self, protocol, args):
command = powerpod.SetTrainerWeightsCommand(
self.extra.constant,
self.extra.linear,
self.extra.quadratic,
self.extra.cubic,
)
response = protocol.do_command(command)
def interval_format(string):
power_watts, work_secs, rest_secs = map(int, string.split(':'))
return powerpod.NewtonInterval(power_watts, work_secs, rest_secs)
@add_action
class SetIntervalsCommand(Action):
PARSER = argparse.ArgumentParser('set_intervals')
PARSER.add_argument('intervals', type=interval_format, nargs='*')
def run(self, protocol, args):
protocol.do_command(powerpod.SetIntervalsCommand(
len(self.extra.intervals),
len(self.extra.intervals),
self.extra.intervals,
))
@add_action
class GetSerialNumberCommand(Action):
PARSER = argparse.ArgumentParser('get_serial_number')
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetSerialNumberCommand())
sys.stdout.write('{}\n'.format(response.as_hex))
@add_action
class GetSpaceUsageCommand(Action):
PARSER = argparse.ArgumentParser('get_space_used')
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetSpaceUsageCommand())
sys.stdout.write('{} %\n'.format(response.used_percentage))
TIME_FORMAT = lambda string: datetime.datetime.strptime(string, '%Y-%m-%dT%H:%M:%S')
@add_action
class SetTimeCommand(Action):
PARSER = argparse.ArgumentParser('set_time')
PARSER.add_argument('--time', type=TIME_FORMAT, help='eg. 2016-01-31T22:01:12; default=local time', required=False)
def run(self, protocol, args):
if self.extra.time is None:
time = datetime.datetime.now()
else:
time = self.extra.time
protocol.do_command(powerpod.SetTimeCommand(0, powerpod.NewtonTime.from_datetime(time)))
@add_action
class GetDefaultProfileCommand(Action):
PARSER = argparse.ArgumentParser('get_default_profile')
PARSER.add_argument('number', choices=(0, 1, 2, 3), type=int)
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetProfileNumberCommand())
sys.stdout.write("{}\n".format(response.number))
@add_action
class SetDefaultProfileCommand(Action):
PARSER = argparse.ArgumentParser('set_default_profile')
PARSER.add_argument('number', choices=(0, 1, 2, 3), type=int)
def run(self, protocol, args):
protocol.do_command(powerpod.SetProfileNumberCommand(self.extra.number))
response = protocol.do_command(powerpod.GetProfileNumberCommand())
assert self.extra.number == response.number, response.number
@add_action
class DumpProfilesCommand(Action):
""" Since the profile editing commands are a different shape to profile getting, there seems little point in a raw dump. """
PARSER = argparse.ArgumentParser('dump_profiles')
PARSER.add_argument('--number', choices=(0, 1, 2, 3), type=int)
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetProfileDataCommand())
if self.extra.number is not None:
data = simplejson.dumps(response.records[self.extra.number]._asdict())
else:
data = simplejson.dumps([profile._asdict() for profile in response.records])
sys.stdout.write("{}\n".format(data))
@add_action
class RestoreProfilesCommand(Action):
PARSER = argparse.ArgumentParser('restore_profiles', description="Note that this temporarily sets the default profile, and not all data is restored. Input should be JSON from dump_profiles.")
PARSER.add_argument('--number', choices=(0, 1, 2, 3), type=int)
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetProfileNumberCommand())
original_profile = current_profile = response.number
data = simplejson.load(sys.stdin)
if self.extra.number is not None:
profiles = [(self.extra.number, data)]
else:
profiles = list(enumerate(data))
try:
for number, profile in profiles:
if current_profile != number:
current_profile = number
protocol.do_command(powerpod.SetProfileNumberCommand(number))
params = []
for field in powerpod.SetProfileDataCommand._fields:
params.append(profile.pop(field))
protocol.do_command(powerpod.SetProfileDataCommand(*params))
params = []
for field in powerpod.SetProfileData2Command._fields:
params.append(profile.pop(field))
protocol.do_command(powerpod.SetProfileData2Command(*params))
if profile:
LOGGER.warn("left over profile %s data: %r", number, profile)
except Exception:
traceback.print_exc()
if current_profile != original_profile:
protocol.do_command(powerpod.SetProfileNumberCommand(original_profile))
sys.exit(1)
if current_profile != original_profile:
protocol.do_command(powerpod.SetProfileNumberCommand(original_profile))
@add_action
class UpdateProfileCommand(Action):
PARSER = argparse.ArgumentParser('update_profile', description="Note that this temporarily sets the default profile.")
PARSER.add_argument('number', choices=(0, 1, 2, 3), type=int)
for command in (powerpod.SetProfileDataCommand, powerpod.SetProfileData2Command):
for field, typ in zip(command._fields, command.SHAPE[1:]):
if typ in ('h', 'H'):
field_type = int
else:
assert typ == 'f', typ
field_type = float
PARSER.add_argument('--' + field.replace('_', '-'), type=field_type)
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetProfileNumberCommand())
original_profile = response.number
if original_profile != self.extra.number:
protocol.do_command(powerpod.SetProfileNumberCommand(self.extra.number))
profile = protocol.do_command(powerpod.GetProfileDataCommand()).records[self.extra.number]
coalesce = lambda field: getattr(self.extra, field) if getattr(self.extra, field) is not None else getattr(profile, field)
try:
params = []
used = False
for field in powerpod.SetProfileDataCommand._fields:
if getattr(self.extra, field) is None:
params.append(getattr(profile, field))
else:
used = True
params.append(getattr(self.extra, field))
if used:
protocol.do_command(powerpod.SetProfileDataCommand(*params))
params = []
used = False
for field in powerpod.SetProfileData2Command._fields:
if getattr(self.extra, field) is None:
params.append(getattr(profile, field))
else:
used = True
params.append(getattr(self.extra, field))
if used:
protocol.do_command(powerpod.SetProfileData2Command(*params))
except Exception:
traceback.print_exc()
if self.extra.number != original_profile:
protocol.do_command(powerpod.SetProfileNumberCommand(original_profile))
sys.exit(1)
if self.extra.number != original_profile:
protocol.do_command(powerpod.SetProfileNumberCommand(original_profile))
@add_action
class DumpScreensCommand(Action):
""" Since the profile editing commands are a different shape to profile getting, there seems little point in a raw dump. """
PARSER = argparse.ArgumentParser('dump_screens')
PARSER.add_argument('--number', choices=(0, 1, 2, 3), type=int)
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetAllScreensCommand())
if self.extra.number is not None:
data = simplejson.dumps(response.records[self.extra.number].to_dict())
else:
data = simplejson.dumps([profile.to_dict() for profile in response.records])
sys.stdout.write("{}\n".format(data))
@add_action
class RestoreScreensCommand(Action):
PARSER = argparse.ArgumentParser('restore_screens', description="Note that this temporarily sets the default profile, and not all data is restored. Input should be JSON from dump_screens.")
PARSER.add_argument('--number', choices=(0, 1, 2, 3), type=int)
def run(self, protocol, args):
response = protocol.do_command(powerpod.GetProfileNumberCommand())
original_profile = current_profile = response.number
data = simplejson.load(sys.stdin)
if self.extra.number is not None:
screenss = [(self.extra.number, data)]
else:
screenss = list(enumerate(data))
try:
for number, screens in screenss:
if current_profile != number:
current_profile = number
protocol.do_command(powerpod.SetProfileNumberCommand(number))
protocol.do_command(powerpod.SetScreensCommand(powerpod.NewtonProfileScreens.from_dict(screens)))
except Exception:
traceback.print_exc()
if current_profile != original_profile:
protocol.do_command(powerpod.SetProfileNumberCommand(original_profile))
sys.exit(1)
if current_profile != original_profile:
protocol.do_command(powerpod.SetProfileNumberCommand(original_profile))
def make_action(string):
parts = CMD_SPLIT.findall(string)
if not parts:
raise ValueError("Invalid command {}".format(string))
if parts[0] not in ACTIONS:
raise ValueError("Unknown command {}".format(string))
action_class = ACTIONS[parts[0]]
args = action_class.PARSER.parse_args(parts[1:])
return action_class(args)
class HelpActions(argparse.Action):
def __init__(self, *args, **kwargs):
kwargs['nargs'] = 0
super(HelpActions, self).__init__(*args, **kwargs)
@staticmethod
def __call__(parser, namespace, values, option_string):
for action_class in ACTIONS.values():
action_class.PARSER.print_help()
sys.stdout.write('\n\n')
sys.exit(0)
def arg_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--port', default='/dev/ttyUSB0')
parser.add_argument('--debug', default=False)
parser.add_argument(
'actions',
nargs='+',
type=make_action,
help="""
Actions to perform. See --help-actions for a list.
Parameters to actions must be quoted with the action.
""",
)
parser.add_argument(
'--help-actions',
action=HelpActions,
)
return parser
def main():
args = arg_parser().parse_args()
if args.debug:
log_level = logging.DEBUG
else:
log_level = logging.INFO
logging.basicConfig(level=log_level)
kwargs = {}
serial_connection = powerpod.NewtonSerialConnection(port=args.port)
protocol = powerpod.NewtonSerialProtocol(serial_connection, device_side=False)
for action in args.actions:
action.run(protocol, args)
if __name__ == '__main__':
main()