2022年6月13日 星期一

[mqtt, websockets] How to using MQTT Over WebSockets with Mosquitto

How to using MQTT Over WebSockets with Mosquitto

井民全, Jing, mqjing@gmail.com

This documents records a quick note for setup a MQTT solution over websocket using Mosquitto packages. 

Quick

(a) Setup the mqtt broker

# Donwload Server

docker pull eclipse-mosquitto  # pull the latest mqtt server


# Download the config file and editing

wget -f  https://hub.docker.com/_/eclipse-mosquitto eclipse-mosquitto.conf


vi eclipse-mosquitto.conf


File: eclipse-mosquitto.conf

# setup unauthenticated access

allow_anonymous true

listener 1883


listener 9001

protocol websockets



# start the server

sudo docker run -it -p 1883:1883 -p 9001:9001 -v /home/jing/work/mosquitto/mosquitto.conf:/mosquitto/config/mosquitto.conf -v /home/jing/work/mosquitto/data -v /home/jing/work/mosquitto/log eclipse-mosquitto


# testing normal mqtt

# (1) send

mosquitto_pub -h 172.20.10.3 -m "test message" -t vital/ppg


# (2) subscribe

mosquitto_sub -h 172.20.10.3 -t vital/ppg -C 3


# debug

# check if port is in use 

sudo lsof -i -P -n | grep LISTEN



(b) setup the javascript

File: index.htm

<!doctype html>

<html lang="en">


<head>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>

</head>


<body>

    <h1>Test</h1>

    <script src="index.js"></script>

</body>

</html>



File: index.js

// API Doc: https://www.eclipse.org/paho/files/jsdoc/Paho.MQTT.Client.html


'use strict';


let strBrokerIP = "172.20.10.3";

let strTopic = "World";

let client = null;

let message = null;

let body = document.getElementsByTagName("body")[0];

let eleStatus = null;



function createHtmlElement(strStyle, strTitle, funClickCallback){

  let ele = document.createElement(strStyle);

  if(strTitle != null)

    ele.innerHTML = strTitle;

  if (funClickCallback != null)

    ele.addEventListener('click', funClickCallback);

  return ele;

}


function createHtmlBr(body){

  let ele = createHtmlElement('br', null, null);

  if(body == null){

    console.log('Error: createHtmlBr::body == null')

    return null;

  }


  body.appendChild(ele);

  return ele;

}


function createHtmlButton(strtitle, funClickCallback, body){

  let ele = createHtmlElement('button', strtitle, funClickCallback);

  if(body == null){

    console.log('Error: createHtmlButton::body == null')

    return null;

  }


  body.appendChild(ele);

  return ele;

}


function createHtmlPTag(strtitle, body){

  let ele = createHtmlElement('p', strtitle, null);

  if(body == null){

    console.log('Error: createHtmlPTag::body == null')

    return null;

  }

  body.appendChild(ele);

  return ele;

}


function updatePTagTitle(eleStatus, strTitle){

  if(eleStatus == null){

    console.log('Error: eleStatus == null.');

    return;

  }

  eleStatus.innerText = strTitle;

  console.log('UpdatePTagTitle:: ' + strTitle)

}


function cbConnect(){

    console.log('cbConnect::start to connect and send message');

    let clientId = "clientId" + Math.floor(Math.random() * 10).toString();

    console.log('clientId = ' + clientId);

    client = new Paho.MQTT.Client(strBrokerIP, Number(9001), clientId);

    client.onConnectionLost = onMQTTConnectionLost;

    client.connect({onSuccess:onMQTTConnect});

}


function cbSendRandomMsg() {

  

  if (client == null) {

    console.log('client == null. Not connected?')

    return;

  }


  let strMsg =  Math.floor(Math.random() * 10).toString();

  message = new Paho.MQTT.Message(strMsg);

  message.destinationName = strTopic;

  client.send(message);



  console.log("cbSendRandomMsg:" + strMsg)

  updatePTagTitle(eleStatus, "cbSendRandomMsg:" + strMsg);

}


function cbRegReceiver() {

  console.log('Register to received a messages');

  if (client == null) {

    console.log('client == null. Not connected?')

    return;

  }

  client.onMessageArrived = onMQTTMessageArrived;

}



function onMQTTConnect() {

  console.log("onConnect");

  updatePTagTitle(eleStatus, "onConnected");

  client.subscribe("World");

}


function onMQTTConnectionLost(responseObject) {

  if (responseObject.errorCode !== 0) {

    console.log("onConnectionLost:"+responseObject.errorMessage);

    updatePTagTitle(eleStatus, "onConnectionLost:"+responseObject.errorMessage);

  }

}


function onMQTTMessageArrived(message) {

  console.log("onMessageArrived:"+message.payloadString);

  updatePTagTitle(eleStatus, "onMessageArrived:"+message.payloadString);

}


function uiMainBuild(){

  let btConnect = createHtmlButton("1. Connect", cbConnect, body);

  let BrTag = createHtmlBr(body);

  let btSend = createHtmlButton("2. Send Random number", cbSendRandomMsg, body);

  let btRegReive = createHtmlButton("(3). Reg receiver", cbRegReceiver, body);


  createHtmlBr(body);createHtmlBr(body);

  eleStatus = createHtmlPTag("Status", body);

  

}


function main(){

  uiMainBuild();

}


main();



(c) Result

Publisher


Subscriber


References

  1. Project Home, https://www.eclipse.org/paho/

  2. API Doc: https://www.eclipse.org/paho/files/jsdoc/Paho.MQTT.Client.html

  3. Source, https://github.com/eclipse/paho.mqtt.javascript