MQTT

来自前人的智慧

稳定性: 稳定

MQTT 模块,采用org.eclipse.paho.client.mqttv3实现

代码示例

主题订阅、发布、QOS、遗嘱消息

1importPackage(Packages["org.eclipse.paho.client.mqttv3"]);
2importClass("org.eclipse.paho.android.service.MqttAndroidClient");
3
4// 连接、订阅配置
5const MQTT_URL = "tcp://192.168.20.225:1883";
6const CLIENT_ID = "MOCK";
7const TOPIC = "ANDROID_MOCK";
8const QOS = 2;
9const USERNAME = "device";
10const PASSWORD = "public";
11
12const client = new MqttAndroidClient(context, MQTT_URL, CLIENT_ID);
13const subscribeToTopic = () => {
14    try {
15        client.subscribe(
16            TOPIC,
17            QOS,
18            null,
19            new IMqttActionListener({
20                onSuccess: (token) => {
21                    toast("MQTT 订阅成功");
22                },
23                onFailure: (token, error) => {
24                    toast("MQTT 订阅失败 " + error);
25                },
26            })
27        );
28    } catch (error) {
29        toast(error.message);
30        alert('MQTT订阅错误\n\n"' + error.message);
31    }
32};
33
34const initMQTT = () => {
35    // 创建配置
36    const mqttConnectOptions = new MqttConnectOptions();
37    mqttConnectOptions.setAutomaticReconnect(true);
38    mqttConnectOptions.setCleanSession(true);
39    mqttConnectOptions.setUserName(USERNAME);
40    mqttConnectOptions.setPassword(Array.from(PASSWORD));
41    // 遗嘱消息 QOS = 1, retained = true
42    let willMsgJavaString = new java.lang.String("i am gone");
43    let willMsgJavaBytes = willMsgJavaString.getBytes("UTF-8");
44    mqttConnectOptions.setWill("device-gone", willMsgJavaBytes, 1, true);
45
46    console.log("mqttConnectOptions", mqttConnectOptions);
47
48    const callback = new MqttCallbackExtended({
49        connectComplete: (reconnect, serverUri) => {
50            if (reconnect) {
51                subscribeToTopic();
52                console.log("重新连接到MQTT");
53            } else {
54                console.log("连接到MQTT");
55            }
56        },
57        connectionLost: () => {
58            console.log("MQTT 连接丢失");
59        },
60        messageArrived: (topic, message) => {
61            console.log("MQTT MESSAGE: ", topic, message);
62        },
63    });
64    client.setCallback(callback);
65
66    client.connect(
67        mqttConnectOptions,
68        null,
69        new IMqttActionListener({
70            onSuccess: () => {
71                console.log("mqtt连接成功");
72                subscribeToTopic();
73            },
74            onFailure: (token, error) => {
75                console.error("mqtt连接失败", error);
76                exit();
77            },
78        })
79    );
80};
81
82const publish = (topic, msg, qos = 1, retained = false) => {
83    // publish message
84    try {
85        let javaString = new java.lang.String(msg);
86        let byteArray = javaString.getBytes("UTF-8");
87        client.publish(topic, byteArray, qos, retained);
88    } catch (error) {
89        console.error("MQTT 发布失败", error);
90    }
91};
92
93// 连接
94initMQTT();
95setTimeout(() => {
96    toast("7秒后自动关闭");
97    // send message
98    publish(TOPIC, "hello");
99}, 3000);
100// 断开并退出
101setTimeout(() => {
102    client.close();
103    client.disconnect();
104    toast("自动关闭并退出脚本");
105    exit();
106}, 10 * 1000);
107
108// 防止进程退出
109setInterval(() => {
110    //
111}, 1000);
ON THIS PAGE