Skip to content

Commit 9b8ad80

Browse files
committed
Add documentation to hopefully avoid subclassing the robot
1 parent d83ae07 commit 9b8ad80

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

programming/robot_api/index.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,3 +196,70 @@ RobotMode.COMP.value == "COMP" # True
196196
~~~~~
197197

198198
In general, the enum should be used and compared directly, rather than using its inner value.
199+
200+
## Creating your own helpers
201+
202+
The provided `Robot` object provides access to the boards provided with the kit. However, you may feel the urge to extend it to add your own methods to make development clearer.. However, this can introduce issues if the methods or properties you add interfere with the inner workings of the `Robot` object.
203+
204+
Instead, you can wrap the `Robot` object with your own class:
205+
206+
~~~~~ python
207+
from sr.robot3 import Robot
208+
import time
209+
210+
class MyRobot:
211+
def __init__(self):
212+
self.robot = Robot()
213+
214+
def drive_forwards(self, seconds):
215+
"""
216+
Drive forwards for a given number of seconds
217+
"""
218+
robot.motor_boards["srABC1"].motors[0].power = 0.5
219+
robot.motor_boards["srABC1"].motors[1].power = 0.5
220+
time.sleep(seconds)
221+
robot.motor_boards["srABC1"].motors[0].power = 0
222+
robot.motor_boards["srABC1"].motors[1].power = 0
223+
224+
# Now, use your class instead
225+
robot = MyRobot()
226+
robot.drive_forwards(3)
227+
~~~~~
228+
229+
This is not the only way to design your own robot API. You may instead want to define helper functions:
230+
231+
~~~~~ python
232+
from sr.robot3 import Robot
233+
import time
234+
235+
def drive_forwards(robot, seconds):
236+
"""
237+
Drive forwards for a given number of seconds
238+
"""
239+
robot.motor_boards["srABC1"].motors[0].power = 0.5
240+
robot.motor_boards["srABC1"].motors[1].power = 0.5
241+
time.sleep(seconds)
242+
robot.motor_boards["srABC1"].motors[0].power = 0
243+
robot.motor_boards["srABC1"].motors[1].power = 0
244+
245+
# Now, use your class instead
246+
robot = Robot()
247+
drive_forwards(robot, 3)
248+
~~~~~
249+
250+
Both of these approaches are equally valid. Choosing which you want to use will likely come down to your own preferences.
251+
252+
<div class="warning" markdown="1">
253+
Attempting to subclass the `Robot` class directly will raise an exception.
254+
255+
~~~~~ python
256+
from sr.robot3 import Robot
257+
258+
# This is not supported nor recommended.
259+
class MyRobot(Robot):
260+
...
261+
~~~~~
262+
263+
Subclassing like this can interfere with the general operating of the `Robot` object. Instead, we recommend using the examples above to wrap the existing `Robot` object.
264+
265+
</div>

0 commit comments

Comments
 (0)