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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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: true,
  9. connectTimeout: 4000,
  10. clientId: 'lights-web',
  11. username: mqttUsername,
  12. password: mqttPassword,
  13. }
  14. const callbacks = []
  15. const client = mqtt.connect(mqttUrl, options)
  16. client.on('connect', function () {
  17. console.log('MQTT Connected')
  18. })
  19. client.on('message', function (topic, message) {
  20. console.log("Rx \"" + topic.toString() + "\": \"" + message.toString() + "\"")
  21. for (const cb of callbacks) {
  22. if (cb.topic == topic) {
  23. console.log("Routing to Callback")
  24. cb.callback(message)
  25. }
  26. }
  27. })
  28. /*
  29. function clearSubscriptions() {
  30. for (const cb of callbacks) {
  31. client.unsubscribe(cb.topic)
  32. }
  33. callbacks = []
  34. }
  35. */
  36. function subscribeTopic(topic, callback) {
  37. console.log("Sub to \"" + topic.toString() + "\"")
  38. subOptions = {
  39. rh: true,
  40. }
  41. client.subscribe(topic)
  42. callbackObj = {
  43. topic: topic,
  44. callback: callback,
  45. }
  46. callbacks.push(callbackObj)
  47. }
  48. function setTopic(topic, message) {
  49. console.log("Tx \"" + topic.toString() + "\": \"" + message.toString() + "\"")
  50. pubOptions = {
  51. retain: true,
  52. }
  53. client.publish(topic, message, pubOptions)
  54. }