Skip to content

Commit

Permalink
formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
shardros committed May 1, 2022
1 parent 1bd1d79 commit cc98b73
Show file tree
Hide file tree
Showing 8 changed files with 64 additions and 38 deletions.
4 changes: 2 additions & 2 deletions robot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@

from robot.wrapper import Robot, NoCameraPresent
from robot.greengiant import OUTPUT, INPUT, INPUT_ANALOG, INPUT_PULLUP
from robot.vision import MARKER_ARENA,MARKER_CUBE_WINKIE,MARKER_CUBE_GILLIKIN, MARKER_CUBE_QUADLING,MARKER_CUBE_MUNCHKIN, MARKER_DEFAULT, RoboConUSBCamera
from robot.vision import MARKER_ARENA, MARKER_CUBE_WINKIE, MARKER_CUBE_GILLIKIN, MARKER_CUBE_QUADLING, MARKER_CUBE_MUNCHKIN, MARKER_DEFAULT, RoboConUSBCamera

MINIUM_VERSION = (3, 6)
if sys.version_info <= MINIUM_VERSION:
raise ImportError("Expected python {} but instead got {}".format(
MINIUM_VERSION, sys.version_info))

__all__ = ["Robot", "NoCameraPresent", "OUTPUT", "INPUT", "INPUT_ANALOG",
"INPUT_PULLUP", "MARKER_ARENA","MARKER_CUBE_WINKIE","MARKER_CUBE_GILLIKIN", "MARKER_CUBE_QUADLING","MARKER_CUBE_MUNCHKIN", "MARKER_DEFAULT"]
"INPUT_PULLUP", "MARKER_ARENA", "MARKER_CUBE_WINKIE", "MARKER_CUBE_GILLIKIN", "MARKER_CUBE_QUADLING", "MARKER_CUBE_MUNCHKIN", "MARKER_DEFAULT"]
11 changes: 8 additions & 3 deletions robot/calibrate_camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@
KD = 5
K_READING_COUNTS = 0.5


def _get_reading():
while True:
try:
return R.see()[0].dist
except IndexError:
print("saw nothing")


def _get_reading_number(error):
result = int(K_READING_COUNTS / error)
result = abs(result)
Expand All @@ -30,6 +32,7 @@ def _get_reading_number(error):
result = 6
return result


R = robot.Robot()
result = {}

Expand Down Expand Up @@ -57,10 +60,12 @@ def _get_reading_number(error):
previous_error = error
error = TARGET - average_dist

print("Tried: {} got dist {} error: {}".format(value, average_dist, error))
print(" Max: {} min: {} range: {}".format(max(dists), min(dists), max(dists) - min(dists)))
print("Tried: {} got dist {} error: {}".format(
value, average_dist, error))
print(" Max: {} min: {} range: {}".format(
max(dists), min(dists), max(dists) - min(dists)))
print(" P = {} reading_counts {}".format(error * KP, reading_counts))

result[res] = (value, value)

pprint.pprint(result)
pprint.pprint(result)
9 changes: 6 additions & 3 deletions robot/cytron.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ def __init__(self, max_motor_voltage):

# because we care about heating effects in the motors, we have to scale by
# the square of the ratio
self.power_scaling_factor = (max_motor_voltage / _MAX_OUTPUT_VOLTAGE) ** 2
self.power_scaling_factor = (
max_motor_voltage / _MAX_OUTPUT_VOLTAGE) ** 2

self._percentages = [0, 0]
self._dir = [_DIR_PIN_1, _DIR_PIN_2]
Expand All @@ -65,7 +66,8 @@ def __init__(self, max_motor_voltage):
def __getitem__(self, index):
"""Returns the current PWM value in RC units. Adds a sign to represent"""
if index not in (1, 2):
raise IndexError(f"motor index must be in (1,2) but instead got {index}")
raise IndexError(
f"motor index must be in (1,2) but instead got {index}")

index -= 1
return self._percentages[index]
Expand All @@ -74,7 +76,8 @@ def __setitem__(self, index, percent):
"""Clamps input value, converts from percentage to wiring pi format and
sets a PWM format"""
if index not in (1, 2):
raise IndexError(f"motor index must be in (1,2) but instead got {index}")
raise IndexError(
f"motor index must be in (1,2) but instead got {index}")

index -= 1
percent = clamp(percent, -100, 100)
Expand Down
17 changes: 13 additions & 4 deletions robot/greengiant.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"""A set of constants and interfaces for controlling the green giant over I2C"""


def clamp(value, smallest, largest):
"""Return `value` if in bounds else returns the exceeded bound"""
return max(smallest, min(value, largest))


def _decrement_pin_index(index):
"""Validate then decrement the pin index.
Expand All @@ -17,6 +19,7 @@ def _decrement_pin_index(index):

return index


OUTPUT = "OUTPUT"
INPUT = "INPUT"
INPUT_ANALOG = "INPUT_ANALOG"
Expand Down Expand Up @@ -104,6 +107,7 @@ def read_high_low_data(bus, high_addr, low_addr):
class GreenGiantInternal(object):
"""Intertions for use with the user
not intended to be part of the robot API"""

def __init__(self, bus):
self._bus = bus
self.enabled_12v = False
Expand Down Expand Up @@ -151,7 +155,8 @@ def mode(self):
def mode(self, mode):
self._mode = mode
mask = _GG_GPIO_MASKS[mode]
self._bus.write_byte_data(_GG_I2C_ADDR, _GG_CONTROL_START + self._index, mask)
self._bus.write_byte_data(
_GG_I2C_ADDR, _GG_CONTROL_START + self._index, mask)

@property
def digital(self):
Expand All @@ -168,7 +173,8 @@ def digital(self, value):
f"requiring pin_mode {OUTPUT} but instead pin_mode is "
f"{self._mode}")

self._bus.write_byte_data(_GG_I2C_ADDR, _GG_DIGITAL_START + self._index, int(value))
self._bus.write_byte_data(
_GG_I2C_ADDR, _GG_DIGITAL_START + self._index, int(value))

@property
def analog(self):
Expand All @@ -182,9 +188,10 @@ def analog(self):
raw_adc_max = 0xFFC0

analog_addr = _GG_ANALOG_START + (self._index * 2)
raw_adc_value = read_high_low_data(self._bus, analog_addr, analog_addr + 1)
raw_adc_value = read_high_low_data(
self._bus, analog_addr, analog_addr + 1)

return (raw_adc_value / raw_adc_max) * self._adc_max
return (raw_adc_value / raw_adc_max) * self._adc_max

def __bool__(self):
"""Return a bool if in a digital mode or a float if in an analogue"""
Expand All @@ -197,6 +204,7 @@ def __bool__(self):

class GreenGiantGPIOPinList():
"""A list of pins indexed from 1"""

def __init__(self, bus, adc_max):
self._list = [GreenGiantGPIOPin(bus, i, adc_max)
for i in range(4)]
Expand All @@ -211,6 +219,7 @@ def __setitem__(self, index, value):

class GreenGiantPWM():
"""An object implementing a descriptor protocol to control the servos"""

def __init__(self, bus):
self._bus = bus

Expand Down
3 changes: 3 additions & 0 deletions robot/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
import logging

# Python 2.6's logging doesn't have NullHandler


class NullHandler(logging.Handler):
def emit(self, record):
pass


# Default to sending our log messages nowhere
logger = logging.getLogger("sr")
logger.addHandler(NullHandler())
1 change: 1 addition & 0 deletions robot/reset.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import robot.cytron as c
import robot.greengiant as gg


def reset():
"""Resets the robot components to their default state.
Used by Shepherd when the Stop button is pressed.
Expand Down
24 changes: 11 additions & 13 deletions robot/vision.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import robot.apriltags3 as AT



# TODO put all of the paths together
IMAGE_TO_SHEPHERD_PATH = "/home/pi/shepherd/shepherd/static/image.jpg"

Expand Down Expand Up @@ -101,10 +100,10 @@ class Capture(NamedTuple):

# MARKER_: Marker Data Types
# MARKER_TYPE_: Marker Types
MARKER_TYPE, MARKER_OFFSET, MARKER_COUNT, MARKER_SIZE, MARKER_COLOUR,MARKER_SPECIES = (
'type', 'offset', 'count', 'size', 'colour','species')
MARKER_ARENA,MARKER_CUBE_WINKIE,MARKER_CUBE_GILLIKIN,MARKER_CUBE_QUADLING,MARKER_CUBE_MUNCHKIN,MARKER_DEFAULT = "arena", "winkie", "gillikin","quadling","munchkin","default"
ARENA,CUBE = "arena","cube"
MARKER_TYPE, MARKER_OFFSET, MARKER_COUNT, MARKER_SIZE, MARKER_COLOUR, MARKER_SPECIES = (
'type', 'offset', 'count', 'size', 'colour', 'species')
MARKER_ARENA, MARKER_CUBE_WINKIE, MARKER_CUBE_GILLIKIN, MARKER_CUBE_QUADLING, MARKER_CUBE_MUNCHKIN, MARKER_DEFAULT = "arena", "winkie", "gillikin", "quadling", "munchkin", "default"
ARENA, CUBE = "arena", "cube"
# NOTE Data about each marker
# MARKER_OFFSET: Offset
# MARKER_COUNT: Number of markers of type that exist
Expand Down Expand Up @@ -352,7 +351,6 @@ def __init__(self,
bounding_box=True,
usb_stick=False,
send_to_sheep=False,

save=True):

