Module: MQTT <--> Powerplug Enegenie
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.

powerplug.py 4.5KB

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