fubo_pneumatic_finger.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. 'release': 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. return self.ser.read()
  64. def status(self):
  65. status = {"is_connected": self.is_connected}
  66. return status
  67. def close(self):
  68. if self.ser:
  69. self.ser.close()
  70. self.is_connected = False
  71. return {"is_connected": self.is_connected}