文档首页> IoT边缘 IoTEdge> 常见问题> 子设备管理> 集成ModuleSDK后,上报数据成功后,设备状态显示为未激活,如何上报子设备状态?
更新时间:2022-07-26 GMT+08:00
分享

集成ModuleSDK后,上报数据成功后,设备状态显示为未激活,如何上报子设备状态?

集成ModuleSDK后,目前边缘非直连设备,不能动态获取设备状态,只能根据自身业务是否正常,主动上报设备状态,来更新设备状态。

代码解析:

片段一:初始化构造函数,初始化设备状态数据。

public class ModbusDriver implements GatewayCallback {
    /**
     * 驱动客户端,与边缘Hub建立MQTT连接
     */
    private DriverClient driverClient;

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    //ONLINE:设备在线。
    //OFFLINE:设备离线。
    //ABNORMAL:设备异常。
    //INACTIVE:设备未激活。
    //FROZEN:设备冻结。
    static HashMap<String, String> dataMap = new HashMap() {
        private static final long serialVersionUID = 821550418990759366L;

        {
            this.put("0", "ONLINE");//在线
            this.put("1", "OFFLINE");//离线
            this.put("2", "ABNORMAL");//异常
            this.put("3", "INACTIVE");//未激活
            this.put("4", "FROZEN");//冻结

        }
    };
    public ModbusDriver() throws Exception {
        this.driverClient = DriverClient.createFromEnv();
    }
}

片段二:调用上报子设备状态API,循环更新子设备状态。(可根据自身业务调整,此代码只用于演示功能)

 public static void main(String[] args) throws Exception {
        ModbusDriver modbusDriver = new ModbusDriver();
        modbusDriver.start();
    }

     public void start() throws Exception {
        // 设置回调,打开客户端
        this.driverClient.setGatewayCallback(this);
        this.driverClient.open();
        this.scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                UpdateSubDevicesStatusEvent updateSubDevicesStatusEvent = new UpdateSubDevicesStatusEvent();
                DeviceStatus deviceStatus = new DeviceStatus();
                //设备Id(添加边缘设备时设置)
                deviceStatus.setDeviceId("scmj19961031b");
                int j = new Random().nextInt(4);
                //随机获取设备状态上报
                deviceStatus.setStatus(ModbusDriver.dataMap.get(String.valueOf(j)));
                updateSubDevicesStatusEvent.setDeviceStatuses(Collections.singletonList(deviceStatus));
                try {
                    ModbusDriver.this.driverClient.updateSubDevicesStatus(String.valueOf(new Random().nextInt(100000)), updateSubDevicesStatusEvent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 0, 5, TimeUnit.SECONDS);
    }

分享:

子设备管理 所有常见问题

more