文章目录
ThingsBoard IoT Gateway 实战(二)- 通过 Request Connector 获取天气
1. 问题描述
用API接口查询天气
2. 分析设计
在 ThingsBoard IoT Gateway 中,访问外部API是通过 Request 连接器实现的。
3. 平台配置
本节进行Thingsboard平台中网关的新增配置,如果已经配置,请直接跳到下一节。
使用默认的租户登录Thingsboard平台,在界面上配置网关:
进入添加新设备页面:添加Token,这里设为
ENV_GATEWAY_TOEKN
, 后面会用到。
客户可以不配置,直接把这个设备挂在租户下面就可以了。
可以在设备列表中看到这个网关:
4. 三方平台模拟
由于第三方平台五花八门,我们自己新建app.py
,写一个天气接口作为模拟:
# -*- coding: utf-8 -*-
from flask import Flask, jsonify
from flask_basicauth import BasicAuth
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False # 返回JSON字符串中文修正
app.config['BASIC_AUTH_USERNAME'] = 'admin'
app.config['BASIC_AUTH_PASSWORD'] = '123456'
app.config['BASIC_AUTH_FORCE'] = True # 整个站点都验证
basic_auth = BasicAuth(app)
@app.route('/weather')
def weather():
return jsonify({"weather":"晴","temp":25.6,"sensorName":"ENV-002", "sensorType": "out"})
if __name__ == '__main__':
app.run(debug=True)
代码使用步骤说明:
- 安装Python: 官网下载最新版本即可
- 安装Flask: 命令行
pip install flask
- 编写代码:新建文件
app.py
写入上面这段代码 - 运行代码:命令行
python app.py
5. 网关配置
到网关配置文件夹编辑tb_gateway.yaml文件。
vim /etc/thingsboard-gateway/config/tb_gateway.yaml
将“thingsboard”部分中的主机和端口属性值改为ThingsBoard主机和端口。
将“security”部分中的access token修改为访问令牌,也就是ENV_GATEWAY_TOEKN。
网关配置关键部分如下:
thingsboard:
host: thingsboard平台的IP地址
port: 1883
security:
accessToken: thingsboard平台中配置的网关的token,这里是 ENV_GATEWAY_TOEKN
connectors:
-
name: REQUEST Connector
type: request
configuration: request_env.json
json配置
{
"host": "http://127.0.0.1:5000",
"SSLVerify": false,
"security": {
"type": "basic",
"username": "admin",
"password": "123456"
},
"mapping": [
{
"url": "weather",
"httpMethod": "GET",
"httpHeaders": {
"ACCEPT": "application/json"
},
"allowRedirects": true,
"timeout": 0.5,
"scanPeriod": 5,
"converter": {
"type": "json",
"deviceNameJsonExpression": "${sensorName}",
"deviceTypeJsonExpression": "${sensorType}",
"telemetry": [
{
"type": "double",
"key": "temperature",
"value": "${temp}"
},
{
"type": "string",
"key": "weather",
"value": "${weather}"
}
]
}
}
]
}
注意:
- scanPeriod 是 请求的时间间隔,这里是5秒请求一次。
- rest 和 request 连接器的部分参数名称有区别,请注意分辨。
eg. 遥测在 rest 中是解析 timeseries 字段,request中是解析 telemetry 字段。
6. 查看结果
设备列表中出现了一个代表外部天气API的设备ENV-002
:
可以看到5s刷新一次遥测数据:
由于 deviceNameJsonExpression 可以使用表达式也可以直接使用字符串,
实际项目中,我们可以用城市名称或者区域名称+天气来做设备名,
"deviceNameJsonExpression":"深圳天气",
会比较直观。
7. 下一步
这节讲解网关通过HTTP请求连接器获取设备遥测消息。
下节我们看看网关通过MQTT连接器和窗帘进行交互,剧透一下: