import asyncio import logging from robot_control.src.robot.controller import RobotController from robot_control.src.utils.config import ConfigParser from robot_control.src.vision.datamatrix import DataMatrixReader from robot_control.src.api.i2c_handler import I2C, MockI2C from robot_control.src.vendor.mcp3428 import MCP3428 from robot_control.src.robot.pump_controller import PumpController from robot_control.src.api.gpio import PiGPIO, MockGPIO from robot_control.src.utils.logging import setup_logging class LoaderSystem: def __init__(self): self.config = ConfigParser().config setup_logging(self.config) gpio_config = self.config.gpio if gpio_config.debug: self.gpio = MockGPIO() else: self.gpio = PiGPIO(out_pins=[gpio_config.pump_pin, gpio_config.valve_pin]) self.logger = logging.getLogger(__name__) self.vision = DataMatrixReader(self.config.vision) self.logger.info("Initializing LoaderSystem") self.vision.initialize() # Use mock I2C device if debug is enabled i2c_device_class = MCP3428 if not self.config.i2c.debug else MockI2C self.i2c = I2C(i2c_device_class) self.i2c.initialize() self.logger.info(f"I2C initialized with {i2c_device_class.__name__}") self.pump_controller = PumpController(self.config, self.gpio) # Pass all hardware interfaces to the controller self.controller = RobotController( self.config, self.gpio, self.i2c, self.vision, self.pump_controller ) async def run(self): await self.controller.connect() try: await asyncio.gather( self._loader_loop(), self._poll_i2c_channels() ) finally: self.cleanup() self.logger.info("Cleaning up resources...") async def _poll_i2c_channels(self): while True: try: readings = await self.i2c.read_channels([1, 3, 4]) for channel, value in readings.items(): self.logger.debug(f"Channel {channel} reading: {value}") if channel == 3: # Pressure reading self.pump_controller.handle_tank_reading(value) if channel == 4: state = self.pump_controller.check_endeffector_state(value) self.controller.set_suction_state(state) except Exception as e: self.logger.error(f"Error polling I2C channels: {str(e)}") await asyncio.sleep(1) # Poll every second async def _loader_loop(self): """ Main loop for the loader system. Orchestrates cell preparation, slot filling, and measurement processing. """ while True: await asyncio.sleep(0.1) # avoid busy loop while True: # Prepare a cell in the feeder (returns True if a cell is ready) if not await self.controller.prepare_feeder_cell(): break # Fill the next free slot (returns True if a cell was placed) if not await self.controller.fill_next_free_slot(): break # Check for completed measurements and sort cell await self.controller.process_finished_measurement() def cleanup(self): self.gpio.cleanup() # Ensure PumpController cleans up gpio if __name__ == "__main__": loader_system = LoaderSystem() asyncio.run(loader_system.run())