官网的gateway是用python写的,这在imx6ull等资源有限的cpu上基本带不动。但又需要借助网关功能将设备信息传输到iot平台。这种情况就可以自己写个简单的功能替换掉python程序。
1 mqtt连接iot平台:
mqtt_init(gateway.gwName, addr, gateway.gwAccessToken, NULL, (MSG_RECIVE_CALLBACL)gw_recive_msg_callback);
其中addr为“IP:端口”格式,gwAccessToken为iot平台上该网关对应的token
2 需要订阅的topic
//device subscribe
i32 ret = mqtt_subscribe(gateway.handle, ATTRIBUTES_TOPIC, ONECE_LATEST);
ret |= mqtt_subscribe(gateway.handle, ATTRIBUTES_TOPIC_RESPONSE_ANY, ONECE_LATEST);
ret |= mqtt_subscribe(gateway.handle, RPC_REQUEST_TOPIC_ANY, ONECE_LATEST);
ret |= mqtt_subscribe(gateway.handle, RPC_RESPONSE_TOPIC_ANY, ONECE_LATEST);
//gateway subscribe
ret |= mqtt_subscribe(gateway.handle, GATEWAY_ATTRIBUTES_TOPIC, ONECE_LATEST);
ret |= mqtt_subscribe(gateway.handle, GATEWAY_ATTRIBUTES_RESPONSE_TOPIC, ONECE_LATEST);
ret |= mqtt_subscribe(gateway.handle, GATEWAY_RPC_TOPIC, ONECE_LATEST);
其中宏定义如下
#define GATEWAY_ATTRIBUTES_TOPIC "v1/gateway/attributes"
#define GATEWAY_TELEMETRY_TOPIC "v1/gateway/telemetry"
#define GATEWAY_ATTRIBUTES_REQUEST_TOPIC "v1/gateway/attributes/request"
#define GATEWAY_ATTRIBUTES_RESPONSE_TOPIC "v1/gateway/attributes/response"
#define GATEWAY_MAIN_TOPIC "v1/gateway/"
#define GATEWAY_TOPIC_CONNECT "v1/gateway/connect"
#define GATEWAY_TOPIC_DISCONNECT "v1/gateway/disconnect"
#define GATEWAY_RPC_TOPIC "v1/gateway/rpc"
#define GATEWAY_RPC_RESPONSE_TOPIC "v1/gateway/rpc/response"
#define GATEWAY_CLAIMING_TOPIC "v1/gateway/claim"
#define RPC_RESPONSE_TOPIC "v1/devices/me/rpc/response/"
#define RPC_RESPONSE_TOPIC_ANY "v1/devices/me/rpc/response/+"
#define RPC_REQUEST_TOPIC "v1/devices/me/rpc/request/"
#define RPC_REQUEST_TOPIC_ANY "v1/devices/me/rpc/request/+"
#define ATTRIBUTES_TOPIC "v1/devices/me/attributes"
#define ATTRIBUTES_TOPIC_RESPONSE_ANY "v1/devices/me/attributes/response/+"
#define ATTRIBUTES_TOPIC_REQUEST "v1/devices/me/attributes/request/"
#define ATTRIBUTES_TOPIC_RESPONSE "v1/devices/me/attributes/response/"
#define TELEMETRY_TOPIC "v1/devices/me/telemetry"
#define CLAIMING_TOPIC "v1/devices/me/claim"
3 网关属性上传,网关需要上传一些属性时,可以使用此topic上传
topic为:
v1/devices/me/attributes
数据格式为:
{"devType":"gateway","uptime":2}
也可以在前面添加ts关键字段
{"ts":1606214325915,"values":{"devType":"gateway","uptime":2}}
4 设备上报属性前要先发送连接信息,否则iot会生成一个类型为default的设备
topic为:
v1/gateway/connect
数据格式为:
{"device":"123456","type":"led"}
5 设备掉线后,可以向平台发送离线信息
topic为:
v1/gateway/disconnect
数据格式为:
{"device":"123456","type":"led"}
6 设备发送属性字段
topic为:
v1/gateway/attributes
数据格式为:
{"123456":[{"msgType":"live","counter":0}]}
7 设备发送遥测数据
topic为:
v1/gateway/telemetry
数据格式为:
{"123456":[{"msgType":"live","counter":0}]}
8 接收远程rpc信息
需关注的topic为:
v1/gateway/rpc
接收到的数据格式:
{"device":"123456","data":{"id":0,"method":"setValue","params":{"msgType":"set","devType":2,"ledColor":"green"}}}
这样就基本满足设备与iot平台的通信要求了。