MQTT smart home web interface
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.

lights.js 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * The idea is to use retained messages.
  3. * This way we can keep the state of the lights.
  4. * Make sure all senders use retained messages!
  5. * (in here and shell scripts on PC)
  6. */
  7. const options = {
  8. // Clean session
  9. clean: true,
  10. connectTimeout: 4000,
  11. // Auth
  12. clientId: 'lights-web',
  13. username: 'USER_HERE',
  14. password: 'PW_HERE',
  15. }
  16. const callbacks = []
  17. const client = mqtt.connect('wss://iot.fritz.box:8083', options)
  18. client.on('connect', function () {
  19. console.log('MQTT Connected')
  20. })
  21. client.on('message', function (topic, message) {
  22. console.log("Rx \"" + topic.toString() + "\": \"" + message.toString() + "\"")
  23. for (const cb of callbacks) {
  24. if (cb.topic == topic) {
  25. console.log("Routing to Callback")
  26. cb.callback(message)
  27. }
  28. }
  29. })
  30. /*
  31. function clearSubscriptions() {
  32. for (const cb of callbacks) {
  33. client.unsubscribe(cb.topic)
  34. }
  35. callbacks = []
  36. }
  37. */
  38. function subscribeTopic(topic, callback) {
  39. console.log("Sub to \"" + topic.toString() + "\"")
  40. subOptions = {
  41. rh: true,
  42. }
  43. client.subscribe(topic)
  44. callbackObj = {
  45. topic: topic,
  46. callback: callback,
  47. }
  48. callbacks.push(callbackObj)
  49. }
  50. function setTopic(topic, message) {
  51. console.log("Tx \"" + topic.toString() + "\": \"" + message.toString() + "\"")
  52. pubOptions = {
  53. retain: true,
  54. }
  55. client.publish(topic, message, pubOptions)
  56. }