super(PostProcessor, self).__init__()
Expand Down Expand Up @@ -402,12 +400,12 @@ def _draw_bounding_box(self, frame, detections):
polygon_is_closed,
colour,
thickness=self._bounding_box_thickness*3)
else:
cv2.polylines(frame,
[integer_corners],
polygon_is_closed,
colour,
thickness=self._bounding_box_thickness)
else:
cv2.polylines(frame,
[integer_corners],
polygon_is_closed,
colour,
thickness=self._bounding_box_thickness)

return frame

Expand Down Expand Up @@ -484,7 +482,7 @@ def __init__(self,
self.camera = camera

self.frames_to_postprocess = queue.Queue(max_queue_size)
self.post_processor = PostProcessor(self,zone = self.zone)
self.post_processor = PostProcessor(self, zone=self.zone)

def stop(self):
"""Cleanup to prevent leaking hardware resource"""
Expand Down
33 changes: 20 additions & 13 deletions robot/wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class to their respecitve classes
# this boot cycle. This is to highlight weird behaviour in the arena
COPY_STAT_FILE = "/tmp/usb_file_uploaded"


def setup_logging(level):
"""Display the just the message when logging events
Sets the logging level to `level`"""
Expand All @@ -43,6 +44,7 @@ def setup_logging(level):

class NoCameraPresent(Exception):
"""Camera not connected."""

def __str__(self):
return "No camera found."

Expand Down Expand Up @@ -73,7 +75,8 @@ def __init__(self,
# check if copy stat file exists and read it if it does then delete it
try:
with open(COPY_STAT_FILE, "r") as f:
_logger.info("Robot code copied %s from USB\n", f.read().strip())
_logger.info("Robot code copied %s from USB\n",
f.read().strip())
os.remove(COPY_STAT_FILE)
except IOError:
pass
Expand All @@ -92,8 +95,8 @@ def __init__(self,
self.mode = start_data['mode']
else:
_logger.warning("Robot initalized but usercode running before"
"`robot.wait_start`. Robot will not wait for the "
"start button until `robot.wait_start` is called.")
"`robot.wait_start`. Robot will not wait for the "
"start button until `robot.wait_start` is called.")

def subsystem_init(self, camera):
"""Allows for initalisation of subsystems after instansating `Robot()`
Expand All @@ -117,7 +120,6 @@ def subsystem_init(self, camera):

self._vision = vision.Vision(self.zone, camera=self.camera)


def report_hardware_status(self):
"""Print out a nice log message at the start of each robot init with
the hardware status"""
Expand All @@ -132,13 +134,14 @@ def report_hardware_status(self):
"changing for a charged battery")

if self._gg_version != 3:
self._warnings.append("Green Giant version not 3 but instead {}".format(self._gg_version))

camera_type_str = "Camera: {}".format(self.camera.__class__.__name__)
self._warnings.append(
"Green Giant version not 3 but instead {}".format(self._gg_version))

camera_type_str = "Camera: {}".format(
self.camera.__class__.__name__)

#Adds the secret poem every now and then!
if random.randint(0,100) == 1:
# Adds the secret poem every now and then!
if random.randint(0, 100) == 1:
_logger.info("Today your task is a challenging one")
_logger.info("Gifts for the wizard and deliveries to run")
_logger.info("But due to the unfortunate timing you can not go")
Expand All @@ -147,14 +150,17 @@ def report_hardware_status(self):
_logger.info("Starting in your home (where ever it is found)")
_logger.info("Then taking gifts from your robots zone ")
_logger.info("Delivering it to the wizard on its own")
_logger.info("To the road is good and to the emerald palace is ideal ")
_logger.info("And if in another country you get some but a point they will steal")
_logger.info(
"To the road is good and to the emerald palace is ideal ")
_logger.info(
"And if in another country you get some but a point they will steal")
_logger.info("There are many things that are to be considered")
_logger.info("But remember to bring your gifts for the wizard")

# print report of hardware
_logger.info("------HARDWARE REPORT------")
_logger.info("Time: %s", datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
_logger.info("Time: %s", datetime.now().strftime(
'%Y-%m-%d %H:%M:%S'))
_logger.info("Patch Version: 0")
_logger.info(battery_str)
_logger.info("ADC Max: %.2fv", self._adc_max)
Expand Down Expand Up @@ -267,7 +273,8 @@ def wait_start(self):

if self.startfifo is None:
self._start_pressed = True
_logger.info("No startfifo so using defaults (Zone: {})".format(self.zone))
_logger.info(
"No startfifo so using defaults (Zone: {})".format(self.zone))
return

blink_thread = threading.Thread(target=self._wait_start_blink)
Expand Down

0 comments on commit cc98b73

Please sign in to comment.