add some way to read mqtt data

This commit is contained in:
David Senoner 2025-06-11 19:03:43 +02:00
parent efc2da22ac
commit 1c7be2a776
4 changed files with 469 additions and 32 deletions

View file

@ -1,8 +1,42 @@
<script lang="ts">
import { onMount } from "svelte";
import { onMount, onDestroy } from "svelte";
const { data } = $props();
let mqttMessage = $state("Waiting for MQTT message...");
let eventSource;
onMount(() => {
// Connect to the SSE endpoint
eventSource = new EventSource("/mqtt");
eventSource.onopen = () => {
console.log("SSE connection opened.");
};
eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
mqttMessage = data.message;
console.log("Received SSE message:", mqttMessage);
} catch (e) {
console.error("Error parsing SSE message:", e);
}
};
eventSource.onerror = (error) => {
console.error("SSE Error:", error);
eventSource.close(); // Close the connection on error
};
});
onDestroy(() => {
if (eventSource) {
console.log("Closing SSE connection.");
eventSource.close(); // Clean up the connection when the component is destroyed
}
});
let canvasEl: HTMLCanvasElement;
let ctx;
@ -55,5 +89,6 @@
<div style="display: flex; justify-content: center; align-items: center; height: 100%;">
<h1 class="text-center text-4xl font-bold">Floor {data.slug}</h1>
<span>{mqttMessage}</span>
<canvas bind:this={canvasEl} class="obj-contain" width="800%" height="600%"></canvas>
</div>