Try two – Adventures with MQTT and Tulip Custom Widgets

The first time I tried with the paho client. But paho-mqtt is no longer maintained

https://github.com/eclipse/paho.mqtt.javascript/pull/191

It looks like there might be a patch to use an in-memory fallback, but I’m going to try using https://github.com/mqttjs/MQTT.js/#browser instead

In browsers when localStorage access is disabled for your domain the

browsers will throw an Access denied error if you try to even read the

localStorage property. This commit adds try/catch logic to handle the

error and use the in-memory fallback.

So using this as a start

https://www.shiftr.io/docs/manuals/javascript/

Make some html

<!DOCTYPE html>
<html>
   <p id="p1">MQTT</p>
  <head>
    <meta charset="utf-8" />
    <title>MQTT</title>
   </head>
</html>

Then make some javascript

async function loadScripts(...urls) {
  for (const thisUrl of urls) {
    console.log(`Loading script "${thisUrl}"...`);
    const response = await fetch(thisUrl);
    const responseBody = await response.text();
    const scriptElm = document.createElement("script");
    const inlineCode = document.createTextNode(responseBody);
    scriptElm.appendChild(inlineCode);
    document.body.appendChild(scriptElm);

    console.log(`Script "${thisUrl}" successfully loaded`);
    main();
  }
}

loadScripts('https://unpkg.com/mqtt/dist/mqtt.min.js');

function main () {

const client = mqtt.connect('ws://localhost:9001');

client.on('connect', function() {
  console.log('connected!');
  document.getElementById("p1").innerHTML = "MQTT - Connected";
});

client.on('message', function(topic, message) {
  console.log(topic + ': ' + message.toString());
  fireEvent("MESSAGE",message.toString());
});

getValue('topic',(tempVar) => {
    console.log('subscribed to ' + tempVar);
    tempVar && client.subscribe(tempVar);
  });

}

If you are lucky it will show MQTT – Connected (You have to be running mosquito websocket on 9001 on localhost)

That’s all nice and good, but next we need to connect to a remote mosquito broker…

And then we get the dreaded

Mixed Content: The page at ‘https://.tulip.co/dev-player?appVersion=blah&#8217; was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint ‘ws://172.16.1.105:9001/’. This request has been blocked; this endpoint must be available over WSS.

So this is a block put in by browsers to keep us secure. Next up, how to secure mosquito using wss

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s