integration_test.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import signal
  2. import sys
  3. import asyncio
  4. import logging
  5. from robot_control.src.robot.controller import RobotController, Cell, CellStatus
  6. from robot_control.src.utils.config import ConfigParser, DefeederMagazineConfig
  7. from robot_control.src.utils.logging import setup_logging
  8. from robot_control.src.vision.datamatrix import DataMatrixReader
  9. from robot_control.src.api.i2c_handler import I2C, MockI2C
  10. from robot_control.src.vendor.mcp3428 import MCP3428
  11. from robot_control.src.robot.pump_controller import PumpController
  12. from robot_control.src.api.gpio import PiGPIO, MockGPIO
  13. from robot_control.src.robot.mag_distributor import MagDistributor
  14. """
  15. This is a test script for the loader system.
  16. It initializes the robot controller, vision system, and I2C handler,
  17. """
  18. async def wait_for_enter():
  19. # Use asyncio.Event to coordinate between input and async code
  20. event = asyncio.Event()
  21. def input_callback():
  22. logging.info("Press Enter to continue...")
  23. input() # Wait for Enter
  24. event.set()
  25. # Run input in a separate thread to not block the event loop
  26. loop = asyncio.get_running_loop()
  27. await loop.run_in_executor(None, input_callback)
  28. await event.wait()
  29. class LoaderSystem:
  30. def __init__(self):
  31. self.config = ConfigParser().config
  32. setup_logging(self.config) # Set up logging with config
  33. gpio_config = self.config.gpio
  34. if gpio_config.debug:
  35. self.gpio = MockGPIO()
  36. else:
  37. self.gpio = PiGPIO(out_pins=[gpio_config.pump_pin, gpio_config.valve_pin])
  38. # Initialize vision system
  39. self.vision = DataMatrixReader(self.config.vision)
  40. # Initialize pump controller
  41. self.pump_controller = PumpController(self.config, self.gpio)
  42. # Initialize magazine distributor
  43. self.mag_distributor = MagDistributor(self.config, self.gpio)
  44. i2c_device_class = MCP3428 if not self.config.i2c.debug else MockI2C
  45. self.i2c = I2C(i2c_device_class)
  46. self.i2c.initialize()
  47. self.logger.info(f"I2C initialized with {i2c_device_class.__name__}")
  48. self.feeder_queue: asyncio.Queue[int] = asyncio.Queue(self.config.feeder.max_num_cells)
  49. self.defeeder_queue: asyncio.Queue[DefeederMagazineConfig] = asyncio.Queue(self.config.defeeder.max_num_cells)
  50. # Initialize robot controller with all required arguments
  51. self.controller = RobotController(
  52. self.config,
  53. self.gpio,
  54. self.i2c,
  55. self.vision,
  56. self.pump_controller,
  57. self.feeder_queue,
  58. self.defeeder_queue
  59. )
  60. self.logger = logging.getLogger(__name__)
  61. self.logger.info("Initializing LoaderSystem")
  62. self.vision.initialize()
  63. # Test stuff
  64. self.test_drop_slot = self.config.measurement_devices[0].slots[2]
  65. self.test_pickup_slot = self.config.measurement_devices[0].slots[3]
  66. # Use mock I2C device if debug is enabled
  67. self.i2c.initialize()
  68. self.logger.info(f"I2C initialized with {i2c_device_class.__name__}")
  69. self.pump_controller = PumpController(self.config, self.gpio)
  70. async def run(self):
  71. await self.controller.connect()
  72. await asyncio.gather(
  73. self._loader_loop(),
  74. self._poll_i2c_channels()
  75. )
  76. async def _poll_i2c_channels(self):
  77. while True:
  78. try:
  79. readings = await self.i2c.read_channels([1, 3, 4])
  80. for channel, value in readings.items():
  81. self.logger.debug(f"Channel {channel} reading: {value}")
  82. if channel == 3: # Pressure reading
  83. self.pump_controller.handle_tank_reading(value)
  84. if channel == 4:
  85. state = self.pump_controller.check_endeffector_state(value)
  86. self.controller.set_suction_state(state)
  87. except Exception as e:
  88. self.logger.error(f"Error polling I2C channels: {str(e)}")
  89. await asyncio.sleep(1) # Poll every second
  90. async def _loader_loop(self):
  91. while True:
  92. await wait_for_enter()
  93. # Feeding with MagDistributor
  94. ###########################
  95. self.logger.info("Picking up a cell from magazine and placing it into feeder using MagDistributor...")
  96. self.mag_distributor.mag_to_feeder()
  97. await self.feeder_queue.put(1)
  98. self.logger.info("Done.")
  99. await wait_for_enter()
  100. # Prepare Feeder Cell
  101. ##############################
  102. self.logger.info("Preparing feeder cell...")
  103. await self.controller.prepare_feeder_cell()
  104. self.logger.info("Done.")
  105. await wait_for_enter()
  106. # Feeder -> Slot
  107. ##############################
  108. self.logger.info("Picking up a cell from feeder and placing it into slot...")
  109. await self.controller.pick_cell_from_feeder()
  110. cell = Cell(id=1, status=CellStatus.WAITING)
  111. await self.controller.insert_cell_to_slot(cell, self.test_drop_slot)
  112. await wait_for_enter()
  113. # Slot -> Defeeder
  114. ##############################
  115. self.logger.info("Picking up a cell from slot and placing it into defeeder...")
  116. await self.controller.pick_cell_from_slot(self.test_pickup_slot)
  117. await self.controller.dropoff_cell()
  118. self.logger.info("Done.")
  119. await wait_for_enter()
  120. # Defeeding with MagDistributor
  121. ###########################
  122. self.logger.info("Defeeding a cell from feeder to magazine using MagDistributor...")
  123. self.mag_distributor.defeeder_to_mag(self.config.defeeder_magazines[0])
  124. self.logger.info("Done.")
  125. self.logger.info("\nPress Enter to repeat sequence (or Ctrl+C to exit)...")
  126. async def cleanup(self):
  127. self.logger.info("Cleaning up resources...")
  128. await self.controller.cleanup()
  129. self.gpio.cleanup()
  130. if __name__ == "__main__":
  131. loader_system = LoaderSystem()
  132. async def shutdown():
  133. loader_system.logger.info("Shutting down...")
  134. await loader_system.cleanup()
  135. sys.exit(0)
  136. def handle_signal(sig, frame):
  137. asyncio.get_event_loop().create_task(shutdown())
  138. signal.signal(signal.SIGINT, handle_signal)
  139. signal.signal(signal.SIGTERM, handle_signal)
  140. asyncio.run(loader_system.run())