Module: MQTT <--> Powerplug Enegenie
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

powerplug.py 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import config
  2. import logging
  3. import paho.mqtt.client as mqtt
  4. import report
  5. import subprocess
  6. import time
  7. try:
  8. from config import APP_NAME as ROOT_LOGGER_NAME
  9. except ImportError:
  10. ROOT_LOGGER_NAME = 'root'
  11. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild('main')
  12. class sispmctl(object):
  13. AMP_CHANNEL = 0
  14. def __init__(self, mqtt_client):
  15. logger.info("Starting sispmctl module...")
  16. self.__mqtt_client__ = mqtt_client
  17. self.__state__ = [False, False, False, False]
  18. self.__state_requests__ = [{}, {}, {}, {}]
  19. try:
  20. out_txt = subprocess.check_output(["sudo", "sispmctl", "-f", "all"]).decode('UTF-8')
  21. except subprocess.CalledProcessError as grepexc:
  22. logger.error("sispm error code %d", grepexc.returncode)
  23. else:
  24. logger.info('sispmctl all channels switched off')
  25. self.publish_states()
  26. def __filter_output_parameter__(self, output):
  27. try:
  28. return int(output)
  29. except ValueError:
  30. return output
  31. def set_out_state(self, output, state):
  32. if output == "all":
  33. if self.__state__ != [state, state, state, state]:
  34. self.__set_out_state__(output, state)
  35. else:
  36. if self.__state__[int(output) - 1] != state:
  37. self.__set_out_state__(output, state)
  38. def __set_out_state__(self, output, state):
  39. try:
  40. out_txt = subprocess.check_output(["sudo", "sispmctl", "-o" if state == True else "-f", output]).decode('UTF-8')
  41. except subprocess.CalledProcessError as grepexc:
  42. logger.error("sispm error code %d", grepexc.returncode)
  43. else:
  44. logger.info('sispmctl channel %s changed to %s', output, state)
  45. self.publish_states()
  46. def get_out_states(self):
  47. try:
  48. out_txt = subprocess.check_output(["sudo", "sispmctl", "-g", "all"])
  49. except subprocess.CalledProcessError as grepexc:
  50. logger.error("sispm error code %d", grepexc.returncode)
  51. else:
  52. rv = []
  53. for i in range(1, 5):
  54. rv.append(out_txt.decode("UTF-8").split("\n")[i].split("\t")[1] == "on")
  55. return rv
  56. def publish_states(self):
  57. self.__state__ = self.get_out_states()
  58. for i in range(1, 5):
  59. self.send_state(i)
  60. def send_state(self, output):
  61. topic = config.MQTT_TOPIC + "/status/" + str(output)
  62. logger.info("Sending Powerplug status information of plug %s to mqtt %s = %s", str(output), topic, str(self.__state__[output - 1]))
  63. self.__mqtt_client__.publish(topic, "true" if self.__state__[output - 1] else "false")
  64. class mqtt_powerplug(object):
  65. SUBTOPICS = [
  66. "set/1",
  67. "set/2",
  68. "set/3",
  69. "set/4",
  70. "set/all"
  71. ]
  72. def __init__(self):
  73. self.__client__ = mqtt.Client("mqtt_powerplug") # create client object
  74. self.__client__.on_message = self.__receive__ # attach function to callback
  75. self.__client__.username_pw_set(config.MQTT_USER, config.MQTT_PASS) # login with credentials
  76. self.__client__.connect(config.MQTT_SERVER, 1883) # establish connection
  77. self.__client__.loop_start() # start the loop
  78. self.__topics__ = []
  79. for subtopic in self.SUBTOPICS:
  80. self.__topics__.append(config.MQTT_TOPIC + "/" + subtopic)
  81. self.__client__.subscribe(self.__topics__[-1]) # subscibe a topic
  82. self.__sc__ = sispmctl(self.__client__)
  83. def __receive__(self, client, userdata, message):
  84. if message.topic in self.__topics__:
  85. output = message.topic.split("/")[-1]
  86. state = message.payload == b"true"
  87. logger.info("Received request to set output channel %s to state %s", output, str(state))
  88. self.__sc__.set_out_state(output, state)
  89. else:
  90. logger.warning("Ignoring unknown mqtt topic %s", message.topic)
  91. def __del__(self):
  92. self.__client__.loop_stop() # stop the loop
  93. if __name__ == '__main__':
  94. report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
  95. #
  96. mp = mqtt_powerplug()
  97. while True:
  98. time.sleep(30)
  99. mp.__sc__.publish_states()