JS-Code für Websocket-Verbindung

Raspi MQTT-Daten mit Websocket senden und empfangen



Quellen: S. Cope, "Using MQTT Over WebSockets with Mosquitto", http://www.steves-internet-guide.com/mqtt-websockets, 09/2021
"WebSocket",https://en.wikipedia.org/wiki/WebSocket, aufgerufen: 03/2022

MQTT-Daten werden über WebSocket in eine HTML-Seite eingebunden. WebSocket ist ein Netzwerkprotokoll für eine Full-Duplex-Kommunikation über eine einzige TCP-Verbindung.

Mit Websocket können MQTT-Daten in Echtzeit auf einer Webseite angezeigt werden.

websocket.js JavaScript code

let onConnect = () => {
    console.log("connected!");

    //Abbonieren
    mqtt.subscribe("klasse/messwerte/#");
};


//Verbindungsdaten
//console.log("hello world");
let host = "broker.hivemq.com";
let port = 8000;

let mqtt = new Paho.MQTT.Client(host, port, "clientjs");

let options = {
    timeout: 3,
    onSuccess: onConnect
};


//Senden mit Button
let button = document.querySelector(".btn-websocket");
button.onclick = () => {
    let jsonMessage = {
        temperatur: 23.2,
        luftfeuchte: 29.4
    }
    let message = new Paho.MQTT.Message(JSON.stringify(jsonMessage));
    message.destinationName = "klasse/messwerte/myname";
    mqtt.send(message);

};

//Empfangen
mqtt.onMessageArrived = (msg) => {
    console.log(msg.destinationName);
    console.log(msg.payloadString);
    writeTableRow(msg.payloadString);
};

//write payload in table
let writeTableRow = (payloadString) => {
    console.log(payloadString);
    
    let payload = JSON.parse(payloadString);

    let table = document.querySelector(".table-websocket tbody"); 

    let tr = document.createElement("tr");
    let temperature = document.createElement("td");
    temperature.textContent = payload.temperatur;
    console.log(temperature);
    tr.appendChild(temperature);

    let humidity = document.createElement("td");
    humidity.textContent = payload.luftfeuchte;
    tr.appendChild(humidity);

    table.appendChild(tr);
};

//Verbindungsaufbau
mqtt.connect(options);

websocket-test.html Verbindung herstellen

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  </head>
  <body>
    <div class="py-5" style="background-color: #E1E1E1; color:#000000;">
        <div class="container">
            <button type="button" class="btn btn-primary btn-websocket">Primary</button>
        </div>
    </div>

    <div class="py-5" style="background-color: #FFFFFF; color: black;">
        <div class="container">
            <table class="table table-striped table-websocket">
                <tr>
                    <td>Temperatur in °C</td>
                    <td>Luftfeuchte in %</td>
                </tr>
            </table>
        </div>
    </div>

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

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  </body>
</html>