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.6KB

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 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 setTopic(topic, message) {
  48. console.log("Tx \"" + topic.toString() + "\": \"" + message.toString() + "\"")
  49. pubOptions = {
  50. retain: true,
  51. }
  52. client.publish(topic, message, pubOptions)
  53. }