com.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. '''
  4. @文件 :com.py
  5. @时间 :2022/11/14 17:28:23
  6. @作者 :None
  7. @版本 :1.0
  8. @说明 :modbus 485驱动
  9. '''
  10. import serial.tools.list_ports
  11. import serial
  12. from serial.serialutil import SerialException
  13. from utils.modbus import modbus_rtu
  14. class ComMaster:
  15. def __init__(self):
  16. super(ComMaster, self).__init__()
  17. self.master = None
  18. def set_com(self, port, baudrate, bytesize, parity, stopbits):
  19. self.port = port
  20. self.baudrate = baudrate
  21. self.bytesize = bytesize
  22. self.parity = parity
  23. self.stopbits = stopbits
  24. def open_device(self):
  25. try:
  26. self.master = modbus_rtu.RtuMaster(serial.Serial(port=self.port, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity, stopbits=self.stopbits, xonxoff=0))
  27. self.master.set_timeout(1)
  28. self.master.set_verbose(True)
  29. return True
  30. except SerialException:
  31. return False
  32. def send(self, slave, function_code, starting_address, byte_count):
  33. ret = self.master.execute(slave, function_code, starting_address, byte_count)
  34. print(list(ret))
  35. return ret