|
| 1 | +/** http://w3c.github.io/html-reference/input.color.html |
| 2 | + * |
| 3 | + * sent events: |
| 4 | + * - mqtt_message |
| 5 | + */ |
| 6 | + |
| 7 | +import {event} from "./utils.js" |
| 8 | + |
| 9 | +let client; |
| 10 | +let mqtt_connected = false; |
| 11 | +let subscribe_topic = "" |
| 12 | + |
| 13 | +function init(mqtt_config){ |
| 14 | + subscribe_topic = mqtt_config.subscribe |
| 15 | + mqtt_connect(mqtt_config) |
| 16 | +} |
| 17 | + |
| 18 | +// called when the client connects |
| 19 | +function onConnect() { |
| 20 | + mqtt_connected = true; |
| 21 | + // Once a connection has been made, make a subscription and send a message. |
| 22 | + console.log("mqtt_app> onConnect() mqtt running"); |
| 23 | + |
| 24 | + client.subscribe(subscribe_topic); |
| 25 | + console.log(`mqtt_app> - subscribed to ${subscribe_topic}`); |
| 26 | +} |
| 27 | + |
| 28 | +// called when the client loses its connection |
| 29 | +function onConnectionLost(responseObject) { |
| 30 | + if (responseObject.errorCode !== 0) { |
| 31 | + console.log("onConnectionLost:"+responseObject.errorMessage); |
| 32 | + } |
| 33 | + mqtt_connected = false; |
| 34 | +} |
| 35 | + |
| 36 | +// called when a message arrives |
| 37 | +function onMessageArrived(message) { |
| 38 | + //console.log(`mqtt_app> ${message.destinationName} => ${message.payloadString}`); |
| 39 | + event("mqtt_message",{topic:message.destinationName,payload:JSON.parse(message.payloadString)}); |
| 40 | +} |
| 41 | + |
| 42 | +function mqtt_connect(config){ |
| 43 | + // Create a client instance |
| 44 | + const client_name = window.location.hostname + '#' + config.client; |
| 45 | + client = new Paho.MQTT.Client(config.host, Number(config.port), client_name); |
| 46 | + // set callback handlers |
| 47 | + client.onConnectionLost = onConnectionLost; |
| 48 | + client.onMessageArrived = onMessageArrived; |
| 49 | + |
| 50 | + // connect the client |
| 51 | + client.connect({onSuccess:onConnect}); |
| 52 | +} |
| 53 | + |
| 54 | +export{init} |
0 commit comments