ThingsCloud 支持多种类型的消息规则,其中的 属性上报预处理 规则,经常用来对设备上报的原始数据,进行各种自定义的计算和处理,达到我们需要的数据格式。
本期最佳实践,我们以常用的风向传感器为例,通过采集到的原始风向角度值(例如:30度),来生成风向名称文字(例如:北风)。
某客户在项目中搭建了综合环境采集设备,通过 RS485 风向传感器,成功采集到风向角度值,如下:
客户希望获得直观的风向名称,在了解 ThingsCloud 规则引擎后,尝试采用属性上报预处理规则来实现。
通过 RS485 风向传感器手册,或者任何关于风向角度定义的知识,我们很容易建立角度值到风向名称的函数关系,这是一个分段函数。
虽然有些传感器会支持风向档位,可以直接映射到风向名称,如上图。但是在本期实践中,我们希望不依赖对风向档位值,而做到适应所有的风向传感器,用风向角度值来作为原始数据。
为了生成风向名称,我们先建立一个新的属性,如下:
然后创建一个属性上报预处理规则,如下:
在规则操作中,使用 预处理函数,如下:
在函数编辑框中,编写一段 Javascript
代码。
代码如下:
module.exports = function (report_attributes) {
/**
* report_attributes: 上报的属性对象,同时作为函数返回值。函数中可更新属性对象。
*/
if (report_attributes.wind_direction !== undefined) {
if (report_attributes.wind_direction >= 340) {
report_attributes.wind_direction_text = '北风';
} else if (report_attributes.wind_direction >= 295) {
report_attributes.wind_direction_text = '西北风';
} else if (report_attributes.wind_direction >= 250) {
report_attributes.wind_direction_text = '西风';
} else if (report_attributes.wind_direction >= 205) {
report_attributes.wind_direction_text = '西南风';
} else if (report_attributes.wind_direction >= 160) {
report_attributes.wind_direction_text = '南风';
} else if (report_attributes.wind_direction >= 115) {
report_attributes.wind_direction_text = '东南风';
} else if (report_attributes.wind_direction >= 70) {
report_attributes.wind_direction_text = '东风';
} else if (report_attributes.wind_direction >= 25) {
report_attributes.wind_direction_text = '东北风';
} else if (report_attributes.wind_direction >= 0) {
report_attributes.wind_direction_text = '北风';
}
}
return report_attributes;
}
规则保存生效后,可以在设备的消息日志中,看到每次上报风向角度值时,同时附带了另一个属性,那就是通过属性上报预处理规则函数计算生成的风向名称文字。
生成的风向文字属性,在控制台中我们可以直接查看,还可以展示在看板、大屏、手机 App 中,甚至通过 API 读取后随你怎么使用。
通过这一期实践,希望您可以快速掌握属性上报预处理规则的应用。更多关于消息规则的内容,请您浏览:
关于 ThingsCloud
ThingsCloud 是新一代物联网设备统一接入平台,帮助企业在极短的时间内搭建个性化的物联网平台和应用,并适应不断变化的发展需求。目前广泛应用于制造、电力、能源、环境、农业、楼宇、家居、教育、交通、物流、自动化等领域。
ThingsCloud 可接入各类网关,传感器、执行器、控制器、通信模组、智能硬件等,实现数据采集、远程控制,数据分析、告警通知、智能联动。还可以零代码生成项目应用 SaaS 和用户应用 App,并开放 API 和实时消息,便于业务系统集成和扩展开发。
通过使用 ThingsCloud,企业可以大大缩短搭建物联网系统的时间,节省软件开发费用,降低定制开发的风险,快速落地数字化和智能化项目。我们的客户遍布各行业,包括中国石化、中国铁塔、中国燃气、吉林大学、北控水务、ACE、中国民航大学、西安交通大学、精量电子、大秦铁路、宁波水利局等。