先看看阿里云对物模型的概念解释:物模型是阿里云物联网平台为产品定义的数据模型,用于描述产品的功能。本文介绍物模型相关概念和使用限制。(https://help.aliyun.com/document_detail/88239.html
站在我的角度看,mqqt层面是没有物模型这个概念的。理论上讲只要你定义要topic,定义好传递的palyload就行了。和平时写给前端的接口文档是一个样子的,我可以用post当作get查询,也可以get中实现post数据新增的功能。但是为了专业行的沟通和统一,大家最后搞出一个restful 风格的api开发模式。所以我在我看来所谓物模型就是阿里云iot平台帮你定义好的和嵌入式沟通的“接口文档”和“开发规范”,这就和咋们restful api开发规范是一个道理。

1-功能定义

正如前面所阐述的一样,物模型就是一个阿里云总结定义好的和嵌入式沟通的“接口文档”和“开发规范”,和咋们restful api开发规范是一样。那么我们在和前端对接接口文档的时候是以“功能”作为载体的,比如我会告诉前端:这是登陆的接口文档。
所以真正实现物联网功能的是i阿里云的”功能定义“,功能定义以”物模型“的方式给出。也就是“功能定义”是“登陆功能”,“物模型”是restful风格的api 接口文档。

1.1-功能定义

image.png
image.png

所谓标准功能也是阿里云物联网帮你定义的一些场景的接口参数,比如“cpu使用率”,我们这里选择自定义

2.创建自定义功能

2.1-添加自定义功能

image.png

属性 事件 服务三个区别体现在哪里?

image.png

2.2-物模型

那么功能定义的意义在哪里体现呢?
和前面说的一样这些功能是依托于物模型的,也就是和前端交互的api接口文档,所以我们来看看创建的温度上报功能的“接口文档”也就是“物模型”长什么样子。
image.png
image.png
完整版物模型:

  1. {
  2. "schema": "https://iotx-tsl.oss-ap-southeast-1.aliyuncs.com/schema.json",
  3. "profile": {
  4. "version": "1.0",
  5. "productKey": "guonWDsfHNn"
  6. },
  7. "properties": [
  8. {
  9. "identifier": "temperature",
  10. "name": "温度上报",
  11. "accessMode": "rw",
  12. "desc": "温度定时上报功能",
  13. "required": false,
  14. "dataType": {
  15. "type": "int",
  16. "specs": {
  17. "min": "-10",
  18. "max": "10",
  19. "unit": "°C",
  20. "unitName": "摄氏度",
  21. "step": "1"
  22. }
  23. }
  24. }
  25. ],
  26. "events": [
  27. {
  28. "identifier": "post",
  29. "name": "post",
  30. "type": "info",
  31. "required": true,
  32. "desc": "属性上报",
  33. "method": "thing.event.property.post",
  34. "outputData": [
  35. {
  36. "identifier": "temperature",
  37. "name": "温度上报",
  38. "dataType": {
  39. "type": "int",
  40. "specs": {
  41. "min": "-10",
  42. "max": "10",
  43. "unit": "°C",
  44. "unitName": "摄氏度",
  45. "step": "1"
  46. }
  47. }
  48. }
  49. ]
  50. }
  51. ],
  52. "services": [
  53. {
  54. "identifier": "set",
  55. "name": "set",
  56. "required": true,
  57. "callType": "async",
  58. "desc": "属性设置",
  59. "method": "thing.service.property.set",
  60. "inputData": [
  61. {
  62. "identifier": "temperature",
  63. "name": "温度上报",
  64. "dataType": {
  65. "type": "int",
  66. "specs": {
  67. "min": "-10",
  68. "max": "10",
  69. "unit": "°C",
  70. "unitName": "摄氏度",
  71. "step": "1"
  72. }
  73. }
  74. }
  75. ],
  76. "outputData": []
  77. },
  78. {
  79. "identifier": "get",
  80. "name": "get",
  81. "required": true,
  82. "callType": "async",
  83. "desc": "属性获取",
  84. "method": "thing.service.property.get",
  85. "inputData": [
  86. "temperature"
  87. ],
  88. "outputData": [
  89. {
  90. "identifier": "temperature",
  91. "name": "温度上报",
  92. "dataType": {
  93. "type": "int",
  94. "specs": {
  95. "min": "-10",
  96. "max": "10",
  97. "unit": "°C",
  98. "unitName": "摄氏度",
  99. "step": "1"
  100. }
  101. }
  102. }
  103. ]
  104. }
  105. ]
  106. }

精简版物模型:

  1. {
  2. "properties": [
  3. {
  4. "identifier": "temperature",
  5. "dataType": {
  6. "type": "int"
  7. }
  8. }
  9. ]
  10. }

首先说看到这里我第一眼想起来的就是我们api的swagger文档的格式,所以阿里云肯定是利用swagger文档的语法规则作为物模型的tsl语法来进行校验和解析。真他娘的聪明。 但是实际开发中用阿里云提供的api或者sdk不会直接使用这些原生的物模型json串,更多的是让我们更深刻的去理解物模型这个概念和落地的样子。

2.3-物模型的使用

还是之前的那句话,mqqt层面只需要有topic就可以。
我们这里定义的“温度上报”功能选择的功能类型是“属性”,我们在产品下面的topickankan属性上报的topic是什么:
image.png

  1. /sys/guonWDsfHNn/${deviceName}/thing/event/property/post

我们还是用mqqt.fx模拟设备上报数据:
image.png
阿里云日志:
image.png两条信息,一条设备到云(mqtt topic),一条数物模型相关的数据状态码是失败的
设备到云消息:
image.png
设备到云消息就是我们在mqtt.fx客户端发送的消息内容是一样的。但是物模型的状态是6027,根据文档查阅得到(https://help.aliyun.com/document_detail/44542.html?spm=5176.11485173.help.dexternal.405559afEEnnXX)是数据的格式有误:
image.png
所以导致device1的设备是没有数据上来的:
image.png
服务端订阅的数据也没有:
image.png
云产品流转的数据也是没有上来的:
image.png
记得我前面说的么,那个物模型的格式和swagger文档语法格式很像,所以我们要按照那样的json格式上报数据才可以,我们就按照哪个精简版本的数据格式上报。

  1. {
  2. "properties": [
  3. {
  4. "identifier": "temperature",
  5. "dataType": {
  6. "type": "int"
  7. }
  8. }
  9. ]
  10. }
  1. {
  2. "method":"thing.event.property.post",//对应物模型的属性上报
  3. "params":{
  4. "temperature":27//物模型定义的是int这里一定只能是int
  5. }
  6. }

需要注意的是官网基于物模型通信的案例都是给出的sdk方式,起码我没有找到利用原生mqqt方式物模型使用教程。我也是百度了很久才找到的。
image.png
image.png

amqp本地客户端也收到了消息

3-功能分类

在整个阿里云物联网体系中“物模型”这个概念被大量使用,我们在创建功能的时候有三个选项:
9-物模型 - 图20
image.png
从mqtt的角度叫只有topic发布/订阅的概念,阿里云分类与否对mqtt是没有任何意义的。但是阿里云基于这个分类提供了对应的处理函数是能解决我们的实际开发问题的。比如“服务”这一类型,我完全可以自定义一个topic名字叫“service”,然后通过发布/订阅来完成和设备端的交互。但是阿里云又把服务分为同步和异步,如果我们要实现同步基于mqtt的实现是需要二次封装的,所以我是觉得物模型和功能定义更多的意义是阿里云帮我们在原生的mqtt的基础上二次封装了一个在实际应用场景中的问题解决方案。
那么属性,事件,服务怎么使用,解决了什么问题呢?
https://help.aliyun.com/document_detail/89301.html

https://help.aliyun.com/document_detail/90567.htm?spm=a2c4g.11186623.0.0.78791c80ywd3ZR

3.1-属性

3.1.1-定义属性功能

需求:我要上报当前设备的温度,设备唯一编码,时间三个信息
image.png

这里的读写类型我还没有体会到,因为我把它改成只读的情况topic发布/订阅都能通,阿里云iot日志也有两条数据 现在还不知道体现在哪里

image.png
image.png
image.png

  1. {
  2. "properties": [
  3. {
  4. "identifier": "temperature",
  5. "dataType": {
  6. "type": "int"
  7. }
  8. },
  9. {
  10. "identifier": "tmp_upload",
  11. "dataType": {
  12. "type": "struct",
  13. "specs": [
  14. {
  15. "identifier": "upload_time",
  16. "dataType": {
  17. "type": "int"
  18. }
  19. },
  20. {
  21. "identifier": "now_temp",
  22. "dataType": {
  23. "type": "float"
  24. }
  25. },
  26. {
  27. "identifier": "device_id",
  28. "dataType": {
  29. "type": "text"
  30. }
  31. }
  32. ]
  33. }
  34. }
  35. ]
  36. }

3.1.2-设备上报属性

属性上报的topic:/sys/guonWDsfHNn/${deviceName}/thing/event/property/post
image.png


  1. {
  2. "method": "thing.event.property.post",
  3. "params": {
  4. "temperature": 6,
  5. "tmp_upload": {
  6. "now_temp": 12.3,
  7. "device_id": "12313",
  8. "upload_time": 1646834531
  9. }
  10. }
  11. }

关于原生方式通过topic上传属性/事件/服务的格式:https://help.aliyun.com/document_detail/89301.html

image.png
iot日志
image.png
设备的物模型数据
image.png
amqp服务端订阅:
image.png

3.1.3-服务端订阅能拿到的信息

  1. cmd:
  2. 'MESSAGE'
  3. headers:
  4. {'destination': '/guonWDsfHNn/device1/thing/event/property/post',
  5. 'generateTime': '1646838223863',
  6. 'message-id': '1501574460157725184',
  7. 'qos': '1',
  8. 'subscription': '1',
  9. 'topic': '/guonWDsfHNn/device1/thing/event/property/post'}
  10. original_headers:
  11. {'destination': '/guonWDsfHNn/device1/thing/event/property/post',
  12. 'generateTime': '1646838223863',
  13. 'message-id': '1501574460157725184',
  14. 'qos': '1',
  15. 'subscription': '1',
  16. 'topic': '/guonWDsfHNn/device1/thing/event/property/post'}
  17. body:
  18. {'checkFailedData': {},
  19. 'deviceName': 'device1',
  20. 'deviceType': 'CustomCategory',
  21. 'gmtCreate': 1646838223861,
  22. 'iotId': 'Iml0VgmYzbQv1VYueRsWguon07',
  23. 'items': {'temperature': {'time': 1646838223857, 'value': 7},
  24. 'tmp_upload': {'time': 1646838223857,
  25. 'value': {'device_id': '12313',
  26. 'now_temp': 12.3,
  27. 'upload_time': 1646834531}}},
  28. 'productKey': 'guonWDsfHNn',
  29. 'requestId': 'null'}

根据这些信息你可以做自己业务系统中的业务处理。

3.1.3-云端响应属性上报

实话实说我没有找到云端响应设备上报的规则文档,理论上讲云端下发给不需要过分校验,只需要和嵌入式沟通好协议就行了。
topic:

  1. /sys/guonWDsfHNn/${deviceName}/thing/event/property/post_reply

image.png
mqtt客户端发布且订阅这个topic,会看到2条消息,右边是发布的消息(业务系统),左边是订阅者(设备)收到的消息。
image.png
iot日志:
image.png
image.png

此时设备的订阅的列表中就多了一个topic

3.1.4-云端属性设置

image.png
云端响应的格式:

  1. {
  2. "method": "thing.event.property.set",
  3. "params": {
  4. "temperature": 8,
  5. "tmp_upload": {
  6. "now_temp": 9,
  7. "device_id": "12313",
  8. "upload_time": 1646834531
  9. }
  10. }
  11. }

mqtt客户端发布消息

image.png

iot日志
image.png
物模型数据:
image.png
物模型数据是不会变的,因为我们是下发消息响应他的“属性上报”的请求,虽然我的消息内容是关于温度的数据,其实是障眼法。。。。
我就是想看看当前设备的属性会不会变化,所以是不会变的。要等设备吧温度调好了,下一次属性上报(3.1.2)的时候物模型数据才会变化。可想而知这个命令amqp客户端也是没有收到流转的消息的。
image.png
我们可以在amqp的监听的设备消息的类型来验证:
image.png
能流转到客户端订阅的都是以设备到主动上报内通的消息类型。

3.2-事件

3.2.1-定义事件

image.png
image.png

“信息”是设备上报的一般性通知,如完成某项任务等。“告警”和“故障”是设备运行过程中主动上报的突发或异常情况,优先级高。不同的事件类型将用于统计分析。(摘抄阿里云的解释)没有体现就是和平时的日志一样的等级区分而已。

此时产品的精简物模型

  1. {
  2. "properties": [
  3. {
  4. "identifier": "temperature",
  5. "dataType": {
  6. "type": "int"
  7. }
  8. },
  9. {
  10. "identifier": "tmp_upload",
  11. "dataType": {
  12. "type": "struct",
  13. "specs": [
  14. {
  15. "identifier": "upload_time",
  16. "dataType": {
  17. "type": "int"
  18. }
  19. },
  20. {
  21. "identifier": "now_temp",
  22. "dataType": {
  23. "type": "float"
  24. }
  25. },
  26. {
  27. "identifier": "device_id",
  28. "dataType": {
  29. "type": "text"
  30. }
  31. }
  32. ]
  33. }
  34. }
  35. ],
  36. //比之前多了event标识
  37. "events": [
  38. {
  39. "outputData": [
  40. {
  41. "identifier": "code",
  42. "dataType": {
  43. "type": "int"
  44. }
  45. }
  46. ],
  47. "identifier": "open_door",
  48. "type": "info"
  49. }
  50. ]
  51. }

3.2.2-事件上报

事件上报的topic:

  1. /sys/guonWDsfHNn/${deviceName}/thing/event/${tsl.event.identifier}/post
  2. /sys/guonWDsfHNn/device1/thing/event/open_door/post

image.png

  1. {
  2. "method": "thing.event.open_door.post",
  3. "params":{
  4. "code":1//假设1表示门开了 0表示门关了
  5. }
  6. }

image.png
iot日志:
image.png

以前属性上报的时候,这里叫做“设备到云消息”,云端响应属性上报是“云到设备”,属性设置是“设备到云消息” 这里的事件上报是“物模型消息”,实话说不知道怎么分的业务类型

image.png
此时设备的事件管理多了一调记录
image.png

3.2.3-服务端订阅能拿到的信息

  1. cmd:
  2. 'MESSAGE'
  3. headers:
  4. {'destination': '/guonWDsfHNn/device1/thing/event/open_door/post',
  5. 'generateTime': '1646841984778',
  6. 'message-id': '1501590234578562048',
  7. 'qos': '1',
  8. 'subscription': '1',
  9. 'topic': '/guonWDsfHNn/device1/thing/event/open_door/post'}
  10. original_headers:
  11. {'destination': '/guonWDsfHNn/device1/thing/event/open_door/post',
  12. 'generateTime': '1646841984778',
  13. 'message-id': '1501590234578562048',
  14. 'qos': '1',
  15. 'subscription': '1',
  16. 'topic': '/guonWDsfHNn/device1/thing/event/open_door/post'}
  17. body:
  18. {'checkFailedData': {},
  19. 'deviceName': 'device1',
  20. 'deviceType': 'CustomCategory',
  21. 'identifier': 'open_door',
  22. 'iotId': 'Iml0VgmYzbQv1VYueRsWguon07',
  23. 'name': '冰柜开门',
  24. 'productKey': 'guonWDsfHNn',
  25. 'requestId': 'null',
  26. 'time': 1646841984733,
  27. 'type': 'info',
  28. 'value': {'code': 1}}

目前来看和之前属性上报拿到的消息体结构差不多,业务系统只能通过判断topic结构区分属性或者事件,然后根据物模型的内容判断业务,比如这里的code=1表示们开了。

3.2.4-云端响应事件上报

  1. sys/guonWDsfHNn/${deviceName}/thing/event/${tsl.event.identifier}/post_reply
  2. sys/guonWDsfHNn/device1/thing/event/open_door/post_reply

image.png

image.png

和之前云端响应属性上报一样,我消息体随笔定义的

iot日志:
image.png

明明应该是云到设备啊。。。哎

image.png

当然因为是云到设备的功能,amqp是没有收到转发消息的。

3.3-服务

9-物模型 - 图52

3.3.1-定义异步服务

输入参数
image.png
输出参数
image.png
image.png
image.png

3.3.2-异步服务调用

image.png

  1. /sys/guonWDsfHNn/${deviceName}/thing/service/${tsl.service.identifier}
  2. /sys/guonWDsfHNn/device1/thing/service/func_open_door_async
  1. {
  2. "properties": [
  3. {
  4. "identifier": "temperature",
  5. "dataType": {
  6. "type": "int"
  7. }
  8. },
  9. {
  10. "identifier": "tmp_upload",
  11. "dataType": {
  12. "type": "struct",
  13. "specs": [
  14. {
  15. "identifier": "upload_time",
  16. "dataType": {
  17. "type": "int"
  18. }
  19. },
  20. {
  21. "identifier": "now_temp",
  22. "dataType": {
  23. "type": "float"
  24. }
  25. },
  26. {
  27. "identifier": "device_id",
  28. "dataType": {
  29. "type": "text"
  30. }
  31. }
  32. ]
  33. }
  34. }
  35. ],
  36. "events": [
  37. {
  38. "outputData": [
  39. {
  40. "identifier": "code",
  41. "dataType": {
  42. "type": "int"
  43. }
  44. }
  45. ],
  46. "identifier": "open_door",
  47. "type": "info"
  48. }
  49. ],
  50. //新增的服务
  51. "services": [
  52. {
  53. "outputData": [
  54. {
  55. "identifier": "code",
  56. "dataType": {
  57. "type": "int"
  58. }
  59. }
  60. ],
  61. "identifier": "func_open_door_async",
  62. "inputData": [
  63. {
  64. "identifier": "device_id",
  65. "dataType": {
  66. "type": "text"
  67. }
  68. }
  69. ]
  70. }
  71. ]
  72. }
  1. {
  2. "method": "thing.service.func_open_door_async",
  3. "params": {
  4. "device_id":"xxxxx"
  5. }
  6. }

原生topic方式调用服务消息体格式:https://help.aliyun.com/document_detail/89301.html#title-3pt-nfy-jys

需要强调的是:
1-服务调用必须要用api方式作命令下发,和之前的属性服务不一样,你用mqtt客户端模拟的时候虽然能通信但是amqp没法流转,因为对服务来讲是一个完整的功能,它有一个消息id在功能生命周期中,但是这个消息id只能通过api调用。

  1. {
  2. "method": "thing.service.func_open_door_async",
  3. "version": "1.0.0",
  4. "id":"397241467",//这个消息id必须是调用InvoceThingService返回的才行
  5. "params": {
  6. "device_id": "device1"
  7. }
  8. }

image.png
2-不管是同步还是异步都是同一个函数:https://help.aliyun.com/document_detail/69584.htm?spm=a2c4g.11186623.0.0.15584ec9Au4Vn7#doc-api-Iot-InvokeThingService

3.3.3-异步服务命令下发

api接口文档调用地址:https://help.aliyun.com/document_detail/69584.htm?spm=a2c4g.11186623.0.0.2773eaefRGTjKT#reference-snk-mrz-wdb

  1. import requests
  2. import uuid
  3. import datetime
  4. import hmac
  5. import hashlib
  6. import base64
  7. import pprint
  8. def percent_encoding(string):
  9. """
  10. 满足RFC3986编码的规则函数
  11. """
  12. result = ''
  13. accepted = [c for c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~'.encode('utf-8')]
  14. for char in string.encode('utf-8'):
  15. result += chr(char) if char in accepted else '%{}'.format(hex(char)[2:]).upper()
  16. return result
  17. def open_door(DeviceName=''):
  18. base_url = "https://iot.cn-shenzhen.aliyuncs.com/?" # 创建设备
  19. AccessKey_Secret = "ZEZHyWv8hh06qq6uVQbky1ejXR0iBA"
  20. params = {
  21. # 公共参数
  22. "Format": "json", # 返回内容格式为json
  23. "Version": "2018-01-20", # 固定值
  24. "AccessKeyId": "LTAI5tArgc71UVg8JRTkUar7", # AccessKeyId
  25. "SignatureMethod": "HMAC-SHA1", # 签名方式 固定值
  26. "SignatureVersion": "1.0", # 签名算法版本 固定值
  27. "SignatureNonce": str(uuid.uuid4()).replace("-", ""), # 随机字符串
  28. "RegionId": "cn-shenzhen", # 设备所在地域
  29. "Timestamp": str(datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")), # 当前请求的时间戳 根据请求动态生成
  30. # 业务接口的自定义参数
  31. "Action": "InvokeThingService",
  32. "Args": '{"device_id":"device1"}',
  33. "Identifier": 'func_open_door_async',#首次期望状态从0开始
  34. "IotInstanceId": "iot-040a0aee", # 非必传 iot实例ID
  35. "ProductKey": "guonWDsfHNn", # 产品的ProductKey。
  36. "DeviceName": DeviceName, # 非必传 为待注册的设备命名,如果不传入该参数,则由系统随机生成设备名称。
  37. }
  38. pprint.pprint(params)
  39. # 1-构造规范化的请求字符串
  40. # 参数排序后 ket value需要编码 且用$符号连接
  41. src = '&'.join(['%s=%s' % (percent_encoding(k), percent_encoding(v)) for k, v in sorted(params.items())])
  42. # 2-准备构造签名字符串
  43. string_to_sign = "GET" + "&" + percent_encoding("/") + "&" + percent_encoding(src)
  44. # 3-HMAC签名串
  45. hmac_string = hmac.new((AccessKey_Secret + "&").encode(),
  46. string_to_sign.encode(),
  47. hashlib.sha1)
  48. # 4-转换base64格式
  49. signature = base64.b64encode(hmac_string.digest()).strip()
  50. url = base_url + src + "&Signature=" + percent_encoding(signature.decode())
  51. res = requests.get(url)
  52. pprint.pprint(res.json())
  53. return 1
  54. if __name__ == "__main__":
  55. res = open_door(DeviceName="device1")
  1. {'Code': '',
  2. 'Data':
  3. {'MessageId': '2145529832'},
  4. 'RequestId': '6B2E2C3B-1384-5E07-BB32-7FF67A99B236',
  5. 'Success': True}

这个messageid需要在设备完成功能后通过“设备端响应服务调用”的topic(/sys/guonWDsfHNn/${deviceName}/thing/service/${tsl.service.identifier}_reply)要带上。
3.3.4-设备响应服务端掉用

image.png

  1. cmd
  2. 'MESSAGE'
  3. headers
  4. {'destination': '/guonWDsfHNn/device1/thing/downlink/reply/message',
  5. 'generateTime': '1646901780552',
  6. 'message-id': '1501841036232637952',
  7. 'qos': '1',
  8. 'subscription': '1',
  9. 'topic': '/guonWDsfHNn/device1/thing/downlink/reply/message'}
  10. original_headers
  11. {'destination': '/guonWDsfHNn/device1/thing/downlink/reply/message',
  12. 'generateTime': '1646901780552',
  13. 'message-id': '1501841036232637952',
  14. 'qos': '1',
  15. 'subscription': '1',
  16. 'topic': '/guonWDsfHNn/device1/thing/downlink/reply/message'}
  17. body
  18. {'checkFailedData': {},
  19. 'code': 200,
  20. 'data': {'code': 1},
  21. 'deviceName': 'device1',
  22. 'gmtCreate': 1646901780551,
  23. 'iotId': 'Iml0VgmYzbQv1VYueRsWguon07',
  24. 'productKey': 'guonWDsfHNn',
  25. 'requestId': '2145529832',
  26. 'source': 'DEVICE',
  27. 'topic': '/sys/guonWDsfHNn/device1/thing/service/func_open_door_async_reply'}

根据返回的:’requestId’: ‘2145529832’,我就可以判断我的异步的服务掉用成功了。

3.3.4-同步命令下发

我先去把这个服务改成同步:
image.png
根据文档调用是同一个接口:
https://help.aliyun.com/document_detail/89301.html#title-3pt-nfy-jys(同步服务调用介绍文档)
https://help.aliyun.com/document_detail/69584.htm?spm=a2c4g.11186623.0.0.2773eaefRGTjKT#reference-snk-mrz-wdb(InvokeThingService接口文档)

  1. # 调用阿里云iot api 物模型功能 从云到设备
  2. """
  3. 因为物模型是阿里云的默认封装的topic,这个属性设置topic刚好是设备只需要订阅的
  4. 所以我想试试调用物模型属性api设置功能,实际上是不是就是public
  5. https://help.aliyun.com/document_detail/107582.htm?spm=a2c4g.11186623.0.0.27731c80LFwEPK#reference-z5c-dwd-5gb
  6. 答案:是的
  7. 我用mqqt.fx客户端订阅:/sys/guonlFaZtGq/132426114151/thing/service/property/set
  8. 属性设置这个topic 调用次api 阿里云物联网会给这个topic中发送消息 我的客户端会收到对应的消息
  9. 于此同时还发现:
  10. 那些基础通信topic物模型topic只是阿里云帮你总结的topic
  11. 具体topic中的传递的内容需要在"功能定义"中类型wsagger文档方式编写这个topic的内容参数是什么
  12. 并且记得需要点击发布。还需要注意这个topic的accessMode是否拥有读写权限
  13. """
  14. import requests
  15. import uuid
  16. import datetime
  17. import hmac
  18. import hashlib
  19. import base64
  20. import pprint
  21. options = {
  22. "ProductKey": "guonlFaZtGq",
  23. "DeviceName": "iot-fridge-1",
  24. "DeviceSecret": "f93aa96c371bfd3f8a441c2c2079db97"
  25. }
  26. def percent_encoding(string):
  27. """
  28. 满足RFC3986编码的规则函数
  29. """
  30. result = ''
  31. accepted = [c for c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~'.encode('utf-8')]
  32. for char in string.encode('utf-8'):
  33. result += chr(char) if char in accepted else '%{}'.format(hex(char)[2:]).upper()
  34. return result
  35. def open_door(DeviceName=''):
  36. base_url = "https://iot.cn-shenzhen.aliyuncs.com/?" # 创建设备
  37. AccessKey_Secret = "ZEZHyWv8hh06qq6uVQbky1ejXR0iBA"
  38. params = {
  39. # 公共参数
  40. "Format": "json", # 返回内容格式为json
  41. "Version": "2018-01-20", # 固定值
  42. "AccessKeyId": "LTAI5tArgc71UVg8JRTkUar7", # AccessKeyId
  43. "SignatureMethod": "HMAC-SHA1", # 签名方式 固定值
  44. "SignatureVersion": "1.0", # 签名算法版本 固定值
  45. "SignatureNonce": str(uuid.uuid4()).replace("-", ""), # 随机字符串
  46. "RegionId": "cn-shenzhen", # 设备所在地域
  47. "Timestamp": str(datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")), # 当前请求的时间戳 根据请求动态生成
  48. # 业务接口的自定义参数
  49. "Action": "InvokeThingService",
  50. "Args": '{"device_id":"device1"}',
  51. "Identifier": 'func_open_door_async',#首次期望状态从0开始
  52. "IotInstanceId": "iot-040a0aee", # 非必传 iot实例ID
  53. "ProductKey": "guonWDsfHNn", # 产品的ProductKey。
  54. "DeviceName": DeviceName, # 非必传 为待注册的设备命名,如果不传入该参数,则由系统随机生成设备名称。
  55. }
  56. pprint.pprint(params)
  57. # 1-构造规范化的请求字符串
  58. # 参数排序后 ket value需要编码 且用$符号连接
  59. src = '&'.join(['%s=%s' % (percent_encoding(k), percent_encoding(v)) for k, v in sorted(params.items())])
  60. # 2-准备构造签名字符串
  61. string_to_sign = "GET" + "&" + percent_encoding("/") + "&" + percent_encoding(src)
  62. # 3-HMAC签名串
  63. hmac_string = hmac.new((AccessKey_Secret + "&").encode(),
  64. string_to_sign.encode(),
  65. hashlib.sha1)
  66. # 4-转换base64格式
  67. signature = base64.b64encode(hmac_string.digest()).strip()
  68. url = base_url + src + "&Signature=" + percent_encoding(signature.decode())
  69. res = requests.get(url)
  70. pprint.pprint(res.json())
  71. return 1
  72. if __name__ == "__main__":
  73. res = open_door(DeviceName="device1")

因为是同一个接口,这的代码和上面调用异步服务python代码是一样的

  1. {'Code': '',
  2. 'Data': {'MessageId': '444960131'},
  3. 'RequestId': '21024E89-A475-56B8-8D4D-626A8856F46F',

从实际调用上讲感觉不出来任何同步和异步调用的区别,但是异步调用的返回体的MessageId是可以通过“设备端响应服务调用”的topic上报,被流转到amqp客户端的。
但是同步的情况下比如这里的’MessageId’: ‘444960131’,通过“设备端响应服务调用”的topic上报的时候amqp的客户端是没有任何反应的,因为同步的生命周期已经结束了。
至于同步怎么实现的具体看文档:https://help.aliyun.com/document_detail/90567.htm?spm=a2c4g.11186623.0.0.1558eaefBLtcTu#concept-zlp-gsl-cfb

4-其他

  1. 'MESSAGE'
  2. {'destination': '/as/mqtt/status/guonWDsfHNn/device1',
  3. 'generateTime': '1646844865245',
  4. 'message-id': '1501602316132812800',
  5. 'qos': '1',
  6. 'subscription': '1',
  7. 'topic': '/as/mqtt/status/guonWDsfHNn/device1'}
  8. {'destination': '/as/mqtt/status/guonWDsfHNn/device1',
  9. 'generateTime': '1646844865245',
  10. 'message-id': '1501602316132812800',
  11. 'qos': '1',
  12. 'subscription': '1',
  13. 'topic': '/as/mqtt/status/guonWDsfHNn/device1'}
  14. {'clientIp': '119.123.132.232',
  15. 'deviceName': 'device1',
  16. 'iotId': 'Iml0VgmYzbQv1VYueRsWguon07',
  17. 'lastTime': '2022-03-10 00:54:25.233',
  18. 'offlineReasonCode': 1912,
  19. 'productKey': 'guonWDsfHNn',
  20. 'status': 'offline',
  21. 'time': '2022-03-10 00:54:25.233',
  22. 'utcLastTime': '2022-03-09T16:54:25.233Z',
  23. 'utcTime': '2022-03-09T16:54:25.233Z'}
  1. {'destination': '/as/mqtt/status/guonWDsfHNn/device1',
  2. 'generateTime': '1646844914267',
  3. 'message-id': '1501602521745990144',
  4. 'qos': '1',
  5. 'subscription': '1',
  6. 'topic': '/as/mqtt/status/guonWDsfHNn/device1'}
  7. {'destination': '/as/mqtt/status/guonWDsfHNn/device1',
  8. 'generateTime': '1646844914267',
  9. 'message-id': '1501602521745990144',
  10. 'qos': '1',
  11. 'subscription': '1',
  12. 'topic': '/as/mqtt/status/guonWDsfHNn/device1'}
  13. {'clientIp': '119.123.132.232',
  14. 'deviceName': 'device1',
  15. 'iotId': 'Iml0VgmYzbQv1VYueRsWguon07',
  16. 'lastTime': '2022-03-10 00:55:14.256',
  17. 'productKey': 'guonWDsfHNn',
  18. 'status': 'online',
  19. 'time': '2022-03-10 00:55:14.256',
  20. 'utcLastTime': '2022-03-09T16:55:14.256Z',
  21. 'utcTime': '2022-03-09T16:55:14.256Z'}