summaryrefslogtreecommitdiffstats
path: root/extra/simple-mqtt-server.js
blob: 66ebfe4d9559e5dc86277ce0c36b46017529d3bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const { log } = require("../src/util");

const mqttUsername = "louis1";
const mqttPassword = "!@#$LLam";

class SimpleMqttServer {
    aedes = require("aedes")();
    server = require("net").createServer(this.aedes.handle);

    /**
     * @param {number} port Port to listen on
     */
    constructor(port) {
        this.port = port;
    }

    /**
     * Start the MQTT server
     * @returns {void}
     */
    start() {
        this.server.listen(this.port, () => {
            console.log("server started and listening on port ", this.port);
        });
    }
}

let server1 = new SimpleMqttServer(10000);

server1.aedes.authenticate = function (client, username, password, callback) {
    if (username && password) {
        console.log(password.toString("utf-8"));
        callback(null, username === mqttUsername && password.toString("utf-8") === mqttPassword);
    } else {
        callback(null, false);
    }
};

server1.aedes.on("subscribe", (subscriptions, client) => {
    console.log(subscriptions);

    for (let s of subscriptions) {
        if (s.topic === "test") {
            server1.aedes.publish({
                topic: "test",
                payload: Buffer.from("ok"),
            }, (error) => {
                if (error) {
                    log.error("mqtt_server", error);
                }
            });
        }
    }

});

server1.start();