Advertisement
Javi

HTML: browser based mqtt client

May 24th, 2020
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. # Paho browser
  2.  
  3. ## Mosquitto broker
  4.  
  5. * Install the server
  6.  
  7. ```bash
  8. sudo apt update
  9. sudo apt install mosquitto
  10. ```
  11.  
  12. * Update broker config to enable websockets
  13.  
  14. ```bash
  15. sudo cat << EOF >> /etc/mosquitto/mosquitto.conf
  16. listener 9001
  17. protocol websockets
  18.  
  19. listener 1883
  20. EOF
  21. ```
  22.  
  23. * Restart the service to use the new config
  24.  
  25. ```bash
  26. sudo service mosquitto restart
  27. ```
  28.  
  29. ## HTML client
  30.  
  31. * Import the library
  32.  
  33.  
  34. ```html
  35. <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
  36. ```
  37.  
  38. * Manage messages
  39.  
  40. ```javascript
  41. const TOPIC_NAME='mytopic';
  42. const client = new Paho.MQTT.Client('mqtt.myserver.com', 9001, 'UniqueClientId'+Date.now());
  43.  
  44. function clientOnConnect() {
  45. console.log(`mqtt client connected.`);
  46. client.subscribe(TOPIC_NAME);
  47. }
  48.  
  49. client.onConnectionLost = (error) => {
  50. console.log(`mqtt client disconnected: ${error.errorMessage}. Retry in two seconds.`);
  51. setTimeout(()=> client.connect({onSuccess: clientOnConnect}), 1000*2);
  52. };
  53.  
  54. client.onMessageArrived = (message)=>{
  55. const payload = JSON.parse(message.payloadString);
  56.  
  57. // do whatever you need to do with the new message
  58. };
  59.  
  60. client.connect({
  61. onSuccess : clientOnConnect
  62. });
  63.  
  64. function sendMessage(topic, body) {
  65. const message = new Paho.MQTT.Message(json.stringify(body));
  66. message.destinationName = topic;
  67. client.send(message);
  68. }
  69. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement