ioext.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. #!/usr/bin/python3 -u
  2. #
  3. import serial
  4. from time import sleep
  5. import os
  6. import sys
  7. import paho.mqtt.client as mqtt
  8. import json
  9. from datetime import datetime
  10. # --- CONFIGURATION ---
  11. import config
  12. # --- END CONFIGURATION ---
  13. # --- GLOBAL VARS ---
  14. noReceiveCount = 0 # increase everytime the serial readline times out (1s timeout)
  15. #getStatusCount = 0 # used as heartbeat, get status every 30s
  16. verbose = False
  17. debug = False
  18. quiet = True
  19. lastState_P2 = None
  20. lastState_P3 = None
  21. lastState_P4 = None
  22. # --- END GLOBAL VARS ---
  23. if len(sys.argv) >= 2:
  24. if sys.argv[1] == "-q":
  25. verbose = False
  26. debug = False
  27. quiet = True
  28. #print("VERBOSE=ON")
  29. elif sys.argv[1] == "-v":
  30. verbose = True
  31. debug = False
  32. quiet = False
  33. #print("VERBOSE=ON")
  34. elif sys.argv[1] == "-d":
  35. verbose = True
  36. quiet = False
  37. debug = True
  38. #print("DEBUG=ON")
  39. def on_connect(client, userdata, flags, rc):
  40. if not quiet:
  41. print("MQTT connected with result code " + str(rc))
  42. #client.subscribe(mqtt_topic_cmd)
  43. #def on_message(client, userdata, msg):
  44. # if msg.topic == mqtt_topic_cmd:
  45. # payload = msg.payload.decode('ascii')
  46. # if payload == "status" or payload == "get conf" or payload == "clear" or payload == "open door" or payload.startswith("set prof ") or payload.startswith("set conf "):
  47. # if verbose:
  48. # print("serCmd: " + payload)
  49. # serCmd = payload + '\n'
  50. # ser.write(serCmd.encode('ascii'))
  51. # elif verbose:
  52. # print("unknown command:", payload)
  53. def touch(fname, times=None):
  54. with open(fname, 'a'):
  55. os.utime(fname, times)
  56. mqttc = mqtt.Client()
  57. mqttc.on_connect = on_connect
  58. #mqttc.on_disconnect = on_disconnect
  59. #mqttc.on_message = on_message
  60. mqttc.username_pw_set(config.mqtt_user, config.mqtt_password)
  61. mqttc.connect(config.mqtt_server, config.mqtt_port, 60)
  62. mqttc.loop_start()
  63. ser = serial.Serial(port=config.serialPort,
  64. baudrate = config.serialBaud,
  65. parity=serial.PARITY_NONE,
  66. stopbits=serial.STOPBITS_ONE,
  67. bytesize=serial.EIGHTBITS,
  68. timeout=config.serialTimeout)
  69. try:
  70. while True:
  71. ##ser.flushInput() ## attention truncates incoming strings if there is little time between them
  72. #read buffer until cr/lf
  73. serLine = ser.readline().strip()
  74. # catch exception on invalid char coming in: UnicodeDecodeError: 'ascii' codec can't decode byte 0xf4 in position 6: ordinal not in range(128)
  75. try:
  76. serLine = serLine.decode('ascii')
  77. except:
  78. serLine = ""
  79. # if there came something in...
  80. if(serLine):
  81. noReceiveCount = 0
  82. # touch status file if configured
  83. try:
  84. config.statusFile
  85. except:
  86. if debug:
  87. print("statusFile not defined")
  88. else:
  89. if config.statusFile is not None and config.statusFile != "":
  90. try:
  91. touch(config.statusFile)
  92. except:
  93. if debug:
  94. print("ERROR - could not touch statusFile '" + str(config.statusFile) + "'")
  95. else:
  96. if debug:
  97. print("statusFile not configured")
  98. if verbose:
  99. print ('RX: ' + repr(serLine)) #Echo the serial buffer bytes up to the CRLF back to screen
  100. mqttc.publish(config.mqtt_base_topic + "/RX", str(serLine), qos=0, retain=False)
  101. # digital input P2
  102. if serLine.startswith('P2='):
  103. newState = None
  104. if serLine == "P2=L":
  105. newState = "OFF"
  106. elif serLine == "P2=H":
  107. newState = "ON"
  108. if newState is not None and (lastState_P2 != newState or not config.P2_MQTT_SendOnlyIfValueChanged):
  109. lastState_P2 = newState
  110. mqttc.publish(config.P2_MQTT_Topic, newState, qos=0, retain=config.P2_MQTT_SendRetained)
  111. if config.P2_MQTT_SendLastUpdate:
  112. mqttc.publish(config.P2_MQTT_Topic + "_lastUpdate", datetime.now().isoformat(), qos=0, retain=config.P2_MQTT_SendRetained)
  113. # digital input P3
  114. if serLine.startswith('P3='):
  115. newState = None
  116. if serLine == "P3=L":
  117. newState = "OFF"
  118. elif serLine == "P3=H":
  119. newState = "ON"
  120. if newState is not None and (lastState_P3 != newState or not config.P3_MQTT_SendOnlyIfValueChanged):
  121. lastState_P3 = newState
  122. mqttc.publish(config.P3_MQTT_Topic, newState, qos=0, retain=config.P3_MQTT_SendRetained)
  123. if config.P3_MQTT_SendLastUpdate:
  124. mqttc.publish(config.P3_MQTT_Topic + "_lastUpdate", datetime.now().isoformat(), qos=0, retain=config.P3_MQTT_SendRetained)
  125. # digital input P4
  126. if serLine.startswith('P4='):
  127. newState = None
  128. if serLine == "P4=L":
  129. newState = "OFF"
  130. elif serLine == "P4=H":
  131. newState = "ON"
  132. if newState is not None and (lastState_P4 != newState or not config.P4_MQTT_SendOnlyIfValueChanged):
  133. lastState_P4 = newState
  134. mqttc.publish(config.P4_MQTT_Topic, newState, qos=0, retain=config.P4_MQTT_SendRetained)
  135. if config.P4_MQTT_SendLastUpdate:
  136. mqttc.publish(config.P4_MQTT_Topic + "_lastUpdate", datetime.now().isoformat(), qos=0, retain=config.P4_MQTT_SendRetained)
  137. # DHT TH sensor
  138. # {"T":26.60,"H":36}
  139. if serLine.startswith('{"T":'):
  140. th = json.loads(serLine)
  141. t = round(float(th["T"]), 1)
  142. h = int(th["H"])
  143. if t >= -20 and t <= 50:
  144. mqttc.publish(config.DHT22_MQTT_Topic_Temp, str(t), qos=0, retain=config.DHT22_MQTT_SendRetained)
  145. if h >= 0 and h <= 100:
  146. mqttc.publish(config.DHT22_MQTT_Topic_Hum, str(h), qos=0, retain=config.DHT22_MQTT_SendRetained)
  147. if config.DHT22_MQTT_SendLastUpdate:
  148. mqttc.publish(config.DHT22_MQTT_Topic_Temp + "_lastUpdate", datetime.now().isoformat(), qos=0, retain=config.DHT22_MQTT_SendRetained)
  149. # nothing came in this time...
  150. else:
  151. noReceiveCount += 1
  152. if debug:
  153. print("noReceiveCount=" + str(noReceiveCount))
  154. # quit script if nothing has been received for some time - will be restarted by systemd
  155. if noReceiveCount >= config.quitOnNoReceiveTimeout:
  156. quit()
  157. except KeyboardInterrupt:
  158. print('\n')