阿里云物联网平台设备历史属性上报及MNS服务端订阅

作者:俏巴

概述

阿里云物联网平台不仅支持设备即时属性的上报,也支持因为某些原因,没有及时上报的属性数据,通过历史属性上报的方式进行上报,历史属性上报Topic:/sys/{productKey}/{deviceName}/thing/event/property/history/post。本文结合物联网平台最新推出的独享实例,在新的实例下面创建产品及设备,进行历史属性的上报测试,并进行 MNS 历史属性服务端订阅。

操作步骤

1、创建独享实例,在独享实例下面创建产品和设备

阿里云物联网平台设备历史属性上报及MNS服务端订阅

阿里云物联网平台设备历史属性上报及MNS服务端订阅

阿里云物联网平台设备历史属性上报及MNS服务端订阅

2、获取独享实例设备端MQTT接入点

阿里云物联网平台设备历史属性上报及MNS服务端订阅

3、设备端接入,参考链接

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格式参考

4、设备运行状态查看

阿里云物联网平台设备历史属性上报及MNS服务端订阅

5、MNS服务端订阅配置
阿里云物联网平台设备历史属性上报及MNS服务端订阅

6、使用 MNS Python SDK 获取MNS订阅到Queue中的消息

  • 6.1 安装SDK
    阿里云物联网平台设备历史属性上报及MNS服务端订阅
  • 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

更多参考

使用MNS服务端订阅
Python SDK 队列使用手册

上一篇:三大措施将SQL注入攻击的危害最小化


下一篇:启动报错“No bootable device”