Projet de remplacement du "RPiPasserelle" d'Otec.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

modbus.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/env python3
  2. from serial import Serial
  3. from serial.serialutil import SerialException
  4. from umodbus.client.serial import rtu
  5. import umodbus
  6. from pprint import pprint
  7. from .config import config
  8. serial_conn = None
  9. def connect():
  10. global serial_conn
  11. if serial_conn is None:
  12. print('Connecting to serial port *{}*'.format(
  13. config.get('heatpump', 'serial_port')))
  14. serial_conn = Serial(
  15. port=config.get('heatpump', 'serial_port'),
  16. baudrate=config.get('heatpump', 'baudrate'),
  17. bytesize=8,
  18. parity='N',
  19. stopbits=1,
  20. timeout=10)
  21. if serial_conn.open is False:
  22. print('Opening serial port')
  23. serial_conn.open()
  24. return serial_conn
  25. def read_coils(start, end):
  26. global serial_con
  27. connect()
  28. res = []
  29. address = -1
  30. qty = -1
  31. try:
  32. for address in range(start, end + 1, 125):
  33. qty = 125 if (end - address) >= 125 else (end - address)
  34. if not qty:
  35. break
  36. req_adu = rtu.read_coils(
  37. slave_id=1,
  38. starting_address=address,
  39. quantity=qty)
  40. resp = rtu.send_message(req_adu, serial_conn)
  41. res.extend(resp)
  42. except umodbus.exceptions.IllegalDataAddressError as e:
  43. print(e)
  44. print(f'{address} {qty}')
  45. return res
  46. def read_holding_registers(start, end):
  47. global serial_conn
  48. connect()
  49. res = []
  50. address = -1
  51. qty = -1
  52. try:
  53. for address in range(start, end + 1, 125):
  54. qty = 125 if (end - address) >= 125 else (end - address)
  55. if not qty:
  56. break
  57. req_adu = rtu.read_holding_registers(
  58. slave_id=1,
  59. starting_address=address,
  60. quantity=qty)
  61. resp = rtu.send_message(req_adu, serial_conn)
  62. res.extend(resp)
  63. except umodbus.exceptions.IllegalDataAddressError as e:
  64. print(e)
  65. print(f'{address} {qty}')
  66. return res
  67. if __name__ == '__main__':
  68. resp = read_holding_registers(1, 5000)
  69. #pprint(resp)
  70. print(len(resp))
  71. resp = read_coils(1, 2000)
  72. #pprint(resp)
  73. print(len(resp))