Replace browser MQTT bridge with backend device-events service
The frontend previously connected directly to the MQTT broker via a CDN-loaded Paho client and a Paho-specific ws proxy. Move that responsibility into the backend: DeviceDataService persists MQTT messages to Postgres, and DeviceEventsController exposes them over a REST endpoint plus a WebSocket gateway that the frontend now consumes directly. Also adds a pgadmin service for inspecting the database. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,33 +1,26 @@
|
||||
import Head from 'next/head';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
const WS_PATH = '/api/device-events/ws';
|
||||
|
||||
interface ApiStatus {
|
||||
message: string;
|
||||
docs: string;
|
||||
}
|
||||
|
||||
interface MqttMessage {
|
||||
interface DeviceRecord {
|
||||
id: number;
|
||||
topic: string;
|
||||
payload: string;
|
||||
receivedAt: string;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
Paho?: {
|
||||
Client: new (...args: any[]) => any;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
const [status, setStatus] = useState<ApiStatus | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [messages, setMessages] = useState<MqttMessage[]>([]);
|
||||
const [messages, setMessages] = useState<DeviceRecord[]>([]);
|
||||
const [connected, setConnected] = useState(false);
|
||||
|
||||
const clientId = useMemo(() => `ulhub-web-${Math.random().toString(16).slice(2)}`, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/status')
|
||||
.then((res) => res.json())
|
||||
@@ -36,90 +29,48 @@ export default function Home() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js';
|
||||
script.async = true;
|
||||
console.log('Appending Paho script to page:', script.src);
|
||||
script.onerror = () => {
|
||||
console.error('Failed to load Paho MQTT script from CDN');
|
||||
setError('Failed to load MQTT client script');
|
||||
};
|
||||
script.onload = () => {
|
||||
console.log('Paho script loaded', !!window.Paho);
|
||||
console.log('Paho global:', window.Paho);
|
||||
// connect to same-origin via nginx proxy at /mqtt so browsers use wss on HTTPS
|
||||
const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
const uri = `${scheme}://${window.location.host}/mqtt`;
|
||||
console.log('Connecting Paho client to', uri);
|
||||
fetch('/api/device-events')
|
||||
.then((res) => res.json())
|
||||
.then((payload) => {
|
||||
const records = Array.isArray(payload) ? payload : payload?.records ?? [];
|
||||
setMessages(Array.isArray(records) ? records : []);
|
||||
setConnected(true);
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err.message || 'Unable to load device events');
|
||||
});
|
||||
|
||||
let client: any;
|
||||
const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
const socket = new WebSocket(`${wsProtocol}://${window.location.host}${WS_PATH}`);
|
||||
|
||||
socket.onopen = () => {
|
||||
setConnected(true);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
try {
|
||||
if (window.Paho && typeof (window.Paho as any).Client === 'function') {
|
||||
client = new (window.Paho as any).Client(uri, clientId);
|
||||
} else if (window.Paho && (window.Paho as any).MQTT && typeof (window.Paho as any).MQTT.Client === 'function') {
|
||||
// Paho.MQTT.Client(host, port, path, clientId)
|
||||
const url = new URL(uri);
|
||||
const host = url.hostname;
|
||||
const port = url.port ? Number(url.port) : (url.protocol === 'wss:' ? 443 : 80);
|
||||
const path = url.pathname + (url.search || '');
|
||||
client = new (window.Paho as any).MQTT.Client(host, port, path, clientId);
|
||||
} else {
|
||||
console.error('Paho client constructor not found', window.Paho);
|
||||
setError('MQTT client not available in browser');
|
||||
const payload = JSON.parse(event.data);
|
||||
if (payload.type === 'connected') {
|
||||
setConnected(true);
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to instantiate Paho client', e);
|
||||
setError(String(e));
|
||||
return;
|
||||
|
||||
setMessages((prev) => [payload, ...prev].slice(0, 20));
|
||||
} catch (err) {
|
||||
console.error('Failed to parse device-event payload', err);
|
||||
}
|
||||
|
||||
client.onConnectionLost = (responseObject: { errorCode: number; errorMessage: string }) => {
|
||||
console.warn('Paho connection lost', responseObject);
|
||||
setConnected(false);
|
||||
setError(responseObject.errorMessage || 'MQTT connection lost');
|
||||
};
|
||||
|
||||
client.onMessageArrived = (message: { topic: string; payloadString: string }) => {
|
||||
setMessages((prev) => [
|
||||
{
|
||||
topic: message.topic,
|
||||
payload: message.payloadString,
|
||||
receivedAt: new Date().toLocaleTimeString(),
|
||||
},
|
||||
...prev,
|
||||
].slice(0, 10));
|
||||
};
|
||||
|
||||
const connectOptions: any = {
|
||||
onSuccess: () => {
|
||||
console.log('Paho connected');
|
||||
setConnected(true);
|
||||
setError(null);
|
||||
client.subscribe('devices/#');
|
||||
},
|
||||
onFailure: (err: { errorMessage: string }) => {
|
||||
console.error('Paho connect failure', err);
|
||||
setConnected(false);
|
||||
setError(err.errorMessage || 'Unable to connect to MQTT broker');
|
||||
},
|
||||
};
|
||||
// force secure websocket when page is served over HTTPS
|
||||
connectOptions.useSSL = window.location.protocol === 'https:';
|
||||
console.log('Paho connect options:', connectOptions);
|
||||
client.connect(connectOptions);
|
||||
|
||||
return () => {
|
||||
client.disconnect();
|
||||
};
|
||||
};
|
||||
|
||||
document.body.appendChild(script);
|
||||
socket.onerror = () => {
|
||||
setConnected(false);
|
||||
setError('Realtime stream disconnected');
|
||||
};
|
||||
|
||||
return () => {
|
||||
document.body.removeChild(script);
|
||||
socket.close();
|
||||
};
|
||||
}, [clientId]);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -145,10 +96,10 @@ export default function Home() {
|
||||
</section>
|
||||
|
||||
<section style={{ marginTop: '1.5rem' }}>
|
||||
<h2>MQTT WebSocket</h2>
|
||||
<h2>Device Events</h2>
|
||||
<p>Status: {connected ? 'Connected' : 'Connecting...'}</p>
|
||||
<ul>
|
||||
{messages.map((msg, index) => (
|
||||
{(Array.isArray(messages) ? messages : []).map((msg, index) => (
|
||||
<li key={`${msg.topic}-${index}`} style={{ marginBottom: '0.75rem' }}>
|
||||
<strong>{msg.topic}</strong> <span style={{ color: '#666' }}>{msg.receivedAt}</span>
|
||||
<br />
|
||||
|
||||
Reference in New Issue
Block a user