ThingsGateway(六)MqttClient插件实战
项目地址
Gitee源代码仓库:https://gitee.com/diego2098/ThingsGateway
Github源代码仓库:https://github.com/kimdiego2098/ThingsGateway
使用文档:https://diego2098.gitee.io/thingsgateway-docs/
一、前言
ThingsGateway是国内新生开源项目,归属工业数据采集网关,经过近四个月的洗礼,已经趋于稳定
二、准备测试环境
2、MQTTX
3、EMQX
运行ThingsGateway的方法请查看源文档
在操作之前应已建立任意变量,并且启动emqx
三、通讯测试
建立MqttClient插件设备,重启运行态后可以看到设备已经初始化完成,测试客户端我们使用MQTTX进行连接测试,输入对应的参数后,这里还需要订阅变量Topic(ThingsGateway/Variable),可以看到数据变化后网关发布出的Json数据
四、RPC写入值
启用Rpc写入,往Topic为ThingsGatewat/RpcWrite中发送
{
"key":"test400001",
"Value":"1",
"RpcId":"testid123456"
}
可以看到回复
{"RpcId":"testid123456","Message":"操作成功","Success":true}
五、动态Json配置
上例中的Json数据实际上是网关内部的固定实体类序列化的,但有时我们不需要这么多数据,或者需要自定义格式,可以使用实体配置脚本`
//定义返回List
List<dynamic> newModelList=new List<dynamic>();
//input为固定传入值,在变量脚本中为变量实体类List,在设备脚本中为设备实体类List,查看上面的json说明
foreach (var item in input)
{
//添加自定义值
newModelList.Add(new
{
customName=item.Name,//变量名称
customValue=item.Value,//变量值
customCollectTime=item.CollectTime.ToString("yyyy-MM-dd HH:mm:ss fffffff"), //采集时间,这里格式化为自定义时间格式
});
}
return newModelList;
可以看到,通过脚本转化之后,实际传输的json键名称已经改为了脚本内的customName、customValue与customCollectTime