Motion Detector
Arduino & Svelte

Commands

Motion Sensor - PIR

Internet of Things

Programming

Svelte

SRE | Arduino & MQTT with Svelte UI

Arduino and MQTT with Svelte UI

Intro

If you need nice Web UI for your IoT project, Svelte is a good choice. It is easy to embed free Bootstrap themes and get nice and functional, responsive, UI in short time. Another issue is to resolve Internet connectivity for your devices. Most probably your IoT device will be behind home firewall (NAT). MQTT could be one simple solution to create end to end connectivity between your phone or PC and IoT devices automating your home.

MQTT

MQTT is one of the standards for Internet of Things communication. It is publish/subscribe network protocol for message queuing. It is simple to install and configure it on Ubuntu using Mosquitto package.

By default it will listen for MQTT connections on TCP port 1883 or WebSocket connection (with SSL) on port 9001. Communication is via topics where multiple clients subscribe or publish messages. When message is published in some topics, all subscribers will receive it. This communication will work even if the subscribers are behind NAT because they will initiate the connection.

Solution

If your are using SvelteKit, you must make sure to load MQTT libs on the client side (not on the server). One solution is:

    
    # Load Paho Lib in your app.html
    <head>
        ...
        <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>

    </head>
    
                

Then you can use MQTT in your components like this:


        onMount(async () => {

            // Execute in Browser - not server side!!!
            client = new Paho.MQTT.Client('YOUR.MQTT.SERVER', 9001, "car")
        
            client.connect({
                useSSL: false, 
                onSuccess: onConnect
            })
        
            client.onConnectionLost = onConnectionLost
            client.onMessageArrived = onMessageArrived
        
        }) 

        function onConnect() {
            console.log("Paho Connected")
            client.subscribe("outTopic")
        
        }
        
        function onConnectionLost() {
            console.log("Paho Lost Connection")
        }
        
        function onMessageArrived(message) {
            console.log("Paho MSG: " + message.payloadString)
            data = message.payloadString
        }