Created
September 27, 2022 09:53
-
-
Save jenschr/35de02694674c8c1f598c0e94d9e14e9 to your computer and use it in GitHub Desktop.
TEK303 Mqtt client example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const myTopic = "users/jensa/led"; | |
const myServer = "mqtt.toytronics.com"; | |
const client = new Paho.MQTT.Client(myServer,8883, "myClientId" + new Date().getTime()); | |
client.onConnectionLost = onConnectionLost; | |
client.onMessageArrived = onMessageArrived; | |
console.log("Start connection!"); | |
var connectOptions = { | |
useSSL: false, | |
userName: secret.mqttuser, | |
password: secret.mqttpass, | |
onSuccess:onConnect, | |
} | |
client.connect(connectOptions); | |
let counter = 0 | |
function onConnect() { | |
console.log("connection successful"); | |
client.subscribe(myTopic); //subscribe to our topic | |
document.getElementById("server").value = myServer; | |
document.getElementById("topic").value = myTopic; | |
document.getElementById("button").ariaBusy = true; | |
} //publish count every 5s | |
const publish = (topic, msg) => { //takes topic and message string | |
let message = new Paho.MQTT.Message(msg); | |
message.destinationName = topic; | |
client.send(message); | |
} | |
function onMessageArrived(message) { | |
console.log("Got: "+message.payloadString); | |
document.getElementById("button").ariaBusy = false; | |
document.getElementById("button").innerHTML = "Got something!"; | |
document.getElementById("payload").value = message.payloadString; | |
if(message.payloadString == "1") | |
{ | |
document.getElementById("button").className = "primary"; | |
} | |
else | |
{ | |
document.getElementById("button").className = "secondary"; | |
} | |
} | |
function onConnectionLost(responseObject) { | |
console.log(responseObject); | |
return; | |
if (responseObject.errorCode !== 0) { | |
console.log("onConnectionLost:" + responseObject.errorMessage); | |
} | |
client.connect({ onSuccess: onConnect }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment