-
Notifications
You must be signed in to change notification settings - Fork 551
/
command_line.py
2691 lines (2096 loc) · 96.3 KB
/
command_line.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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2023 Boston Dynamics, Inc. All rights reserved.
#
# Downloading, reproducing, distributing or otherwise using the SDK Software
# is subject to the terms and conditions of the Boston Dynamics Software
# Development Kit License (20191101-BDSDK-SL).
"""Command-line utility code for interacting with robot services."""
from __future__ import division
import abc
import argparse
import datetime
import os
import signal
import socket
import sys
import threading
import time
from deprecated.sphinx import deprecated
from google.protobuf import json_format
import bosdyn.client
from bosdyn.api import data_acquisition_pb2, image_pb2
from bosdyn.api.data_buffer_pb2 import Event, TextMessage
from bosdyn.api.data_index_pb2 import EventsCommentsSpec
from bosdyn.api.keepalive import keepalive_pb2
from bosdyn.api.robot_state_pb2 import BehaviorFault
from bosdyn.util import duration_str, timestamp_to_datetime
from .auth import InvalidLoginError, InvalidTokenError
from .data_acquisition import DataAcquisitionClient
from .data_acquisition_helpers import acquire_and_process_request
from .data_acquisition_plugin import DataAcquisitionPluginClient
from .data_buffer import DataBufferClient
from .data_service import DataServiceClient
from .directory import DirectoryClient, NonexistentServiceError
from .directory_registration import DirectoryRegistrationClient, DirectoryRegistrationResponseError
from .estop import EstopClient, EstopEndpoint, EstopKeepAlive
from .exceptions import Error, InvalidRequestError, ProxyConnectionError
from .image import (ImageClient, ImageResponseError, UnknownImageSourceError, build_image_request,
save_images_as_files)
from .keepalive import KeepaliveClient
from .lease import LeaseClient
from .license import LicenseClient
from .local_grid import LocalGridClient
from .log_status import InactiveLogError, LogStatusClient
from .payload import PayloadClient
from .payload_registration import PayloadAlreadyExistsError, PayloadRegistrationClient
from .power import (PowerClient, power_cycle_robot, power_off_payload_ports, power_off_robot,
power_off_wifi_radio, power_on_payload_ports, power_on_wifi_radio)
from .robot_id import RobotIdClient
from .robot_state import RobotStateClient
from .time_sync import TimeSyncClient, TimeSyncEndpoint, TimeSyncError, timespec_to_robot_timespan
from .util import add_common_arguments, authenticate, setup_logging
# pylint: disable=too-few-public-methods
class Command(object, metaclass=abc.ABCMeta):
"""Command-line command.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
# The name of the command the user should enter on the command line to select this command.
NAME = None
# Whether authentication is needed before the command is run.
# Most commands need authentication.
NEED_AUTHENTICATION = True
def __init__(self, subparsers, command_dict):
command_dict[self.NAME] = self
self._parser = subparsers.add_parser(self.NAME, help=self.__doc__)
def run(self, robot, options):
"""Invoke the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
"""
try:
if self.NEED_AUTHENTICATION:
if hasattr(options, 'username') and hasattr(
options, 'password') and (options.username or options.password):
robot.authenticate(options.username, options.password)
else:
authenticate(robot)
robot.sync_with_directory() # Make sure that we can use all registered services.
return self._run(robot, options)
except ProxyConnectionError:
print('Could not contact robot with hostname "{}".'.format(options.hostname),
file=sys.stderr)
except InvalidTokenError:
print('The provided user token is invalid.', file=sys.stderr)
except InvalidLoginError:
print('Username and/or password are invalid.', file=sys.stderr)
except Error as err:
print('{}: {}'.format(type(err).__name__, err), file=sys.stderr)
@abc.abstractmethod
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
"""
class Subcommands(Command):
"""Run subcommands.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
subcommands: List of subcommands to run.
"""
def __init__(self, subparsers, command_dict, subcommands):
super(Subcommands, self).__init__(subparsers, command_dict)
command_dest = '{}_command'.format(self.NAME)
cmd_subparsers = self._parser.add_subparsers(title=self.__doc__, dest=command_dest)
cmd_subparsers.required = True
self._subcommands = {}
for subcommand in subcommands:
subcommand(cmd_subparsers, self._subcommands)
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
Execution of the specific subcommand from the options.
"""
command_dest = '{}_command'.format(self.NAME)
subcommand = vars(options)[command_dest]
return self._subcommands[subcommand].run(robot, options)
class DirectoryCommands(Subcommands):
"""Commands related to the directory service."""
NAME = 'dir'
def __init__(self, subparsers, command_dict):
"""Commands related to the directory service.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(DirectoryCommands, self).__init__(subparsers, command_dict, [
DirectoryListCommand, DirectoryGetCommand, DirectoryRegisterCommand,
DirectoryUnregisterCommand
])
def _format_dir_entry( # pylint: disable=too-many-arguments
name, service_type, authority, tokens, name_width=23, type_width=31, authority_width=27):
"""Prints the passed values as "name service_type authority tokens", with the first three using
the specified width.
Args:
name: Name of the service.
service_type: Type of the service.
authority: Authority of the service.
tokens: Tokens required for using the service.
name_width: Width for printing the name value.
type_width: Width for printing the service_type value.
authority_width: Width for printing the authority value.
"""
print(('{:' + str(name_width) + '} {:' + str(type_width) + '} {:' + str(authority_width) +
'} {}').format(name, service_type, authority, tokens))
def _token_req_str(entry):
"""Returns a string representing tokens required for using the service.
Args:
entry: Service entry being checked.
Returns:
String with a comma-separated list of required tokens.
"""
required = []
if entry.user_token_required:
required.append('user')
if not required:
return ''
return ', '.join(required)
def _show_directory_list(robot, as_proto=False):
"""Print service directory list for robot.
Args:
robot: Robot object used to get the list of services.
as_proto: Boolean to determine whether the directory entries should be printed as full
proto definitions or formatted strings.
Returns:
True
"""
entries = robot.ensure_client(DirectoryClient.default_service_name).list()
if not entries:
print("No services found")
return True
if as_proto:
for entry in entries:
print(entry)
return True
max_name_length = max(len(entry.name) for entry in entries)
max_type_length = max(len(entry.type) for entry in entries)
max_authority_length = max(len(entry.authority) for entry in entries)
_format_dir_entry('name', 'type', 'authority', 'tokens', max_name_length + 4,
max_type_length + 4, max_authority_length + 4)
print("-" * (20 + max_name_length + max_type_length + max_authority_length))
for entry in entries:
_format_dir_entry(entry.name, entry.type, entry.authority, _token_req_str(entry),
max_name_length + 4, max_type_length + 4, max_authority_length + 4)
return True
def _show_directory_entry(robot, service, as_proto=False):
"""Print a service directory entry.
Args:
robot: Robot object used to get the list of services.
service: Name of the service to print.
as_proto: Boolean to determine whether the directory entries should be printed as full
proto definitions or formatted strings.
Returns:
True
"""
entry = robot.ensure_client(DirectoryClient.default_service_name).get_entry(service)
if as_proto:
print(entry)
else:
_format_dir_entry('name', 'type', 'authority', 'tokens')
print("-" * 90)
_format_dir_entry(entry.name, entry.type, entry.authority, _token_req_str(entry))
return True
class DirectoryListCommand(Command):
"""List all services in the directory."""
NAME = 'list'
def __init__(self, subparsers, command_dict):
"""List all services in the directory.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(DirectoryListCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('--proto', action='store_true',
help='print listing in proto format')
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True
"""
_show_directory_list(robot, as_proto=options.proto)
return True
class DirectoryGetCommand(Command):
"""Get entry for a given service in the directory."""
NAME = 'get'
def __init__(self, subparsers, command_dict):
"""Get entry for a given service in the directory.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(DirectoryGetCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('--proto', action='store_true',
help='print listing in proto format')
self._parser.add_argument('service', help='service name to get entry for')
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
False if NonexistentServiceError is caught, True otherwise.
"""
try:
_show_directory_entry(robot, options.service, as_proto=options.proto)
except NonexistentServiceError:
print('The requested service name "{}" does not exist. Available services:'.format(
options.service))
_show_directory_list(robot, as_proto=options.proto)
return False
return True
class DirectoryRegisterCommand(Command):
"""Register entry for a service in the directory."""
NAME = 'register'
def __init__(self, subparsers, command_dict):
"""Register entry for a service in the directory.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(DirectoryRegisterCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('--service-name', required=True,
help='unique name of the service')
self._parser.add_argument('--service-type', required=True,
help='Type of the service, e.g. bosdyn.api.RobotStateService')
self._parser.add_argument('--service-authority', required=True,
help='authority of the service')
self._parser.add_argument('--service-hostname', required=True,
help='hostname of the service computer')
self._parser.add_argument('--service-port', required=True, type=int,
help='port the service is running on')
self._parser.add_argument('--no-user-token', action='store_true', required=False,
help='disable requirement for user token')
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
False if DirectoryRegistrationResponseError is caught, True otherwise.
"""
directory_registration_client = robot.ensure_client(
DirectoryRegistrationClient.default_service_name)
try:
directory_registration_client.register(options.service_name, options.service_type,
options.service_authority,
options.service_hostname, options.service_port,
user_token_required=not options.no_user_token)
except DirectoryRegistrationResponseError as exc:
# pylint: disable=no-member
print("Failed to register service {}.\nResponse Status: {}".format(
options.service_name,
bosdyn.api.directory_registration_pb2.RegisterServiceResponse.Status.Name(
exc.response.status)))
return False
else:
print("Successfully registered service {}".format(options.service_name))
return True
class DirectoryUnregisterCommand(Command):
"""Unregister entry for a service in the directory."""
NAME = 'unregister'
def __init__(self, subparsers, command_dict):
"""Unregister entry for a service in the directory.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(DirectoryUnregisterCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('--service-name', required=True,
help='unique name of the service')
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
False if DirectoryRegistrationResponseError is caught, True otherwise.
"""
directory_registration_client = robot.ensure_client(
DirectoryRegistrationClient.default_service_name)
try:
directory_registration_client.unregister(options.service_name)
except DirectoryRegistrationResponseError as exc:
# pylint: disable=no-member
print("Failed to unregister service {}.\nResponse Status: {}".format(
options.service_name,
bosdyn.api.directory_registration_pb2.UnregisterServiceResponse.Status.Name(
exc.response.status)))
return False
else:
print("Successfully unregistered service {}".format(options.service_name))
return True
class PayloadCommands(Subcommands):
"""Commands related to the payload and payload registration services."""
NAME = 'payload'
def __init__(self, subparsers, command_dict):
"""Commands related to the payload and payload registration services.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(PayloadCommands, self).__init__(subparsers, command_dict,
[PayloadListCommand, PayloadRegisterCommand])
def _show_payload_list(robot, as_proto=False):
"""Print payload list for robot.
Args:
robot: Robot object used to get the list of services.
as_proto: Boolean to determine whether the payload entries should be printed as full
proto definitions or formatted strings.
Returns:
True
"""
payload_protos = robot.ensure_client(PayloadClient.default_service_name).list_payloads()
if not payload_protos:
print("No payloads found")
return True
if as_proto:
for payload in payload_protos:
print(payload)
return True
# Print out the payload name, description, and GUID in columns with set width.
name_width = 30
description_width = 60
guid_width = 36
print(('\n{:' + str(name_width) + '} {:' + str(description_width) + '} {:' + str(guid_width) +
'}').format('Name', 'Description', 'GUID'))
print("-" * (5 + name_width + description_width + guid_width))
for payload in payload_protos:
print(('{:' + str(name_width) + '} {:' + str(description_width) + '} {:' + str(guid_width) +
'}').format(payload.name, payload.description, payload.GUID))
return True
class PayloadListCommand(Command):
"""List all payloads registered with the robot."""
NAME = 'list'
def __init__(self, subparsers, command_dict):
"""List all payloads registered with the robot.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(PayloadListCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('--proto', action='store_true',
help='print listing in proto format')
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True
"""
_show_payload_list(robot, as_proto=options.proto)
return True
def _register_payload(robot, name, guid, secret):
"""Register a payload with the robot.
Args:
robot: Robot object used to register the payload.
name: The name that will be assigned to the registered payload.
guid: The GUID that will be assigned to the registered payload.
secret: The secret that the payload will be registered with.
Returns:
True
"""
payload_registration_client = robot.ensure_client(
PayloadRegistrationClient.default_service_name)
payload = bosdyn.api.payload_pb2.Payload(GUID=guid, name=name)
try:
payload_registration_client.register_payload(payload, secret)
except PayloadAlreadyExistsError:
print('\nA payload with this GUID is already registered. Check the robot Admin Console.')
else:
print('\nPayload successfully registered with the robot.\n'
'Before it can be used, the payload must be authorized in the Admin Console.')
return True
class PayloadRegisterCommand(Command):
"""Register a payload with the robot."""
NAME = 'register'
def __init__(self, subparsers, command_dict):
"""Register a payload with the robot.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(PayloadRegisterCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('--payload-name', required=True, help='name of the payload')
self._parser.add_argument('--payload-guid', required=True, help='guid of the payload')
self._parser.add_argument('--payload-secret', required=True, help='secret for the payload')
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True
"""
_register_payload(robot, options.payload_name, options.payload_guid, options.payload_secret)
class FaultCommands(Subcommands):
"""Commands related to the fault service and robot state service (for fault reading)."""
NAME = 'fault'
def __init__(self, subparsers, command_dict):
"""Commands related to the fault service and robot state service (for fault reading).
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(FaultCommands, self).__init__(subparsers, command_dict,
[FaultShowCommand, FaultWatchCommand])
def _show_all_faults(robot):
"""Print faults for the robot.
Args:
robot: Robot object used to get the list of services.
"""
robot_state_client = robot.ensure_client(RobotStateClient.default_service_name)
robot_state = robot_state_client.get_robot_state()
system_fault_state = robot_state.system_fault_state
behavior_fault_state = robot_state.behavior_fault_state
service_fault_state = robot_state.service_fault_state
print('\n' + '-' * 80)
if len(system_fault_state.faults) == 0:
print("No active system faults.")
else:
for fault in system_fault_state.faults:
print('''
{fault.name}
Error Message: {fault.error_message}
Onset Time: {timestamp}''' \
.format(fault=fault, timestamp=timestamp_to_datetime(fault.onset_timestamp)))
print()
if len(behavior_fault_state.faults) == 0:
print("No active behavior faults.")
else:
for fault in behavior_fault_state.faults:
print('''
{cause}
Onset Time: {timestamp}
Clearable: {clearable}''' \
.format(cause=BehaviorFault.Cause.Name(fault.cause),
timestamp=timestamp_to_datetime(fault.onset_timestamp),
clearable=BehaviorFault.Status.Name(fault.status)))
print()
if len(service_fault_state.faults) == 0:
print("No active service faults.")
else:
for fault in service_fault_state.faults:
print('''
{fault.fault_id.fault_name}
Service Name: {fault.fault_id.service_name}
Payload GUID: {fault.fault_id.payload_guid}
Error Message: {fault.error_message}
Onset Time: {timestamp}'''\
.format(fault=fault, timestamp=timestamp_to_datetime(fault.onset_timestamp)))
class FaultShowCommand(Command):
"""Show all faults currently active in robot state."""
NAME = 'show'
def __init__(self, subparsers, command_dict):
"""Show all faults currently active in robot state.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(FaultShowCommand, self).__init__(subparsers, command_dict)
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True
"""
_show_all_faults(robot)
return True
class FaultWatchCommand(Command):
"""Watch all faults in robot state and print them out."""
NAME = 'watch'
def __init__(self, subparsers, command_dict):
"""Watch all service faults in robot state and print them out.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(FaultWatchCommand, self).__init__(subparsers, command_dict)
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True
"""
print('Press Ctrl-C or send SIGINT to exit\n\n')
try:
while True:
_show_all_faults(robot)
time.sleep(1)
except KeyboardInterrupt:
pass
return True
class LogStatusCommands(Subcommands):
"""Start, update and terminate experiment logs, start and terminate retro logs and check status of
active logs for robot."""
NAME = 'log-status'
NEED_AUTHENTICATION = True
def __init__(self, subparsers, command_dict):
"""Interact with logs for robot
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(LogStatusCommands, self).__init__(subparsers, command_dict, [
GetLogCommand,
GetActiveLogStatusesCommand,
ExperimentLogCommand,
StartRetroLogCommand,
TerminateLogCommand,
])
class GetLogCommand(Command):
"""Get log status but log id."""
NAME = 'get'
def __init__(self, subparsers, command_dict):
"""Get log status from robot
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(GetLogCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('id', help='id of log bundle to display')
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True
"""
client = robot.ensure_client(LogStatusClient.default_service_name)
response = client.get_log_status(options.id)
print(response.log_status)
return True
class GetActiveLogStatusesCommand(Command):
"""Get active log bundles for robot."""
NAME = 'active'
def __init__(self, subparsers, command_dict):
"""Retrieve active log statuses for robot.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(GetActiveLogStatusesCommand, self).__init__(subparsers, command_dict)
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True
"""
client = robot.ensure_client(LogStatusClient.default_service_name)
response = client.get_active_log_statuses()
print(response.log_statuses)
return True
class ExperimentLogCommand(Subcommands):
"""Give experiment log commands to robot."""
NAME = 'experiment'
def __init__(self, subparsers, command_dict):
"""Start a timed or continuous experiment log.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(ExperimentLogCommand, self).__init__(subparsers, command_dict, [
StartTimedExperimentLogCommand,
StartContinuousExperimentLogCommand,
])
class StartTimedExperimentLogCommand(Command):
"""Start a timed experiment log."""
NAME = 'timed'
def __init__(self, subparsers, command_dict):
"""Start timed experiment log
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(StartTimedExperimentLogCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('seconds', type=float, help='how long should the experiment run?')
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True
"""
client = robot.ensure_client(LogStatusClient.default_service_name)
response = client.start_experiment_log(options.seconds)
print(response.log_status)
return True
class StartContinuousExperimentLogCommand(Command):
"""Start a continuous experiment log."""
NAME = 'continuous'
def __init__(self, subparsers, command_dict):
"""Start continuous experiment log, defaulted to update keep alive time by 10 seconds every 5 seconds.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(StartContinuousExperimentLogCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('-sleep', type=float, default=5,
help='how long should thread sleep before extending')
@staticmethod
def handle_keyboard_interruption(client, log_id):
try:
print(" Received keyboard interruption\n\n")
response = client.terminate_log(log_id)
print(response.log_status)
except KeyboardInterrupt:
client.terminate_log_async(log_id)
print("Log will terminate shortly")
response = client.get_log_status(log_id)
print(response.log_status)
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True
"""
client = robot.ensure_client(LogStatusClient.default_service_name)
response = client.start_experiment_log(options.sleep * 2)
log_id = response.log_status.id
print("Experiment log id: ", log_id)
print('Use terminate command, press Ctrl-C or send SIGINT to complete log\n\n')
try:
while True:
time.sleep(options.sleep)
client.update_experiment(log_id, options.sleep * 2)
except InactiveLogError:
response = client.get_log_status(log_id)
print(response.log_status)
except KeyboardInterrupt:
self.handle_keyboard_interruption(client, log_id)
return True
class StartRetroLogCommand(Command):
"""Start a retro log."""
NAME = 'retro'
def __init__(self, subparsers, command_dict):
"""Start a retro log
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(StartRetroLogCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('seconds', type=float, help='how long should the retro log run?')
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True
"""
client = robot.ensure_client(LogStatusClient.default_service_name)
response = client.start_retro_log(options.seconds)
print(response.log_status)
return True
class TerminateLogCommand(Command):
"""Terminate log gathering process."""
NAME = 'terminate'
def __init__(self, subparsers, command_dict):
"""Terminate log on robot
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(TerminateLogCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('id', help='id of log to terminate')
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True
"""
client = robot.ensure_client(LogStatusClient.default_service_name)
response = client.terminate_log(options.id)
print(response.log_status)
return True
class RobotIdCommand(Command):
"""Show robot-id."""
NAME = 'id'
NEED_AUTHENTICATION = False
def __init__(self, subparsers, command_dict):
"""Show robot-id.
Args:
subparsers: List of argument parsers.
command_dict: Dictionary of command names which take parsed options.
"""
super(RobotIdCommand, self).__init__(subparsers, command_dict)
self._parser.add_argument('--proto', action='store_true',
help='print listing in proto format')
def _run(self, robot, options):
"""Implementation of the command.
Args:
robot: Robot object on which to run the command.
options: Parsed command-line arguments.
Returns:
True.
"""
proto = robot.ensure_client(RobotIdClient.default_service_name).get_id()
if options.proto:
print(proto)
return True
nickname = ''
if proto.nickname and proto.nickname != proto.serial_number:
nickname = proto.nickname
release = proto.software_release
version = release.version
print(u"{:20} {:15} {:10} {} ({})".format(proto.serial_number, proto.computer_serial_number,
nickname, proto.species, proto.version))
print(" Software: {}.{}.{} ({} {})".format(version.major_version, version.minor_version,
version.patch_level, release.changeset,
timestamp_to_datetime(release.changeset_date)))
print(" Installed: {}".format(timestamp_to_datetime(release.install_date)))
return True
class DataBufferCommands(Subcommands):
"""Commands related to the data-buffer service."""
NAME = 'log'
def __init__(self, subparsers, command_dict):