安卓使用MQTT实现阿里云物联网云台订阅和发布主题(3)

时间:2024-03-22 12:31:50

一、订阅主题代码讲解

private final String mqtt_sub_topic = "/sys/k0wih08FdYq/LHAPP/thing/service/property/set";//订阅话题
        
        //mqtt客户端订阅主题
        //QoS=0时,报文最多发送一次,有可能丢失
        //QoS=1时,报文至少发送一次,有可能重复
        //QoS=2时,报文只发送一次,并且确保消息只到达一次。
        int[] qos = {1};
        String[] topic = {mqtt_sub_topic};
        mqttClient.subscribe(topic, qos);

二、发布主题代码讲解

private final String payloadJson = "{\"id\":%s,\"params\":{\"LightLux\": %s,\"Humidity\": %s,\"temperature\": %s},\"method\":\"thing.event.property.post\"}";

private void postDeviceProperties() {
        try {
            String payload = String.format(payloadJson, String.valueOf(System.currentTimeMillis()), 10,10,10);
            String responseBody = payload;
            MqttMessage message = new MqttMessage(payload.getBytes("utf-8"));
            message.setQos(1);
            String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
            mqttClient.publish(pubTopic, message);
            Log.d(TAG, "publish topic=" + pubTopic + ",payload=" + payload);
            msgTextView.setText("发布成功");
        } catch (Exception e) {
            e.printStackTrace();
            msgTextView.setText("发布失败");
            Log.e(TAG, "postDeviceProperties error " + e.getMessage(), e);
        }
    }

三、回调函数代码讲解

mqttClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                //这里不需要做处理
                //因为在option有一个方法可以自动重连(如下)
                //断开后,是否自动连接,connOpts.setAutomaticReconnect(true);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                //publish后会执行到这里
                System.out.println("deliveryComplete---------" + token.isComplete());
            }

            @Override
            public void messageArrived(String topicName, MqttMessage message) throws Exception {
                //subscribe主题后,收到消息执行到这里
                try {
                    JSONObject jsonObject = new JSONObject(message.toString());// 解析JSON数据
                    Log.i(TAG, "消息到达,message: " + message);
                    JSONObject paramsObject = jsonObject.getJSONObject("params");// 获取params字段中的JSONObject

                    int Humidity = paramsObject.getInt("Humidity");
                    int LightLux = paramsObject.getInt("LightLux");
                    int temperature = paramsObject.getInt("temperature");
                    humidityTextView.setText(String.valueOf(Humidity));
                    lightluxTextView.setText(String.valueOf(LightLux));
                    temperatureTextView.setText(String.valueOf(temperature));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

四、实验现象 

五、完整代码

链接:https://pan.baidu.com/s/1cbcAjmzPWw4n7EvO7uT62A?pwd=8888 
提取码:8888