com.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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.utils import calculate_crc_16
  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.com_manager = serial.Serial(port=self.port, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity, stopbits=self.stopbits, xonxoff=0)
  27. # if (self.com_manager is open):
  28. return True
  29. except SerialException:
  30. return False
  31. def send_16h(self, slave, addr, num, number_write, data):
  32. buf = [slave, 0x16, (addr >> 8) & 0xFF, addr & 0xFF, (num >> 8) & 0xFF, num & 0xFF, number_write] + data
  33. crc = calculate_crc_16(buf, len(buf))
  34. buf = buf + [crc & 0xFF, (crc >> 8) & 0xFF]
  35. self.com_manager.write(buf)
  36. def send(self, addr=0, command=0, param1=0, param0=0, data3=0, data2=0, data1=0, data0=0):
  37. buf = [addr, command, param1, param0, data3, data2, data1, data0]
  38. self.com_manager.write(buf)
  39. def reveive_env_version(self):
  40. sub_seq = list()
  41. try:
  42. data_count = self.com_manager.inWaiting()
  43. if data_count == 5:
  44. result = self.com_manager.read(data_count).hex()
  45. ptr = 0
  46. while ptr < len(result):
  47. sub_seq += [int('0x' + result[ptr:ptr + 2], 16)]
  48. ptr += 2
  49. else:
  50. return [0]
  51. except Exception as e:
  52. print(str(e))
  53. return sub_seq