Module: MQTT <--> Powerplug Enegenie
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

powerplug.py 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import config
  2. import logging
  3. import mqtt
  4. import report
  5. import socket
  6. import subprocess
  7. import time
  8. try:
  9. from config import APP_NAME as ROOT_LOGGER_NAME
  10. except ImportError:
  11. ROOT_LOGGER_NAME = 'root'
  12. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild('main')
  13. class sispmctl(object):
  14. AMP_CHANNEL = 0
  15. def __init__(self, mqtt_client):
  16. logger.info("Starting sispmctl module...")
  17. self.__mqtt_client__ = mqtt_client
  18. self.__state_requests__ = [{}, {}, {}, {}]
  19. self.publish_states()
  20. def __filter_output_parameter__(self, output):
  21. try:
  22. return int(output)
  23. except ValueError:
  24. return output
  25. def set_out_state(self, output, state):
  26. if output == "all":
  27. if self.__state__ != [state, state, state, state]:
  28. self.__set_out_state__(output, state)
  29. else:
  30. if self.__state__[int(output) - 1] != state:
  31. self.__set_out_state__(output, state)
  32. def __set_out_state__(self, output, state):
  33. try:
  34. out_txt = subprocess.check_output(["sudo", "sispmctl", "-o" if state == True else "-f", output]).decode('UTF-8')
  35. except subprocess.CalledProcessError as grepexc:
  36. logger.error("sispm error code %d", grepexc.returncode)
  37. else:
  38. logger.info('sispmctl channel %s changed to %s', output, state)
  39. self.publish_states()
  40. def toggle_out_state(self, output):
  41. if output == "all":
  42. for i in range(1,5):
  43. self.toggle_out_state(str(i))
  44. else:
  45. self.set_out_state(output, not self.__state__[int(output) - 1])
  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. try:
  64. self.__mqtt_client__.send(topic, "true" if self.__state__[output - 1] else "false")
  65. except (socket.timeout, OSError) as e:
  66. logger.warning("Erro while sending state information information")
  67. class mqtt_powerplug(mqtt.mqtt_client):
  68. def __init__(self):
  69. mqtt.mqtt_client.__init__(self, config.APP_NAME, config.MQTT_SERVER, 1883, config.MQTT_USER, config.MQTT_PASS)
  70. for target in ["1", "2", "3", "4", "all"]:
  71. self.add_callback(config.MQTT_TOPIC + "/set/" + target, self.__set__)
  72. self.add_callback(config.MQTT_TOPIC + "/toggle/" + target, self.__toggle__)
  73. #
  74. self.__sc__ = sispmctl(self)
  75. def __set__(self, client, userdata, message):
  76. output = message.topic.split("/")[-1]
  77. if message.topic.find("set") >= 0:
  78. state = message.payload == b"true"
  79. logger.info("Received request to set output channel %s to state %s", output, str(state))
  80. self.__sc__.set_out_state(output, state)
  81. def __toggle__(self, client, userdata, message):
  82. output = message.topic.split("/")[-1]
  83. logger.info("Received request to toggle output channel %s", output)
  84. if message.payload != b"false":
  85. self.__sc__.toggle_out_state(output)
  86. def __del__(self):
  87. self.__client__.loop_stop() # stop the loop
  88. if __name__ == '__main__':
  89. report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
  90. #
  91. mp = mqtt_powerplug()
  92. while True:
  93. time.sleep(30)
  94. mp.__sc__.publish_states()