Module: MQTT <--> Powerplug Enegenie
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

powerplug.py 5.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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 toggle_out_state(self, output):
  47. if output == "all":
  48. for i in range(1,5):
  49. self.toggle_out_state(str(i))
  50. else:
  51. self.set_out_state(output, not self.__state__[int(output) - 1])
  52. def get_out_states(self):
  53. try:
  54. out_txt = subprocess.check_output(["sudo", "sispmctl", "-g", "all"])
  55. except subprocess.CalledProcessError as grepexc:
  56. logger.error("sispm error code %d", grepexc.returncode)
  57. else:
  58. rv = []
  59. for i in range(1, 5):
  60. rv.append(out_txt.decode("UTF-8").split("\n")[i].split("\t")[1] == "on")
  61. return rv
  62. def publish_states(self):
  63. self.__state__ = self.get_out_states()
  64. for i in range(1, 5):
  65. self.send_state(i)
  66. def send_state(self, output):
  67. topic = config.MQTT_TOPIC + "/status/" + str(output)
  68. logger.info("Sending Powerplug status information of plug %s to mqtt %s = %s", str(output), topic, str(self.__state__[output - 1]))
  69. self.__mqtt_client__.publish(topic, "true" if self.__state__[output - 1] else "false")
  70. class mqtt_powerplug(object):
  71. SUBTOPICS = [
  72. "set/1",
  73. "set/2",
  74. "set/3",
  75. "set/4",
  76. "set/all",
  77. "toggle/1",
  78. "toggle/2",
  79. "toggle/3",
  80. "toggle/4",
  81. "toggle/all",
  82. ]
  83. def __init__(self):
  84. self.__client__ = mqtt.Client("mqtt_powerplug") # create client object
  85. self.__client__.on_message = self.__receive__ # attach function to callback
  86. self.__client__.username_pw_set(config.MQTT_USER, config.MQTT_PASS) # login with credentials
  87. self.__client__.connect(config.MQTT_SERVER, 1883) # establish connection
  88. self.__client__.loop_start() # start the loop
  89. self.__topics__ = []
  90. for subtopic in self.SUBTOPICS:
  91. self.__topics__.append(config.MQTT_TOPIC + "/" + subtopic)
  92. self.__client__.subscribe(self.__topics__[-1]) # subscibe a topic
  93. self.__sc__ = sispmctl(self.__client__)
  94. def __receive__(self, client, userdata, message):
  95. if message.topic in self.__topics__:
  96. output = message.topic.split("/")[-1]
  97. if message.topic.find("set") >= 0:
  98. state = message.payload == b"true"
  99. logger.info("Received request to set output channel %s to state %s", output, str(state))
  100. self.__sc__.set_out_state(output, state)
  101. elif message.topic.find("toggle") >= 0:
  102. logger.info("Received request to toggle output channel %s", output)
  103. if message.payload != b"false":
  104. self.__sc__.toggle_out_state(output)
  105. else:
  106. logger.warning("Ignoring unknown mqtt topic %s", message.topic)
  107. def __del__(self):
  108. self.__client__.loop_stop() # stop the loop
  109. if __name__ == '__main__':
  110. report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
  111. #
  112. mp = mqtt_powerplug()
  113. while True:
  114. time.sleep(30)
  115. mp.__sc__.publish_states()