apricot-mqtt
v1.0.0
Published
## Install
Downloads
5
Readme
apricot-mqtt
Install
$ npm install apricot-mqtt
Usage
// mqtt client
var mqtt = new MQttClient("ws://192.168.20.75:5223/mqtt", { username: "admin", password: "123456" });
// message handler
mqtt.onMessageHandler = (result) => {
console.log(`mqtt onmessage success`, result.topic, result.payload.toString());
};
Sample
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>mqtt-client</title>
</head>
<script src="index.js"></script>
<body>
<input type="button" value="subscribe" onclick="subscribe()" />
<input type="button" value="publish" onclick="publish()" />
</body>
</html>
<script>
// mqtt client
var mqtt = new MQttClient("ws://192.168.20.75:5223/mqtt", { username: "admin", password: "123456" });
// message handler
mqtt.onMessageHandler = (result) => {
console.log(`mqtt onmessage success`, result.topic, result.payload.toString());
};
// connect handler
mqtt.onConnectHandler = (packet) => {
console.log(`connect to server succeed.`, packet);
};
// error handler
mqtt.onErrorHandler = (result) => {
console.error(`server throw error:`, error);
};
// reconnect handler
mqtt.onReconnectHandler = (result) => {
console.log(`reconnect to server.`);
};
// subscribe
async function subscribe() {
await mqtt.subscribeAsync("apricot");
}
// publish
async function publish() {
await mqtt.publishAsync({ topic: "apricot", payload: JSON.stringify({ datetime: Date.now() }) })
}
</script>