Things Ali cloud platform and reporting device attributes history MNS server subscription

Outline

Things Ali cloud platform not only supports real-time reporting device attributes, but also support for some reason, there is no timely reporting of property data, reported by historical property reported way historical property reporting Topic: / sys / {productKey} / {deviceName } / thing / event / property / history / post. In this paper, the latest exclusive examples of Things platform, create new products and equipment in the following example, it is reported test history attributes, and historical property MNS server subscription.

Steps

1, to create exclusive instance, create the following products and equipment in exclusive examples

_
_
_

2, examples of obtaining exclusive access point device side MQTT

_

3, the access device side, the reference links

import com.alibaba.taro.AliyunIoTSignUtil;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.HashMap;
import java.util.Map;

public class IoTDemoPubSubDemo {

    public static String productKey = "g028S******";
    public static String deviceName = "device1";
    public static String deviceSecret = "aKEHNK1w0UBvGcA1BA7gf2eHC********";
    public static String regionId = "cn-shanghai";
    public static String isntanceId = "iot-instc-public-cn-0pp1g*******";

    // 物模型 - 历史属性上报topic
    private static String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/history/post";

    private static MqttClient mqttClient;

    public static void main(String [] args){

        initAliyunIoTClient();
        postDeviceProperties();
    }

    /**
     * 初始化 Client 对象
     */
    private static void initAliyunIoTClient() {

        try {
            // 构造连接需要的参数
            String clientId = "java" + System.currentTimeMillis();
            Map<String, String> params = new HashMap<>(16);
            params.put("productKey", productKey);
            params.put("deviceName", deviceName);
            params.put("clientId", clientId);
            String timestamp = String.valueOf(System.currentTimeMillis());
            params.put("timestamp", timestamp);
            // MQTT 设备接入 公网终端节点(Endpoint)
            String targetServer = "tcp://" + isntanceId + ".iot-as-mqtt."+regionId+".iothub.aliyuncs.com:1883";

            String mqttclientId = clientId + "|securemode=3,signmethod=hmacsha1,timestamp=" + timestamp + "|";
            String mqttUsername = deviceName + "&" + productKey;
            String mqttPassword = AliyunIoTSignUtil.sign(params, deviceSecret, "hmacsha1");

            connectMqtt(targetServer, mqttclientId, mqttUsername, mqttPassword);

        } catch (Exception e) {
            System.out.println("initAliyunIoTClient error " + e.getMessage());
        }
    }

