1.0.0 • Published 11 months ago

apricot-mqtt v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
11 months ago

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>