Repository navigation
Expand file tree
/
Copy pathhelper.py
More file actions
264 lines (195 loc) · 7.22 KB
/
Copy pathhelper.py
File metadata and controls
264 lines (195 loc) · 7.22 KB
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
#!/usr/bin/env python
import logging
import os
import sys
import time
import ev3dev.auto
from ev3dev.auto import (RemoteControl, list_motors,
INPUT_1, INPUT_2, INPUT_3, INPUT_4,
OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D)
from math import pi
from time import sleep
log = logging.getLogger(__name__)
INPUTS = (INPUT_1, INPUT_2, INPUT_3, INPUT_4)
OUTPUTS = (OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D)
# =============
# Motor classes
# =============
class MotorStartFail(Exception):
pass
class MotorStopFail(Exception):
pass
class MotorPositionFail(Exception):
pass
class MotorStall(Exception):
pass
class MotorMixin(object):
stop_mode_choices = (ev3dev.auto.Motor.STOP_COMMAND_COAST,
ev3dev.auto.Motor.STOP_COMMAND_BRAKE,
ev3dev.auto.Motor.STOP_COMMAND_HOLD)
shutdown = False
def running(self):
prev_pos = self.position
time.sleep(0.01)
pos = self.position
return True if pos != prev_pos else False
def wait_for_running(self, timeout=5):
"""
timeout is in seconds
"""
tic = time.time() + timeout
prev_pos = None
while time.time() < tic:
if self.shutdown:
break
pos = self.position
if prev_pos is not None and pos != prev_pos:
break
else:
prev_pos = pos
time.sleep(0.001)
else:
raise MotorStartFail("%s: failed to start within %ds" % (self, timeout))
def wait_for_stop(self, timeout=60):
"""
timeout is in seconds
"""
tic = time.time() + timeout
prev_pos = None
stall_count = 0
while time.time() < tic:
if self.shutdown:
break
pos = self.position
log.debug("%s: wait_for_stop() pos %s, prev_pos %s, stall_count %d" % (self, pos, prev_pos, stall_count))
if prev_pos is not None and pos == prev_pos:
stall_count += 1
else:
stall_count = 0
prev_pos = pos
if stall_count >= 5:
break
else:
time.sleep(0.001)
else:
raise MotorStopFail("%s: failed to stop within %ds" % (self, timeout))
def wait_for_position(self, target_position, delta=2, timeout=10, stall_ok=False):
"""
delta is in degrees
timeout is in seconds
"""
min_pos = target_position - delta
max_pos = target_position + delta
time_cutoff = time.time() + timeout
prev_pos = None
stall_count = 0
while time.time() < time_cutoff:
if self.shutdown:
break
pos = self.position
log.debug("%s: wait_for_pos() pos %d/%d, min_pos %d, max_pos %d" % (self, pos, target_position, min_pos, max_pos))
if pos >= min_pos and pos <= max_pos:
break
if prev_pos is not None and pos == prev_pos:
stall_count += 1
else:
stall_count = 0
if stall_count == 50:
if stall_ok:
log.warning("%s: stalled at position %d, target was %d" % (self, pos, target_position))
break
else:
raise MotorStall("%s: stalled at position %d, target was %d" % (self, pos, target_position))
prev_pos = pos
time.sleep(0.001)
else:
raise MotorPositionFail("%s: failed to reach %s within %ss, current position %d" %
(self, target_position, timeout, pos))
class LargeMotor(ev3dev.auto.LargeMotor, MotorMixin):
pass
class MediumMotor(ev3dev.auto.MediumMotor, MotorMixin):
pass
class ColorSensorMixin(object):
def rgb(self):
"""
Note that the mode for the ColorSensor must be set to MODE_RGB_RAW
"""
# These values are on a scale of 0-1020, convert them to a normal 0-255 scale
red = int((self.value(0) * 255) / 1020)
green = int((self.value(1) * 255) / 1020)
blue = int((self.value(2) * 255) / 1020)
return (red, green, blue)
class ColorSensor(ev3dev.auto.ColorSensor, ColorSensorMixin):
pass
# ============
# Tank classes
# ============
class Tank(object):
def __init__(self, left_motor, right_motor, polarity='normal'):
for motor in (left_motor, right_motor):
if motor not in OUTPUTS:
log.error("%s in an invalid motor, choices are %s" % (motor, ', '.join(OUTPUTS)))
sys.exit(1)
self.left_motor = LargeMotor(left_motor)
self.right_motor = LargeMotor(right_motor)
for x in (self.left_motor, self.right_motor):
if not x.connected:
log.error("%s is not connected" % x)
sys.exit(1)
self.left_motor.reset()
self.right_motor.reset()
self.duty_cycle_sp = 90
self.left_motor.duty_cycle_sp = self.duty_cycle_sp
self.right_motor.duty_cycle_sp = self.duty_cycle_sp
self.set_polarity(polarity)
def set_polarity(self, polarity):
valid_choices = ('normal', 'inversed')
assert polarity in valid_choices,\
"%s is an invalid polarity choice, must be %s" % (polarity, ', '.join(valid_choices))
self.left_motor.polarity = polarity
self.right_motor.polarity = polarity
class RemoteControlledTank(Tank):
def __init__(self, left_motor, right_motor, polarity='inversed'):
Tank.__init__(self, left_motor, right_motor, polarity)
self.remote = RemoteControl(channel=1)
if not self.remote.connected:
log.error("%s is not connected" % self.remote)
sys.exit(1)
self.remote.on_red_up = self.make_move(self.left_motor, self.duty_cycle_sp)
self.remote.on_red_down = self.make_move(self.left_motor, self.duty_cycle_sp * -1)
self.remote.on_blue_up = self.make_move(self.right_motor, self.duty_cycle_sp)
self.remote.on_blue_down = self.make_move(self.right_motor, self.duty_cycle_sp * -1)
def make_move(self, motor, dc_sp):
def move(state):
if state:
motor.run_forever(duty_cycle_sp=dc_sp)
else:
motor.stop()
return move
def main(self):
try:
while True:
self.remote.process()
time.sleep(0.01)
# Exit cleanly so that all motors are stopped
except (KeyboardInterrupt, Exception) as e:
log.exception(e)
for motor in list_motors():
motor.stop()
# =====================
# Wheel and Rim classes
# =====================
class Wheel(object):
"""
A base class for various types of wheels, tires, etc
All units are in mm
"""
def __init__(self, diameter, width):
self.diameter = float(diameter)
self.width = float(width)
self.radius = float(diameter/2)
self.circumference = diameter * pi
# A great reference when adding new wheels is http://wheels.sariel.pl/
class EV3RubberWheel(Wheel):
def __init__(self):
Wheel.__init__(self, 43.2, 21)