MQTT Webpage Update
by ludovicoiovino
HTML
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<div id="status">Connecting...</div>
<div id="mqttMessage" class="blink_text" style="margin-top: 20px; font-size: 1.2em; color: navy;">
Waiting for messages...
</div>
CSS
body{
background-color: white;
}
.blink_text{
animation-name:blink;
width:100%;
animation-duration:2s;
animation-timing-function:ease-in;
animation-iteration-count:Infinite;
font-size: 1.5em;
letter-spacing: 0.04em;
margin: 0;
font-weight: normal;
color: #ff5252;
}
#mqttMessage{paddoing:5px;}
.announcement {
padding: 10px 15px 0px;
border: 1px solid #e1e1e1;
background-color: #f9f9f9;
border-radius: 4px;
}
@keyframes blink{
0%{color:red;}
50%{color:white;}
100%{color:red;}
JavaScript
function getCurrentDateTime() {
const now = new Date();
const day = String(now.getDate()).padStart(2, '0');
const month = String(now.getMonth() + 1).padStart(2, '0'); // months are 0-based
const year = now.getFullYear();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
return `${day}-${month}-${year} ${hours}:${minutes}`;
}
// Connect to HiveMQ Cloud using WebSockets (port 8884)
const client = mqtt.connect('wss://baede9a2f1bc4e609a38cc6dd1a15f12.s1.eu.hivemq.cloud:8884/mqtt', {
username: 'iovino',
password: 'dHp892d298dfb!p4bf',
clientId: 'web_' + Math.random().toString(16).substr(2, 8),
clean: true,
connectTimeout: 4000,
reconnectPeriod: 1000
});
client.on('connect', () => {
console.log('Connected to HiveMQ WebSocket broker');
document.getElementById('status').textContent = 'Connected. Subscribing to "test"...';
// Subscribe to topic "test" immediately
client.subscribe('test', (err) => {
if (err) {
console.error('Subscription error:', err);
document.getElementById('status').textContent = 'Subscription failed: ' + err.message;
} else {
document.getElementById('status').textContent = 'Subscribed to the topic...';
}
});
});
client.on('message', (topic, message) => {
try {
const payload = JSON.parse(message.toString()); // convert JSON string to object
const msgText = payload.msg || '[msg key missing]'; // extract the 'msg' key
document.getElementById('mqttMessage').innerText = msgText;
document.getElementById('status').textContent = `✅ Message received`;
} catch (err) {
console.error('Invalid JSON:', err);
document.getElementById('mqttMessage').innerText = '⚠️ Invalid JSON payload';
}
});
client.on('error', (err) => {
console.error('Connection error:', err);
...