48 lines
1.3 KiB
HTML
48 lines
1.3 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Weboscoket MQTT</title>
|
|
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
|
|
</head>
|
|
<body>
|
|
Use WebSocket client to connect to MQTT server
|
|
</body>
|
|
<script>
|
|
const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)
|
|
const host = 'mqtt://dev.tannercollin.com:8080'
|
|
const options = {
|
|
keepalive: 60,
|
|
clientId: clientId,
|
|
protocolId: 'MQTT',
|
|
protocolVersion: 4,
|
|
clean: true,
|
|
reconnectPeriod: 1000,
|
|
connectTimeout: 30 * 1000,
|
|
will: {
|
|
topic: 'WillMsg',
|
|
payload: 'Connection Closed abnormally..!',
|
|
qos: 0,
|
|
retain: false
|
|
},
|
|
}
|
|
console.log('Connecting mqtt client')
|
|
const client = mqtt.connect(host, options)
|
|
client.on('error', (err) => {
|
|
console.log('Connection error: ', err)
|
|
client.end()
|
|
})
|
|
client.on('reconnect', () => {
|
|
console.log('Reconnecting...')
|
|
})
|
|
client.on('connect', () => {
|
|
console.log(`Client connected: ${clientId}`)
|
|
// Subscribe
|
|
client.subscribe('test', { qos: 0 })
|
|
})
|
|
client.on('message', (topic, message, packet) => {
|
|
console.log(`Received Message: ${message.toString()} On topic: ${topic}`)
|
|
})
|
|
</script>
|