mag_to_feeder_moving_sequence.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import time
  2. from robot_control.src.robot.mag_distributor import MagDistributor
  3. from robot_control.src.api.gpio import PiGPIO
  4. from robot_control.src.utils.config import ConfigParser
  5. import asyncio
  6. import time
  7. import sys
  8. # Assign two servo pins (update as needed)
  9. SERVO_PINS = {1: 6, 2: 13} # Example: GPIO6 and GPIO13
  10. gpio = PiGPIO([], list(SERVO_PINS.values()))
  11. # Load config and create mag distributor for stepper control
  12. try:
  13. config_parser = ConfigParser()
  14. mag_dist = MagDistributor(config_parser.config, gpio)
  15. except Exception as e:
  16. print(f"Error: Could not initialize mag distributor: {e}")
  17. sys.exit(1)
  18. def move_servo(servo_number, angle, speed):
  19. """Move servo using PiGPIO's smooth function"""
  20. pin = SERVO_PINS.get(servo_number)
  21. if pin is None:
  22. print(f"Servo {servo_number} not configured.")
  23. return False
  24. print(f"S {servo_number} {angle} {speed} - Moving servo {servo_number} (GPIO {pin}) to {angle}° at speed {speed}")
  25. try:
  26. gpio.set_servo_angle_smooth(pin, angle, speed)
  27. print("Servo move complete.")
  28. return True
  29. except Exception as e:
  30. print(f"Error moving servo: {e}")
  31. return False
  32. def move_stepper(pos_mm, rot_deg, speed=7): # Increased default from 100 to 300 mm/min
  33. """Move stepper motor using mag distributor"""
  34. print(f"M {pos_mm} {rot_deg} {speed if speed else ''} - Moving stepper to position {pos_mm}mm, rotation {rot_deg}° at {speed} mm/min")
  35. try:
  36. if speed is not None:
  37. # Convert speed to step delay if needed
  38. step_delay = mag_dist._speed_to_step_delay(speed)
  39. mag_dist.move_mag_distributor_at_pos(pos_mm, rot_deg, step_delay)
  40. else:
  41. mag_dist.move_mag_distributor_at_pos(pos_mm, rot_deg)
  42. print("Stepper move complete.")
  43. return True
  44. except Exception as e:
  45. print(f"Error moving stepper: {e}")
  46. return False
  47. async def home_system():
  48. """Home the mag distributor system"""
  49. print("H - Starting homing sequence...")
  50. try:
  51. await mag_dist.home()
  52. print("Homing completed successfully.")
  53. return True
  54. except Exception as e:
  55. print(f"Homing failed: {e}")
  56. return False
  57. def execute_sequence():
  58. """Execute the predefined sequence of movements"""
  59. print("Starting Mag_to_Dist_to_Rob sequence...")
  60. print("=" * 50)
  61. # Define the sequence of commands (including homing at the start)
  62. commands = [
  63. ("S", 1, 60, 1000), # S 1 40 1000
  64. ("H",), # Homing sequence
  65. ("M", -222, 0, 10), # M -223 0 200 (increased speed from 100 to 200)
  66. ("S", 1, 5, 250), # S 1 0 250
  67. ("S", 1, 60, 250), # S 1 40 250
  68. ("M", -46, 0, 10), # M -46 0 150 (increased speed from 100 to 150)
  69. ("S", 2, 15, 500), # S 2 35 250
  70. ("S", 1, 153, 200), # S 1 153 200
  71. ("S", 2, 88, 500), # S 2 90 1000
  72. ("S", 2, 130, 150), # S 2 120 150
  73. ("S", 1, 60, 1000), # S 1 40 1000
  74. # Defeeder pos -6 angle 120
  75. ]
  76. success_count = 0
  77. total_commands = len(commands)
  78. for i, command in enumerate(commands, 1):
  79. print(f"\nStep {i}/{total_commands}:")
  80. if command[0] == "H": # Homing command
  81. success = asyncio.run(home_system())
  82. elif command[0] == "S": # Servo command
  83. _, servo_num, angle, speed = command
  84. success = move_servo(servo_num, angle, speed)
  85. elif command[0] == "M": # Motor/stepper command
  86. _, pos_mm, rot_deg, speed = command
  87. success = move_stepper(pos_mm, rot_deg, speed)
  88. else:
  89. print(f"Unknown command type: {command[0]}")
  90. success = False
  91. if success:
  92. success_count += 1
  93. else:
  94. print(f"Command {i} failed!")
  95. response = input("Continue with next command? (y/n): ").strip().lower()
  96. if response != 'y':
  97. print("Sequence aborted by user.")
  98. break
  99. # Wait 1 second between commands (except for the last one)
  100. if i < total_commands:
  101. print("Waiting 1 second...")
  102. time.sleep(2)
  103. print("\n" + "=" * 50)
  104. print(f"Sequence completed: {success_count}/{total_commands} commands successful")
  105. return success_count == total_commands
  106. def main():
  107. """Main function"""
  108. print("Mag_to_Dist_to_Rob - Automated Movement Sequence with Homing")
  109. print("This script will execute a predefined sequence starting with homing.")
  110. print("\nSequence includes:")
  111. print("1. Homing sequence (H)")
  112. print("2. Servo and stepper movements as specified")
  113. print("\nPress Enter to start the sequence, or Ctrl+C to exit...")
  114. try:
  115. input()
  116. success = execute_sequence()
  117. if success:
  118. print("\n✓ All movements completed successfully!")
  119. else:
  120. print("\n⚠ Some movements failed. Check the output above.")
  121. except KeyboardInterrupt:
  122. print("\n\nSequence interrupted by user.")
  123. except Exception as e:
  124. print(f"\nUnexpected error: {e}")
  125. finally:
  126. # Cleanup
  127. try:
  128. gpio.cleanup()
  129. print("GPIO cleanup completed.")
  130. except:
  131. pass
  132. if __name__ == "__main__":
  133. main()