mqttHandler.py 906 B

12345678910111213141516171819202122232425262728293031
  1. import paho.mqtt.client as mqtt
  2. import random
  3. class RgbLamp:
  4. def __init__(self, host, port = 1883):
  5. self.mqttc = mqtt.Client()
  6. self.mqttc.on_message = self.onMessage
  7. self.mqttc.on_connect = self.onConnect
  8. self.host = host
  9. self.port = port
  10. self.mqttc.connect_async(self.host, self.port, 60)
  11. self.mqttc.loop_start()
  12. self._nBeat = 0
  13. def onMessage(self, mqttc, obj, msg):
  14. print(msg)
  15. def onConnect(self, client, userdata, flags, rc):
  16. print("Connected with result code "+str(rc))
  17. self.mqttc.subscribe("Timer/#", 2)
  18. self.mqttc.subscribe("Pc/#", 2)
  19. def onBeat(self, fft):
  20. json = "{\"spot\":[{\"color\":" + str(0) + ",\"radius\":" + str(int(fft[1])*3+2) + ",\"pos\":" + str(10 + self._nBeat%4 * 10) + ",\"keep\":0}],\"speed\":40}"
  21. self._nBeat += 1
  22. #print(" ------------------ " + json)
  23. self.mqttc.publish("RgbLamp/spot", json)