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_get.py 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #!/usr/bin/env python
  2. # scripts/examples/simple_tcp_client.py
  3. import fcntl
  4. import sys
  5. import socket
  6. import struct
  7. from serial import Serial
  8. from serial.serialutil import SerialException
  9. from umodbus.client.serial import rtu
  10. import json
  11. from db.db import sql
  12. s = Serial('/dev/ttyUSB0',19200)
  13. try:
  14. s.open()
  15. except SerialException:
  16. print('already open')
  17. BOOLEAN=1000
  18. FLOAT=500
  19. INT=1250
  20. def read_digital():
  21. global req_adu
  22. global sql
  23. global s
  24. start_address, end_address = sql(
  25. f"SELECT start_address, end_address FROM var_type
  26. WHERE slabel LIKE 'D';")
  27. res = []
  28. # digital - boolean
  29. req_adu = rtu.read_coils(
  30. slave_id=1,
  31. starting_address=1,
  32. quantity=1)
  33. resp = rtu.send_message(req_adu, s)
  34. address = -1
  35. try:
  36. for address in range(0, BOOLEAN, 1):
  37. res[address+1] = (resp[address] > 0)
  38. except KeyError as e:
  39. print(e)
  40. res[address] = False
  41. except IndexError:
  42. print(address)
  43. return res
  44. def read_analog():
  45. global req_adu
  46. global sql
  47. global s
  48. start_address, end_address = sql(
  49. f"SELECT start_address, end_address FROM var_type
  50. WHERE slabel LIKE 'A';")
  51. # analog - float
  52. for address in range(1, end_address - start_address, 125):
  53. req_adu = rtu.read_holding_registers(
  54. slave_id=1,
  55. starting_address=start_address + address,
  56. quantity=125)
  57. resp = rtu.send_message(req_adu, s)
  58. for n in range(125):
  59. try:
  60. res[address + n] = int(resp[n]) / 10
  61. except Exception as e:
  62. print(e)
  63. res[address + n] = 0.
  64. return res
  65. def read_int():
  66. global req_adu
  67. global sql
  68. global s
  69. res = []
  70. start_address, end_address = sql(
  71. f"SELECT start_address, end_address FROM var_type
  72. WHERE slabel LIKE 'I';")
  73. # integer - int
  74. for address in range(1, end_address - start_address, 125):
  75. req_adu = rtu.read_coils(
  76. slave_id=1,
  77. starting_address=start_address + address,
  78. quantity=125)
  79. resp = rtu.send_message(req_adu, s)
  80. for n in range(125):
  81. try:
  82. res[address + n] = int(resp[n])
  83. except KeyError as e:
  84. print(e)
  85. res[address + n] = 0
  86. return res
  87. s.close()
  88. sys.exit(0)