单元 3: 将个人电脑连接至 EnOS 并采集数据


在 EnOS 管理控制台上完成 PC 的设备建模、设备注册、和数据存储策略配置之后,你现在可以使用 EnOS Java SDK for MQTT 进行编程,将 PC 连接到 EnOS 并开始采集数据。


有关使用 EnOS Java SDK for MQTT 的详细信息,参阅 GitHub 上的自述文件。

步骤 1: 配置开发环境

EnOS Java SDK for MQTT 要求安装 Java SE 8 和 Maven 3。通过以下步骤配置开发环境。

  1. 安装 JDK,下载地址:https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

  2. 安装 Maven,下载地址:http://maven.apache.org/download.cgi

  3. 安装开发环境,如 IntelliJ IDEA,下载地址:https://www.jetbrains.com/idea/download/

  4. 在已创建项目的 pom.xml 中,添加 EnOS Java SDK for MQTT 的依赖:

    <dependency>
        <groupId>com.envisioniot</groupId>
        <artifactId>enos-mqtt</artifactId>
        <version>2.2.16</version>
    </dependency>
    


  5. 在你开发项目的主 pom.xml 文件中,将 oshi(用于摄取计算机操作系统和硬件信息的开源插件)添加为依赖项,如下所示:

    <dependency>
        <groupId>com.github.oshi</groupId>
        <artifactId>oshi-core</artifactId>
        <version>3.13.2</version>
    </dependency>
    

步骤 2. 设备连接编程

设置开发环境后,通过以下步骤将 PC 连接到 EnOS 云端:

  1. 声明将在程序中使用的变量,参见以下示例:

    private static final String uri = "tcp://{address}:{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;
    
    • 服务器的 addressport 和安装的 EnOS 实例相关。对于私有云实例,请登录 EnOS 管理控制台点击 帮助 > 环境信息 获取 MQTT Broker 的地址和端口信息。

    • productKeydeviceKeydeviceSecret 是在 单元 1 中注册PC时生成的设备属性。


  2. 声明 main 函数 connect(),初始化设备连接。参见以下示例:

    public static void main(String[] args) throws Exception {
        connect();
    }
    


  3. 使用 connect() 函数将 PC 连接到 EnOS 云端。参见以下代码示例:

    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 ConnCallback(){
             public void connectComplete(boolean reconnect) {
                 System.out.println("connect success");
             }
    
             public void connectLost(Throwable cause) {
                 System.out.println("onConnectLost");
             }
    
             public void connectFailed(Throwable cause) {
                 System.out.println("onConnectFailed : " + cause);
             }
         });
        }
        catch (Throwable var1) {
        }
        System.out.println("connect result :" + client.isConnected());
    }
    

步骤 3. 采集数据并将数据上传到 EnOS 云端

将 PC 连接到 EnOS 后,通过以下步骤采集 PC 的系统和硬件数据,并将数据上传到 EnOS 云端:

  1. 使用 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;
    }
    


  2. 使用 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();
        }
    }
    


  3. 使用 postMeasurepoint 函数,将采集的 CPU 负载和内存使用数据上传到 EnOS 云端。参考以下代码示例:

    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. 运行程序并检查结果

  1. 编译并运行程序以进行设备连接和数据采集。参考以下程序代码示例:

    import java.util.HashMap;
    import java.util.Map;
    
    import com.envisioniot.enos.iot_mqtt_sdk.core.ConnCallback;
    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 ConnCallback() {
                    @Override
                    public void connectComplete(boolean reconnect) {
                        System.out.println("connect success");
                    }
    
                    @Override
                    public void connectLost(Throwable cause) {
                        System.out.println("onConnectLost");
                    }
    
                    @Override
                    public void connectFailed(Throwable cause) {
                        System.out.println("onConnectFailed : " + cause);
                    }
    
                });
            } catch (Throwable var1) {
            }
            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 云端
        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();
            }
        }
    }
    


  2. 检查程序的运行结果。如果设备连接成功,程序将返回以下示例结果:

    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}}
    


  3. 在 EnOS 管理控制台上的 设备列表 中检查 PC 设备的状态变更。设备的状态将从 未激活 更改为 在线


    ../../_images/device_status1.png


  4. 设备详情 页面的 属性 选项卡下,检查已更新的 PC 设备的属性。


    ../../_images/updated_attributes.png


  5. 检查 设备详情 页面上 测点 选项卡下发布到云端的 cpu_usedmem_used 测点的数据。


    ../../_images/uploaded_data.png

下一单元

监测 CPU 负载