-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrti_py.py
222 lines (185 loc) · 9.16 KB
/
rti_py.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
#!/usr/bin/python3
"""
MIT License
Copyright (c) 2021 Richard Benjamin Allen, Palaeopi Limited
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEA
"""
import argparse
import logging.config
import os
import time
import serial
import sys
import yaml
from serial import SerialException
from typing import Dict
from typing import List, Optional
log_config: Dict = yaml.load(open('logging.yml', 'r'), Loader=yaml.FullLoader)
log = logging.getLogger("__name__")
def get_serial_port() -> Optional[str]:
"""
Gets the USB serial port that the Arduino board is on if the platform is supported i.e. Mac or Linux only.
:return: string containing the Arduino serial port address on either Linux of MacOS, returns None for other
unsupported systems.
"""
if sys.platform == "linux":
return "/dev/" + os.popen("dmesg | egrep ttyACM | cut -f3 -d: | tail -n1").read().strip()
elif sys.platform == "darwin":
return "/dev/cu.usbmodem1411"
elif sys.platform == "win32":
return "COM3"
return None
def convert_string_to_number(string: str) -> Optional[int]:
"""
Takes a string and tries to convert it into an int as a check for input parameter formatting.
:param string: string containing the calibration command sequence.
:return: integer if string is convertable to that type, returns None if not.
:raises: ValueError if string cannot be converted to an integer.
"""
try:
return int(string)
except ValueError as error:
raise error
def light_led(serial_connection: str) -> bool:
"""
Takes a serial device address and attempts to send a string command to the Arduino to light one LED in the dome for
60 seconds so a camera can be set up with the correct exposure and aperture etc.
:param serial_connection: string containing the serial address of the Arduino connected to the USB port.
:return: True if function successfully writes to the USB port.
:raise: SerialException if USB serial connection is lost.
"""
try:
ser = serial.Serial(serial_connection, 9600, timeout=5)
time.sleep(2)
ser.write(b'L,0')
time.sleep(2)
log.info('Lighting LED for 60 seconds to allow for camera focusing!')
except SerialException as error:
log.error('Having trouble connecting, exiting with the following error %s', error)
raise error
return True
def calibrate_led(serial_connection: str, calibration: str) -> bool:
"""
Takes a serial device address and calibration string and attempts to send a string command to the Arduino to light
one LED in the dome for a specific amount of time (can also be used to set up a camera). The calibration string
needs to be a series of comma delimited integers.
:param serial_connection: string containing the serial address of the Arduino connected to the USB port
:param calibration: string containing 3 comma delimited integers containing the x, y, coordinates of the LED you
wish to light up followed by how many seconds you wish to light it for e.g. 3,0,20.
:return: True if function successfully writes to the USB port.
:raise: SerialException if USB serial connection is lost.
"""
try:
ser = serial.Serial(serial_connection, 9600, timeout=5)
time.sleep(2)
ser.write(f'T, {bytes(calibration,"utf-8")}')
time.sleep(2)
calibration_split: List = calibration.split()
log.info('Turning on an LED at address x: %s, y: %s, for %s seconds!',
calibration_split[0], calibration_split[1], calibration_split[2])
except SerialException as error:
log.error('Having trouble connecting, exiting with the following error %s', error)
raise error
return True
def start_capture(serial_connection: str) -> bool:
"""
Takes a serial device address and loads a configuration defined in a yaml file. The configuration is converted
into a command sequence which is then sent to the Arduino to instruct it to capture a sequence of images in the
dome and what range of LEDs to use. It is possible to set the wait in between photos, and also the start and end
range of the LEDs you wish to use.
:param serial_connection: string containing the serial address of the Arduino connected to the USB port.
:return: True if function successfully writes to the USB port.
:raise: SerialException if USB serial connection is lost.
"""
setup: Dict = yaml.load(open('setup.yml', 'r'), Loader=yaml.FullLoader).get('setup')
delay_before: str = setup.get('delay_before')
delay_after: str = setup.get('delay_after')
start_row: str = setup.get('start_row')
end_row: str = setup.get('end_row')
start_column: str = setup.get('start_column')
end_column: str = setup.get('end_column')
max_leds: str = setup.get('max_leds')
command_sequence: str = f"C, {delay_before},{delay_after},{start_row},{end_row},{start_column},{end_column},{max_leds}"
command_sequence: bytes = bytes(command_sequence, 'utf-8')
try:
ser = serial.Serial(serial_connection, 9600, timeout=5)
time.sleep(2)
ser.write(command_sequence)
time.sleep(2)
log.info("Starting capture sequence in 5 seconds, to cancel simply press the reset button on the Arduino"
"Capture can take 5-10 minutes to complete!")
except SerialException as error:
log.error('Having trouble connecting, exiting with the following error %s', error)
raise error
return True
def main(arguments) -> bool:
"""
Takes arguments from argparse and runs either light_led, calibrate_led, or capture based on your choice.
:param arguments: Arguments parsed out of argparse, this should only ever contain one of the mutually exclusive
group, so it is not possible to run calibration at the same time as capture.
:return: True if chosen function succeeds; False if chosen function fails.
"""
serial_name: str = get_serial_port()
if serial_name is None:
log.error("System operating system is not supported for this program")
return False
if arguments.light:
light: bool = light_led(serial_name)
if not light:
return False
return True
elif arguments.calibrate:
calibration: str = arguments.calibrate
calibrate: bool = calibrate_led(serial_name, calibration)
if not calibrate:
return False
return True
capture: bool = start_capture(serial_name)
if not capture:
return False
return True
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Python terminal application to make operating the RTI dome simpler')
arg_group = parser.add_mutually_exclusive_group(required=True)
arg_group.add_argument('-l', '--light', action='store_true', help='Set up the camera by turning on a light')
arg_group.add_argument('-c', '--calibrate', type=str, help='Enter the address of the LED and how long you would '
'like it to be activated for (in seconds), each variable'
'needs to be delimited by commas starting with '
'x, y, time e.g. 3,0,20')
arg_group.add_argument('-s', '--start', action='store_true', help='Start capture of the RTI dome once camera and '
'LEDS are set up')
args = parser.parse_args()
if args.calibrate:
led_split = args.calibrate.split(',')
if len(led_split) == 3:
for item in led_split:
try:
convert_string_to_number(item)
except ValueError:
log.error("One or more values given in the parameter is not an integer! Please try again!")
sys.exit(1)
else:
log.error("Not enough variables to pass along to the Arduino! Please specify three exactly delimited"
"by a comma and try again!")
try:
success = main(args)
except BaseException:
log.error("Unhandled exception in rti_pi", exc_info=True)
raise
if success:
sys.exit()
else:
sys.exit(1)