integration_test.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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.feeder_queue: asyncio.Queue[int] = asyncio.Queue(self.config.feeder.max_num_cells)
  48. self.defeeder_queue: asyncio.Queue[DefeederMagazineConfig] = asyncio.Queue(self.config.defeeder.max_num_cells)
  49. # Initialize robot controller with all required arguments
  50. self.controller = RobotController(
  51. self.config,
  52. self.gpio,
  53. self.i2c,
  54. self.vision,
  55. self.pump_controller,
  56. self.feeder_queue,
  57. self.defeeder_queue
  58. )
  59. self.logger = logging.getLogger(__name__)
  60. self.logger.info("Initializing LoaderSystem")
  61. # Test stuff
  62. self.test_drop_slot = self.config.measurement_devices[0].slots[2]
  63. self.test_pickup_slot = self.config.measurement_devices[0].slots[3]
  64. # Use mock I2C device if debug is enabled
  65. self.i2c.initialize()
  66. self.logger.info(f"I2C initialized with {i2c_device_class.__name__}")
  67. self.pump_controller = PumpController(self.config, self.gpio)
  68. async def run(self):
  69. await self.controller.connect()
  70. await asyncio.gather(
  71. self._loader_loop(),
  72. self._poll_i2c_channels()
  73. )
  74. async def _poll_i2c_channels(self):
  75. while True:
  76. try:
  77. readings = await self.i2c.read_channels([1, 3, 4])
  78. for channel, value in readings.items():
  79. self.logger.debug(f"Channel {channel} reading: {value}")
  80. if channel == 3: # Pressure reading
  81. self.pump_controller.handle_tank_reading(value)
  82. if channel == 4:
  83. state = self.pump_controller.check_endeffector_state(value)
  84. self.controller.set_suction_state(state)
  85. except Exception as e:
  86. self.logger.error(f"Error polling I2C channels: {str(e)}")
  87. await asyncio.sleep(1) # Poll every second
  88. async def _loader_loop(self):
  89. while True:
  90. await wait_for_enter()
  91. # Feeding with MagDistributor
  92. ###########################
  93. self.logger.info("Picking up a cell from magazine and placing it into feeder using MagDistributor...")
  94. self.mag_distributor.mag_to_feeder()
  95. await self.feeder_queue.put(1)
  96. self.logger.info("Done.")
  97. await wait_for_enter()
  98. # Prepare Feeder Cell
  99. ##############################
  100. self.logger.info("Preparing feeder cell...")
  101. await self.controller.prepare_feeder_cell()
  102. self.logger.info("Done.")
  103. await wait_for_enter()
  104. # Feeder -> Slot
  105. ##############################
  106. self.logger.info("Picking up a cell from feeder and placing it into slot...")
  107. await self.controller.pick_cell_from_feeder()
  108. cell = Cell(id=1, status=CellStatus.WAITING)
  109. await self.controller.insert_cell_to_slot(cell, self.test_drop_slot)
  110. await wait_for_enter()
  111. # Slot -> Defeeder
  112. ##############################
  113. self.logger.info("Picking up a cell from slot and placing it into defeeder...")
  114. await self.controller.pick_cell_from_slot(self.test_pickup_slot)
  115. await self.controller.dropoff_cell()
  116. self.logger.info("Done.")
  117. await wait_for_enter()
  118. # Defeeding with MagDistributor
  119. ###########################
  120. self.logger.info("Defeeding a cell from feeder to magazine using MagDistributor...")
  121. self.mag_distributor.defeeder_to_mag(self.config.defeeder_magazines[0])
  122. self.logger.info("Done.")
  123. self.logger.info("\nPress Enter to repeat sequence (or Ctrl+C to exit)...")
  124. async def cleanup(self):
  125. self.logger.info("Cleaning up resources...")
  126. await self.controller.cleanup()
  127. self.gpio.cleanup()
  128. if __name__ == "__main__":
  129. loader_system = LoaderSystem()
  130. async def shutdown():
  131. loader_system.logger.info("Shutting down...")
  132. await loader_system.cleanup()
  133. sys.exit(0)
  134. def handle_signal(sig, frame):
  135. asyncio.get_event_loop().create_task(shutdown())
  136. signal.signal(signal.SIGINT, handle_signal)
  137. signal.signal(signal.SIGTERM, handle_signal)
  138. asyncio.run(loader_system.run())