Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Paho browser
- ## Mosquitto broker
- * Install the server
- ```bash
- sudo apt update
- sudo apt install mosquitto
- ```
- * Update broker config to enable websockets
- ```bash
- sudo cat << EOF >> /etc/mosquitto/mosquitto.conf
- listener 9001
- protocol websockets
- listener 1883
- EOF
- ```
- * Restart the service to use the new config
- ```bash
- sudo service mosquitto restart
- ```
- ## HTML client
- * Import the library
- ```html
- <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
- ```
- * Manage messages
- ```javascript
- const TOPIC_NAME='mytopic';
- const client = new Paho.MQTT.Client('mqtt.myserver.com', 9001, 'UniqueClientId'+Date.now());
- function clientOnConnect() {
- console.log(`mqtt client connected.`);
- client.subscribe(TOPIC_NAME);
- }
- client.onConnectionLost = (error) => {
- console.log(`mqtt client disconnected: ${error.errorMessage}. Retry in two seconds.`);
- setTimeout(()=> client.connect({onSuccess: clientOnConnect}), 1000*2);
- };
- client.onMessageArrived = (message)=>{
- const payload = JSON.parse(message.payloadString);
- // do whatever you need to do with the new message
- };
- client.connect({
- onSuccess : clientOnConnect
- });
- function sendMessage(topic, body) {
- const message = new Paho.MQTT.Message(json.stringify(body));
- message.destinationName = topic;
- client.send(message);
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement