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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 while changing state of channel %s", grepexc.returncode, output)
  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. i = 0
  48. while i < 10: # number of tries
  49. try:
  50. out_txt = subprocess.check_output(["sudo", "sispmctl", "-g", "all"])
  51. except subprocess.CalledProcessError as grepexc:
  52. logger.error("sispm error code %d while getting states", grepexc.returncode)
  53. else:
  54. rv = []
  55. for i in range(1, 5):
  56. rv.append(out_txt.decode("UTF-8").split("\n")[i].split("\t")[1] == "on")
  57. return rv
  58. logger.warning("Could not get state of powerplugs")
  59. return self.__state__
  60. def publish_states(self):
  61. self.__state__ = self.get_out_states()
  62. for i in range(1, 5):
  63. self.send_state(i)
  64. def send_state(self, output):
  65. topic = config.MQTT_TOPIC + "/output/" + str(output)
  66. logger.debug("Sending Powerplug status information of plug %s to mqtt %s = %s", str(output), topic, str(self.__state__[output - 1]))
  67. try:
  68. self.__mqtt_client__.send(topic, "true" if self.__state__[output - 1] else "false")
  69. except (socket.timeout, OSError) as e:
  70. logger.warning("Error while sending state information via mqtt")
  71. class mqtt_powerplug(mqtt.mqtt_client):
  72. def __init__(self):
  73. mqtt.mqtt_client.__init__(self, config.APP_NAME, config.MQTT_SERVER, 1883, config.MQTT_USER, config.MQTT_PASS)
  74. for target in ["1", "2", "3", "4", "all"]:
  75. self.add_callback(config.MQTT_TOPIC + "/output/%s/set" % target, self.__set__)
  76. #
  77. self.__sc__ = sispmctl(self)
  78. def __set__(self, client, userdata, message):
  79. output = message.topic.split("/")[-2]
  80. if message.payload == b"true" or message.payload == b"false":
  81. self.__sc__.set_out_state(output, message.payload == b"true")
  82. elif message.payload.lower() == b'toggle':
  83. self.__sc__.toggle_out_state(output)
  84. else:
  85. logger.warning("Ignoring set command due to payload: %s", message.payload)
  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()