-
Notifications
You must be signed in to change notification settings - Fork 49
/
peas_shell
executable file
·375 lines (301 loc) · 13.2 KB
/
peas_shell
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
#!/usr/bin/env python
import cmd
import datetime
import os
import readline
import sys
from astropy.utils import console
from threading import Timer
from pprint import pprint
from peas.sensors import ArduinoSerialMonitor
from peas.weather import AAGCloudSensor
from pocs.utils import current_time
from pocs.utils.config import load_config
from pocs.utils.database import PanDB
class PanSensorShell(cmd.Cmd):
""" A simple command loop for the sensors. """
intro = 'Welcome to PEAS Shell! Type ? for help'
prompt = 'PEAS > '
environment = None
weather = None
active_sensors = dict()
db = PanDB()
_keep_looping = False
_loop_delay = 60
_timer = None
captured_data = list()
messaging = None
config = load_config(config_files=['peas'])
##################################################################################################
# Generic Methods
##################################################################################################
def do_status(self, *arg):
""" Get the entire system status and print it pretty like! """
if self._keep_looping:
console.color_print("{:>12s}: ".format('Loop Timer'),
"default", "active", "lightgreen")
else:
console.color_print("{:>12s}: ".format('Loop Timer'),
"default", "inactive", "yellow")
for sensor_name in ['environment', 'weather']:
if sensor_name in self.active_sensors:
console.color_print("{:>12s}: ".format(sensor_name.title()),
"default", "active", "lightgreen")
else:
console.color_print("{:>12s}: ".format(sensor_name.title()),
"default", "inactive", "yellow")
def do_last_reading(self, device):
""" Gets the last reading from the device. """
if not device:
print_warning('Usage: last_reading <device>')
return
if not hasattr(self, device):
print_warning('No such sensor: {!r}'.format(device))
return
rec = self.db.get_current(device)
if rec is None:
print_warning('No reading found for {!r}'.format(device))
return
print_info('*' * 80)
print("{}:".format(device.upper()))
pprint(rec)
print_info('*' * 80)
if isinstance(rec.get('date'), datetime.datetime):
now = current_time(datetime=True)
age = (now - rec['date']).total_seconds()
if age < 120:
print_info('{:.1f} seconds old'.format(age))
else:
print_info('{:.1f} minutes old'.format(age / 60.0))
def complete_last_reading(self, text, line, begidx, endidx):
"""Provide completions for sensor names."""
names = ['environment', 'weather']
return [name for name in names if name.startswith(text)]
def do_enable_sensor(self, sensor, delay=None):
""" Enable the given sensor """
if delay is None:
delay = self._loop_delay
if hasattr(self, sensor) and sensor not in self.active_sensors:
self.active_sensors[sensor] = {'reader': sensor, 'delay': delay}
def do_disable_sensor(self, sensor):
""" Enable the given sensor """
if hasattr(self, sensor) and sensor in self.active_sensors:
del self.active_sensors[sensor]
def do_toggle_debug(self, sensor):
""" Toggle DEBUG on/off for sensor
Arguments:
sensor {str} -- environment, weather
"""
# TODO(jamessynge): We currently use a single logger, not one per module or sensor.
# Figure out whether to keep this code and make it work, or get rid of it.
import logging
get_level = {
logging.DEBUG: logging.INFO,
logging.INFO: logging.DEBUG,
}
if hasattr(self, sensor):
try:
log = getattr(self, sensor).logger
log.setLevel(get_level[log.getEffectiveLevel()])
except Exception:
print_error("Can't change log level for {}".format(sensor))
def do_display_config(self, config):
""" Display the config file for PEAS """
if self.config:
pprint(self.config)
else:
print_warning("No config file for PEAS.")
##################################################################################################
# Load Methods
##################################################################################################
def do_load_all(self, *arg):
"""Load the weather and environment sensors."""
if self._keep_looping:
print_error('The timer loop is already running.')
return
self.do_load_weather()
self.do_load_environment()
def do_load_environment(self, *arg):
""" Load the arduino environment sensors """
if self._keep_looping:
print_error('The timer loop is already running.')
return
print("Loading sensors")
self.environment = ArduinoSerialMonitor(auto_detect=False)
self.do_enable_sensor('environment', delay=1)
def do_load_weather(self, *arg):
""" Load the weather reader """
if self._keep_looping:
print_error('The timer loop is already running.')
return
try:
port = self.config['weather']['aag_cloud']['serial_port']
except KeyError:
port = '/dev/ttyUSB0'
print("Loading AAG Cloud Sensor on {}".format(port))
self.weather = AAGCloudSensor(serial_address=port, store_result=True)
self.do_enable_sensor('weather')
##################################################################################################
# Relay Methods
##################################################################################################
def do_toggle_relay(self, *arg):
""" Toggle a relay
This will toggle a relay on the on the power board, switching off if on
and on if off. Possible relays include:
* fan
* camera_box
* weather
* mount
* cam_0
* cam_0
"""
relay = arg[0]
telemetry_relay_lookup = {
'fan': {'pin': 6, 'board': 'telemetry_board'},
'camera_box': {'pin': 7, 'board': 'telemetry_board'},
'weather': {'pin': 5, 'board': 'telemetry_board'},
'mount': {'pin': 4, 'board': 'telemetry_board'},
'cam_0': {'pin': 5, 'board': 'camera_board'},
'cam_1': {'pin': 6, 'board': 'camera_board'},
}
# NOTE: These are not pins but index numbers
powerboard_relay_lookup = {
'mount': {'pin': 0, 'board': 'power_board'},
'fan': {'pin': 1, 'board': 'power_board'},
'weather': {'pin': 2, 'board': 'power_board'},
'camera_box': {'pin': 3, 'board': 'power_board'},
}
if 'power_board' in self.environment.serial_readers:
relay_lookup = powerboard_relay_lookup
else:
relay_lookup = telemetry_relay_lookup
try:
relay_info = relay_lookup[relay]
serial_connection = self.environment.serial_readers[relay_info['board']]['reader']
serial_connection.ser.flushInput()
serial_connection.write("{},9".format(relay_info['pin']))
except Exception as e:
print_warning("Problem toggling relay {}".format(relay))
print_warning(e)
def complete_toggle_relay(self, text, line, begidx, endidx):
"""Provide completions for relay names."""
if 'power_board' in self.environment.serial_readers:
names = ['camera_box', 'fan', 'mount', 'weather']
else:
names = ['cam_0', 'cam_1', 'camera_box', 'fan', 'mount', 'weather']
return [name for name in names if name.startswith(text)]
def do_toggle_computer(self, *arg):
"""Toggle the computer relay off and then on again."""
try:
board = 'telemetry_board'
pin = 8
# Special command will toggle off, wait 30 seconds, then toggle on
self.environment.serial_readers[board]['reader'].write("{},0".format(pin))
except Exception as e:
print_warning(e)
##################################################################################################
# Start/Stop Methods
##################################################################################################
def do_start(self, *arg):
""" Runs all the `active_sensors`. Blocking loop for now """
if self._keep_looping:
print_error('The timer loop is already running.')
return
self._keep_looping = True
print_info("Starting sensors")
self._loop()
def do_stop(self, *arg):
""" Stop the loop and cancel next call """
# NOTE: We don't yet have a way to clear _timer.
if not self._keep_looping and not self._timer:
print_error('The timer loop is not running.')
return
print_info("Stopping loop")
self._keep_looping = False
if self._timer:
self._timer.cancel()
def do_change_delay(self, *arg):
"""Change the timing between reads from the named sensor."""
# NOTE: For at least the Arduinos, we should not need a delay and a timer, but
# simply a separate thread, reading from the board as data is available.
# We might use a delay to deal with the case where the device is off-line
# but we want to periodically check if it becomes available.
parts = None
if len(arg) == 1:
parts = arg[0].split()
if parts is None or len(parts) != 2:
print_error('Expected a sensor name and a delay, not "{}"'.format(' '.join(arg)))
return
sensor_name, delay = parts
try:
delay = float(delay)
if delay <= 0:
raise ValueError()
except ValueError:
print_warning("Not a positive number: {!r}".format(delay))
return
try:
print_info("Changing sensor {} to a {} second delay".format(sensor_name, delay))
self.active_sensors[sensor_name]['delay'] = delay
except KeyError:
print_warning("Sensor not active: {!r}".format(sensor_name))
##################################################################################################
# Shell Methods
##################################################################################################
def do_shell(self, line):
""" Run a raw shell command. Can also prepend '!'. """
print("Shell command:", line)
output = os.popen(line).read()
print_info("Shell output: ", output)
self.last_output = output
def emptyline(self):
self.do_status()
def do_exit(self, *arg):
""" Exits PEAS Shell """
print("Shutting down")
if self._timer or self._keep_looping:
self.do_stop()
print("Please be patient and allow for process to finish. Thanks! Bye!")
return True
##################################################################################################
# Private Methods
##################################################################################################
def _capture_data(self, sensor_name):
# We are missing a Mutex here for accessing these from active_sensors and
# self.
if sensor_name in self.active_sensors:
sensor = getattr(self, sensor_name)
try:
sensor.capture(store_result=True, send_message=True)
except Exception:
pass
self._setup_timer(sensor_name, delay=self.active_sensors[sensor_name]['delay'])
def _loop(self, *arg):
for sensor_name in self.active_sensors.keys():
self._capture_data(sensor_name)
def _setup_timer(self, sensor_name, delay=None):
if self._keep_looping and len(self.active_sensors) > 0:
if not delay:
delay = self._loop_delay
# WARNING: It appears we have a single _timer attribute, but we create
# one Timer for each active sensor (i.e. environment and weather).
self._timer = Timer(delay, self._capture_data, args=(sensor_name,))
self._timer.start()
##################################################################################################
# Utility Methods
##################################################################################################
def print_info(msg):
console.color_print(msg, 'lightgreen')
def print_warning(msg):
console.color_print(msg, 'yellow')
def print_error(msg):
console.color_print(msg, 'red')
if __name__ == '__main__':
invoked_script = os.path.basename(sys.argv[0])
histfile = os.path.expanduser('~/.{}_history'.format(invoked_script))
histfile_size = 1000
if os.path.exists(histfile):
readline.read_history_file(histfile)
PanSensorShell().cmdloop()
readline.set_history_length(histfile_size)
readline.write_history_file(histfile)