Module: MQTT <--> Powerplug Enegenie
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

powerplug.py 4.3KB

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