    public static void connectMqtt(String url, String clientId, String mqttUsername, String mqttPassword) throws Exception {

        MemoryPersistence persistence = new MemoryPersistence();
        mqttClient = new MqttClient(url, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        // MQTT 3.1.1
        connOpts.setMqttVersion(4);
        connOpts.setAutomaticReconnect(false);
//        connOpts.setCleanSession(true);
        connOpts.setCleanSession(false);

        connOpts.setUserName(mqttUsername);
        connOpts.setPassword(mqttPassword.toCharArray());
        connOpts.setKeepAliveInterval(60);

        mqttClient.connect(connOpts);
    }

    /**
     * 汇报属性
     */
    private static void postDeviceProperties() {

        try {
            //上报数据
            //高级版 物模型-属性上报payload
            System.out.println("历史上报属性值");
            String payloadJson = "{ \"id\": 123, \"version\": \"1.0\", \"method\": \"thing.event.property.history.post\", \"params\": [ { \"identity\": { \"productKey\": \"g028S******\", \"deviceName\": \"device1\" }, \"properties\": [ { \"AreaId\": { \"value\": \"history data test 4\", \"time\": 1578198990000 } } ] } ] }";
            MqttMessage message = new MqttMessage(payloadJson.getBytes("utf-8"));
            message.setQos(1);
            mqttClient.publish(pubTopic, message);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

payLoad format reference .

4, equipment operating status View

_

5, MNS server configuration subscription

_

6, MNS MNS Python SDK subscribe to get the message in the Queue

  • Installing the SDK 6.1

_

  • 6.2 Code Sample
#init my_account, my_queue
from mns.account import Account
import sys
import json
import base64

endpoint = "http://18482178********.mns.cn-shanghai.aliyuncs.com/"
accid = "LTAIOZZg********"
acckey = "v7CjUJCMk7j9aKduMAQLjy********"
token = ""
my_account = Account(endpoint, accid, acckey, token)
queue_name = "aliyun-iot-g028S******"
my_queue = my_account.get_queue(queue_name)

#循环读取删除消息直到队列空
#receive message请求使用long polling方式,通过wait_seconds指定长轮询时间为3秒

## long polling 解析:
### 当队列中有消息时,请求立即返回;
### 当队列中没有消息时,请求在MNS服务器端挂3秒钟,在这期间,有消息写入队列,请求会立即返回消息,3秒后,请求返回队列没有消息;

wait_seconds = 3
print("%sReceive And Delete Message From Queue%s\nQueueName:%s\nWaitSeconds:%s\n" % (10*"=", 10*"=", queue_name, wait_seconds))
while True:
    #读取消息
    try:
        recv_msg = my_queue.receive_message(wait_seconds)
        print("Receive Message Succeed! ReceiptHandle:%s MessageBody:%s MessageID:%s" % (recv_msg.receipt_handle, recv_msg.message_body, recv_msg.message_id))
        print("Message Body: ",base64.b64decode(json.loads(recv_msg.message_body)['payload'])) # 转发到mns 的messagebody经过了base64编码,获取具体消息的内容需要做base64解码
    except Exception as e:
    #except MNSServerException as e:
        if e.type == u"QueueNotExist":
            print("Queue not exist, please create queue before receive message.")
            sys.exit(0)
        elif e.type == u"MessageNotExist":
            print("Queue is empty!")
            sys.exit(0)
        print("Receive Message Fail! Exception:%s\n" % e)
        continue

    #删除消息
    try:
        my_queue.delete_message(recv_msg.receipt_handle)
        print("Delete Message Succeed!  ReceiptHandle:%s" % recv_msg.receipt_handle)
    except Exception as e:
        print("Delete Message Fail! Exception:%s\n" % e)
print("Delete Message Fail! Exception:%s\n" % e)
  • 6.3 Test Result
Receive Message Succeed! ReceiptHandle:8-2zuDHj20LzZz8zcFz0z6YEzcSFqxyIKefW MessageBody:{"payload":"eyJkZXZpY2VUeXBlIjoiQ3VzdG9tQ2F0ZWdvcnkiLCJpb3RJZCI6IlY1WGJXekluY0EyOW41aWNib3RYZzAyODAwIiwicmVxdWVzdElkIjoiMTIzIiwicHJvZHVjdEtleSI6ImcwMjhTR1o4RlJDIiwiZ210Q3JlYXRlIjoxNTc4MjkxNzI0NjY4LCJkZXZpY2VOYW1lIjoiZGV2aWNlMSIsIml0ZW1zIjp7IkFyZWFJZCI6eyJ0aW1lIjoxNTc4MTk4OTkwMDAwLCJ2YWx1ZSI6Imhpc3RvcnkgZGF0YSB0ZXN0*********","messagetype":"thing_history","topic":"/g028S******/device1/thing/event/property/history/post","messageid":1214069604465248256,"timestamp":1578291724} MessageID:5F8092E53A67656C7F811CD50E19A150
Message Body:  b'{"deviceType":"CustomCategory","iotId":"V5XbWzIncA29n5icbo********","requestId":"123","productKey":"g028S******","gmtCreate":1578291724668,"deviceName":"device1","items":{"AreaId":{"time":1578198990000,"value":"history data test 4"}}}'
DEBUG: v7CjUJCMk7j9aKduMAQLjyCmb8cmCm hAbKzezvRlqeVXC18CzChL4OZZk= DELETE

More Reference

Use MNS server subscription
Python SDK queue manual

Guess you like

Origin yq.aliyun.com/articles/741808
Recommended