2
0

fubo_pneumatic_finger.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. '''
  2. @Author : liujunshen
  3. @Ide : vscode
  4. @File : fubo_pneumatic_finger.py
  5. @Time : 2023/04/03 16:49:11
  6. '''
  7. import logging
  8. import time
  9. import serial
  10. from serial.tools.list_ports import comports
  11. logger = logging.getLogger(__name__)
  12. def get_serial_ports():
  13. """获取可选端口"""
  14. ports = list(comports(include_links=False))
  15. available_ports_list = [port.device for port in ports]
  16. return available_ports_list
  17. class FuboPneumaticFingerClient:
  18. """富伯客户端"""
  19. COMMAND_TABLE = {
  20. 'rest': b"R",
  21. 'cylinder': b"C",
  22. 'ball': b"B",
  23. 'flex': b"F",
  24. 'double': b"D",
  25. 'treble': b"T",
  26. 'extend': b"E",
  27. }
  28. def __init__(self, init_params=None):
  29. self.baud_rate = 9600
  30. self.data_bite = 8
  31. self.timeout = 1
  32. self.stop_bit = serial.STOPBITS_ONE # 停止位
  33. self.parity_bit = serial.PARITY_NONE # 校验位
  34. self.is_connected = False
  35. self.ser = None # 连接对象
  36. self.port = "COM 4"
  37. if init_params:
  38. self.port = init_params["port"]
  39. self.connect()
  40. def __del__(self):
  41. self.ser.close()
  42. def connect(self):
  43. try:
  44. self.ser = serial.Serial(port=self.port,
  45. baudrate=self.baud_rate,
  46. parity=self.parity_bit,
  47. stopbits=self.stop_bit,
  48. timeout=self.timeout)
  49. if self.ser.is_open:
  50. self.is_connected = True
  51. logger.info("connect")
  52. return 1
  53. else:
  54. self.is_connected = False
  55. logger.warning("open failed")
  56. return 0
  57. except OSError as e:
  58. warning_info = f"pneumatic finger connect failed: {e}"
  59. logger.warning(warning_info)
  60. return 0
  61. def start(self, command):
  62. self.ser.write(self.COMMAND_TABLE[command])
  63. def status(self):
  64. status = {"is_connected": self.is_connected}
  65. return status
  66. def close(self):
  67. if self.ser:
  68. self.ser.close()
  69. self.is_connected = False
  70. return {"is_connected": self.is_connected}