单元 4:模拟设备测点数据及结果¶
温度传感器和空调设备连接到 EnOS 云端之后,便可使用 EnOS Device SDK 模拟温度传感器的温度数据,并将模拟的数据上传到 EnOS 云端和发送指令至空调设备调节温度。详细步骤如下。
导入以下内容。
import com.envisioniot.enos.iot_mqtt_sdk.core.exception.EnvisionException; import com.envisioniot.enos.iot_mqtt_sdk.core.msg.IMessageHandler; import com.envisioniot.enos.iot_mqtt_sdk.message.downstream.tsl.ServiceInvocationCommand; import com.envisioniot.enos.iot_mqtt_sdk.message.downstream.tsl.ServiceInvocationReply; import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostRequest; import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostResponse; import com.google.common.collect.Maps; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
设置温度传感器和空调设备的处理程序,并将测点上报到 EnOS。
public static void main(String[] args) throws Exception { initWithCallback(); // Set handler to handle measurepoint set commands airConClient.setArrivedMsgHandler(ServiceInvocationCommand.class, new SvcHandler()); // Set handler to handle measurepoint set commands sensorClient.setArrivedMsgHandler(ServiceInvocationCommand.class, new SvcHandler()); // Post measurement point int loop = 100; while ((--loop) >= 0) { postMeasurepoint(); TimeUnit.SECONDS.sleep(3L); } }
使用
postMeasurepoint
函数模拟上报温度传感器设备的测点。测点将通过 Checkpoint 节点将信息路由到 EnOS_default 规则,保存到 EnOS,而当路由规则中的Script Switch 节点检测到信息的temperature
参数超过 30 时,把信息路由到 Send Command 节点。static void postMeasurepoint() throws EnvisionException { // device measurement points are defined in the model, which can be viewed in Model Details page in EnOS Console MeasurepointPostRequest request = MeasurepointPostRequest.builder() .addMeasurePoint("temperature", 37) .build(); MeasurepointPostResponse response = sensorClient.publish(request); System.out.println(response); }
使用
SvcHandler
函数处理测点和设置指令。 当路由规则中的 Send Command 节点发送包含ctrlTemperature
参数的消息时,空调设备将响应温度为 22。static class SvcHandler implements IMessageHandler<ServiceInvocationCommand, ServiceInvocationReply> { @Override public ServiceInvocationReply onMessage(ServiceInvocationCommand arrivedMessage, List<String> argList) throws Exception { System.out.println("svc msg: " + arrivedMessage); if (arrivedMessage.<Map<String, String>>getParams().containsKey("ctrlTemperature")) { Map<String, Object> datas = Maps.newHashMap(); datas.put("newTemperature", 22); return ServiceInvocationReply.builder() .setCode(200) .setOutputDatas(datas) .build(); } else { return ServiceInvocationReply.builder() .setCode(406) .setMessage("unknown sev") .build(); } } }
结果¶
程序将根据上述步骤 3 中指定的内容模拟传感器温度数据,并将数据上传到 EnOS 云端。打开 温度传感器 设备的 设备详情 页面,点击 测点,便可查看温度传感器的模拟温度数据。
由于模拟温度在 30 度以上,空调设备会发出指令,而依次响应步骤 4 中的温度。打开 空调设备 设备的 设备详情 页面,点击 命令,查看空调设备的命令和响应。