单元 3: 将个人电脑连接至EnOS并采集数据¶
在EnOS 管理控制台上完成PC的设备建模、设备注册和数据存储策略配置之后,您现在可以使用EnOS Java SDK for MQTT进行编程,以将PC连接到EnOS并开始采集数据。
有关用于MQTT的EnOS Java SDK的详细信息,请参阅以下网站上的自述文件。 GitHub.
步骤 1: 搭建开发环境¶
EnOS Java SDK for MQTT要求安装Java SE 8 and Maven 3。 按照以下步骤设置开发环境:
安装JDK,下载地址:https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html.
安装Maven,下载地址:http://maven.apache.org/download.cgi.
安装开发环境,如IntelliJ IDEA,下载地址:https://www.jetbrains.com/idea/download/。
在你的创建的project的
pom.xml
中,添加EnOS Java SDK for MQTT的依赖如下:<dependency> <groupId>com.envisioniot</groupId> <artifactId>enos-mqtt</artifactId> <version>2.1.2</version> </dependency>
在你开发项目的主
pom.xml
文件中,将oshi(用于摄取计算机操作系统和硬件信息的开源插件)添加为依赖项,如下所示:<dependency> <groupId>com.github.oshi</groupId> <artifactId>oshi-core</artifactId> <version>3.13.2</version> </dependency>
步骤 2. 设备连接编程¶
设置开发环境后,请执行以下步骤将PC连接到EnOS Cloud:
声明将在程序中使用的变量,请参见以下示例:
private static final String uri = "tcp://{host}:{port}"; private static final String productKey = "product_key"; private static final String deviceKey = "device_key"; private static final String deviceSecret = "device_secret"; private static MqttClient client;
服务器的
host
和port
随云区域和实例的不同而不同。对于私有云实例,请联系您的Envision项目经理或支持代表以获取主机和端口信息。productKey
,deviceKey
和deviceSecret
是在 单元 1中注册PC时生成的设备属性。
声明主要函数
connect()
初始化设备连接。请参见以下示例:public static void main(String[] args) throws Exception { connect(); }
使用“连接”功能将PC连接到EnOS Cloud。请参见以下代码段:
public static void connect() { System.out.println("Start connect with callback ... "); try { client = new MqttClient(uri, productKey, deviceKey, deviceSecret); // json device client.getProfile().setConnectionTimeout(60).setAutoReconnect(true); client.connect(new IConnectCallback() { @Override public void onConnectSuccess() { System.out.println("connect success"); } @Override public void onConnectLost() { System.out.println("onConnectLost"); } @Override public void onConnectFailed(int reasonCode) { System.out.println("onConnectFailed : " + reasonCode); } }); } catch (EnvisionException e) { e.printStackTrace(); } System.out.println("connect result :" + client.isConnected()); }
步骤 3. 编程以采集数据并将数据上传到EnOS Cloud¶
将PC连接到EnOS后,请按照以下步骤提取PC的系统和硬件数据,并将数据上传到EnOS Cloud:
使用
collectDeviceInfo()
函数提取PC的系统和硬件数据。请参见以下代码段:public static Map<String, Object> collectDeviceInfo() { oshi.SystemInfo si = new oshi.SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); OperatingSystem os = si.getOperatingSystem(); Map<String, Object> data=new HashMap<String, Object>(); data.put("system", os.toString()); data.put("model", hal.getComputerSystem().getManufacturer() + " " + hal.getComputerSystem().getModel()); data.put("cpu_core", hal.getProcessor().getLogicalProcessorCount()); data.put("cpu_used", hal.getProcessor().getSystemCpuLoad()); data.put("mem_total", hal.getMemory().getTotal()); data.put("mem_used", hal.getMemory().getAvailable()); data.put("cpu_used_average", hal.getProcessor().getSystemLoadAverage()); data.put("cpu_temperature", hal.getSensors().getCpuTemperature()); return data; }
使用“ updateAttribute()”函数使用已摄取的系统和硬件数据更新EnOS 管理控制台上PC设备的属性。请参见以下代码段:
public static void updateAttribute(){ Map<String, Object> deviceInfo= collectDeviceInfo(); System.out.println("Computer info: "+deviceInfo); AttributeUpdateRequest request = AttributeUpdateRequest.builder() .setQos(1) .addAttribute("system", deviceInfo.get("system")) .addAttribute("model", deviceInfo.get("model")) .addAttribute("cpu_core", deviceInfo.get("cpu_core")) .addAttribute("mem_total", deviceInfo.get("mem_total")) .build(); System.out.println(">>> Update Attribute: "+request); try { AttributeUpdateResponse resp = client.publish(request); System.out.println("<-- " + resp); } catch (Exception e) { e.printStackTrace(); } }
使用
postMeasurepoint
函数将摄取的CPU负载和内存使用情况数据上传到EnOS Cloud。请参见以下代码段:public static void postMeasurepoint(Map<String, Object> systemInfo) { MeasurepointPostRequest request = MeasurepointPostRequest.builder() .setQos(0) .addMeasurePoint("cpu_used", Double.parseDouble(systemInfo.get("cpu_used").toString())+0.0) .addMeasurePoint("mem_used", systemInfo.get("mem_used")) .build(); System.out.println(">>> Post Measurepoint: "+request); try { MeasurepointPostResponse resp = client.publish(request); System.out.println("<-- " + resp); } catch (Exception e) { e.printStackTrace(); } }
步骤 4. 运行程序并检查结果¶
编译并运行程序以进行设备连接和数据提取。请参见以下程序代码示例:
import java.util.HashMap; import java.util.Map; import com.envisioniot.enos.iot_mqtt_sdk.core.IConnectCallback; import com.envisioniot.enos.iot_mqtt_sdk.core.MqttClient; import com.envisioniot.enos.iot_mqtt_sdk.core.exception.EnvisionException; import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.*; import oshi.hardware.HardwareAbstractionLayer; import oshi.software.os.OperatingSystem; public class Sample { private static final String uri = "tcp://{host}:{port}"; private static final String productKey = "product_key"; private static final String deviceKey = "device_key"; private static final String deviceSecret = "device_secret"; private static MqttClient client; public static void main(String[] args) throws Exception { connect(); updateAttribute(); } // Device connection initialization public static void connect() { System.out.println("start connect with callback ... "); try { client = new MqttClient(uri, productKey, deviceKey, deviceSecret); client.getProfile().setConnectionTimeout(60).setAutoReconnect(true); client.connect(new IConnectCallback() { @Override public void onConnectSuccess() { System.out.println("connect success"); } @Override public void onConnectLost() { System.out.println("onConnectLost"); } @Override public void onConnectFailed(int reasonCode) { System.out.println("onConnectFailed : " + reasonCode); } }); } catch (EnvisionException e) { e.printStackTrace(); } System.out.println("connect result :" + client.isConnected()); } // Ingesting PC system and hardware data public static Map<String, Object> collectDeviceInfo() { oshi.SystemInfo si = new oshi.SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); OperatingSystem os = si.getOperatingSystem(); Map<String, Object> data = new HashMap<String, Object>(); data.put("system", os.toString()); data.put("model", hal.getComputerSystem().getManufacturer() + " " + hal.getComputerSystem().getModel()); data.put("cpu_core", hal.getProcessor().getLogicalProcessorCount()); data.put("cpu_used", hal.getProcessor().getSystemCpuLoad()); data.put("mem_total", hal.getMemory().getTotal()); data.put("mem_used", hal.getMemory().getAvailable()); data.put("cpu_used_average", hal.getProcessor().getSystemLoadAverage()); data.put("cpu_temperature", hal.getSensors().getCpuTemperature()); return data; } // Updating PC attributes with the ingested system and hardware data public static void updateAttribute(){ Map<String, Object> deviceInfo= collectDeviceInfo(); System.out.println("Computer info: "+deviceInfo); AttributeUpdateRequest request = AttributeUpdateRequest.builder() .setQos(1) .addAttribute("system", deviceInfo.get("system")) .addAttribute("model", deviceInfo.get("model")) .addAttribute("cpu_core", deviceInfo.get("cpu_core")) .addAttribute("mem_total", deviceInfo.get("mem_total")) .build(); System.out.println(">>> Update Attribute: "+request); try { AttributeUpdateResponse resp = client.publish(request); System.out.println("<-- " + resp); } catch (Exception e) { e.printStackTrace(); } } // Uploading PC system data into EnOS Cloud public static void postMeasurepoint(Map<String, Object> systemInfo) { MeasurepointPostRequest request = MeasurepointPostRequest.builder() .setQos(0) .addMeasurePoint("cpu_used", Double.parseDouble(systemInfo.get("cpu_used").toString())+0.0) .addMeasurePoint("mem_used", systemInfo.get("mem_used")) .build(); System.out.println(">>> Post Measurepoint: "+request); try { MeasurepointPostResponse resp = client.publish(request); System.out.println("<-- " + resp); } catch (Exception e) { e.printStackTrace(); } } }
检查程序的运行结果。如果设备连接成功,程序将返回以下示例结果:
Start connect with callback ... connect result :true connect success Computer info: {mem_used=1401421824, cpu_used_average=-1.0, cpu_temperature=0.0, cpu_used=1.0, system=Microsoft Windows 10 build 17134, cpu_core=4, model=LENOVO 80T9, mem_total=8135401472} >>> Update Attribute: AnswerableMessageBody{id='null', method='thing.attribute.update', version='null', params={attributes={system=Microsoft Windows 10 build 17134, cpu_core=4, model=LENOVO 80T9, mem_total=8135401472}}} >>>Post Measurepoint: AnswerableMessageBody{id='null', method='thing.measurepoint.post', version='null', params={measurepoints={mem_used=1314672640, cpu_used=0.4697233989534014}, time=1565841030584}}
在EnOS 管理控制台上的 设备列表 中检查PC设备的状态更改。设备的状态将从 未激活 更改为 在线。
在 设备详情 页面的 属性 选项卡下,检查已更新的PC设备的属性。
检查 设备详情 页面上 测点 选项卡下发布到云的
cpu_used
和mem_used
测点的数据。