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.

mqtt.js 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 clientId = ("00" + Math.floor(Math.random() * 1000)).substr(-3)
  8. const options = {
  9. clean: true,
  10. connectTimeout: 4000,
  11. clientId: 'lights-web-' + clientId,
  12. username: mqttUsername,
  13. password: mqttPassword,
  14. }
  15. const callbacks = []
  16. const client = mqtt.connect(mqttUrl, options)
  17. client.on('connect', function () {
  18. console.log('MQTT Connected')
  19. })
  20. client.on('message', function (topic, message) {
  21. console.log("Rx \"" + topic.toString() + "\": \"" + message.toString() + "\"")
  22. for (const cb of callbacks) {
  23. if (cb.topic == topic) {
  24. console.log("Routing to Callback")
  25. cb.callback(message)
  26. }
  27. }
  28. })
  29. function subscribeTopic(topic, callback) {
  30. console.log("Sub to \"" + topic.toString() + "\"")
  31. subOptions = {
  32. rh: true,
  33. }
  34. client.subscribe(topic)
  35. callbackObj = {
  36. topic: topic,
  37. callback: callback,
  38. }
  39. callbacks.push(callbackObj)
  40. }
  41. function subscribeSensor(topic, unit, selector, divisor = 1.0) {
  42. subscribeTopic(topic, function (msg) {
  43. const txt = document.querySelector(selector)
  44. txt.innerHTML = "<p>" + parseInt(msg / divisor) + " " + unit + "</p>"
  45. })
  46. }
  47. function subscribeSensorString(topic, selector) {
  48. subscribeTopic(topic, function (msg) {
  49. const txt = document.querySelector(selector)
  50. txt.innerHTML = "<p>" + msg + "</p>"
  51. })
  52. }
  53. function setTopic(topic, message) {
  54. console.log("Tx \"" + topic.toString() + "\": \"" + message.toString() + "\"")
  55. pubOptions = {
  56. retain: true,
  57. }
  58. client.publish(topic, message, pubOptions)
  59. }