Quellcode durchsuchen

update 修改设备同步出错

龙三郎 vor 3 Jahren
Ursprung
Commit
42b45a370b

+ 1 - 0
coffee-admin/src/main/resources/application.yml

@@ -65,6 +65,7 @@ mybatis-plus:
       idType: ASSIGN_ID
   configuration:
     log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl
+#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
     default-enum-type-handler: com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler
   type-aliases-package: com.coffee.bus.entity
 

+ 1 - 1
coffee-admin/src/test/java/com/coffee/admin/BusDeviceTest.java

@@ -30,7 +30,7 @@ public class BusDeviceTest {
         device.setDeviceId("12345678910");
         device.setCreateBy("auto");
         device.setCreateTime(new Date());
-        deviceService.saveByDeviceId(device);
+        deviceService.saveDevice(device);
 
     }
 

+ 2 - 5
coffee-system/src/main/java/com/coffee/aliyun/AliyunConsumerGroupService.java

@@ -8,15 +8,12 @@ import com.coffee.aliyun.utils.EnumUtils;
 import com.coffee.aliyun.utils.Items;
 import com.coffee.bus.bean.AliIotConfig;
 import com.coffee.bus.entity.BusDeviceEntity;
-import com.coffee.bus.entity.BusDeviceHistoryEntity;
 import com.coffee.bus.entity.BusDeviceRunningEntity;
-import com.coffee.bus.entity.BusInfusionHistoryEntity;
 import com.coffee.bus.listener.event.bean.DeviceInfoEvent;
 import com.coffee.bus.service.LocalBusDeviceHistoryService;
 import com.coffee.bus.service.LocalBusDeviceService;
 import com.coffee.bus.service.LocalBusInfusionHistoryService;
 import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Lazy;
@@ -145,7 +142,7 @@ public class AliyunConsumerGroupService {
                     log.info(deviceName+"设备未激活");
                 }
                 // 更新设备状态
-                deviceService.updateByDeviceId(device);
+                deviceService.updateDevice(device);
             }else if (topic.matches("[\\w\\/]*event/property/post$")){//设备属性上报
                 // 设备属性集合
                 Items items = new Items(content.getJSONObject("items"));
@@ -186,7 +183,7 @@ public class AliyunConsumerGroupService {
 
                     // 设置配置信息
                     device.setConfig(config);
-                    deviceService.saveByDeviceId(device);
+                    deviceService.saveDevice(device);
                 }else if ("delete".equals(action)){
                     // 删除设备
                     deviceService.removeByDeviceId(deviceName);

+ 20 - 8
coffee-system/src/main/java/com/coffee/bus/controller/BusDeviceController.java

@@ -4,19 +4,15 @@ import cn.dev33.satoken.annotation.SaCheckPermission;
 import cn.hutool.core.collection.CollectionUtil;
 import cn.hutool.core.util.ObjectUtil;
 import cn.hutool.core.util.StrUtil;
-import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
 import com.baomidou.mybatisplus.core.mapper.Mapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.coffee.bus.controller.vo.DeviceBindVo;
 import com.coffee.bus.entity.BusDeviceEntity;
 import com.coffee.bus.entity.BusDeviceRunningEntity;
-import com.coffee.bus.entity.BusHospitalEntity;
 import com.coffee.bus.enums.DeviceAlarmEnum;
 import com.coffee.bus.enums.DeviceStatusEnum;
 import com.coffee.bus.exception.BusinessException;
 import com.coffee.bus.exception.ErrorStatus;
-import com.coffee.bus.registry.device.DeviceRegistry;
 import com.coffee.bus.service.LocalBusDeviceRunningService;
 import com.coffee.bus.service.LocalBusDeviceService;
 import com.coffee.bus.service.dto.DeviceQuery;
@@ -33,7 +29,6 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.context.request.async.DeferredResult;
 
-import javax.validation.constraints.NotNull;
 import java.util.List;
 import java.util.Objects;
 import java.util.concurrent.CompletableFuture;
@@ -91,6 +86,7 @@ public class BusDeviceController extends BaseCrudController<BusDeviceEntity, Str
 
     /**
      * @author 龙三郎
+     * 新增设备,只有超级管理员才有此权限,如果该设备在系统中存在,则更新,如果设备在系统中不存在,在阿里云平台存在,则从阿里云获取后插入。
      * @param payload
      * @return
      */
@@ -104,7 +100,7 @@ public class BusDeviceController extends BaseCrudController<BusDeviceEntity, Str
             throw new BusinessException(ErrorStatus.DEVICEID_IS_EMPTY);
         }
         // 根据deviceId从阿里云获取设备信息。
-        BusDeviceEntity device = deviceService.add(payload.getDeviceId());
+        BusDeviceEntity device = deviceService.addDevice(payload.getDeviceId());
         if (ObjectUtil.isNull(device)){
             return R.fail("设备添加失败");
         }
@@ -113,13 +109,29 @@ public class BusDeviceController extends BaseCrudController<BusDeviceEntity, Str
 
     /**
      * @author 龙三郎
-     * 从阿里云同步系统所有的设备
+     * 从阿里云同步系统所有的设备,只有超级管理员才有此权限。将阿里云所有的设备同步到系统。
      * @return
      */
     @ApiOperation(value = "从阿里云同步设备",notes = "从阿里云平台获取设备并更新")
     @PutMapping("/sync-device")
     public R syncDevice() {
-        int i = deviceService.syncDevice();
+        int i = deviceService.syncAllDevice();
+        if (i > 0){
+            return R.success(i,"同步成功");
+        }else {
+            return R.fail("同步失败");
+        }
+    }
+
+    /**
+     * @author 龙三郎
+     * 从阿里云更新系统中存在的设备,如果设备在系统中不存在,则不更新。
+     * @return
+     */
+    @ApiOperation(value = "从阿里云更新本地设备",notes = "从阿里云平台获取设备并更新,参数为设备id列表,格式如['123456','456123'],参数可为空。")
+    @PutMapping("/sync-device/batch")
+    public R syncDevice(@RequestBody List<String> ids) {
+        int i = deviceService.syncDevice(ids);
         if (i > 0){
             return R.success(i,"同步成功");
         }else {

+ 76 - 16
coffee-system/src/main/java/com/coffee/bus/service/LocalBusDeviceService.java

@@ -16,6 +16,7 @@ import com.coffee.bus.registry.device.DeviceOperator;
 import com.coffee.bus.service.dto.DeviceQuery;
 import com.coffee.bus.service.dto.DeviceResult;
 import com.coffee.common.crud.BaseService;
+import com.coffee.common.exception.CustomException;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Lazy;
@@ -24,6 +25,8 @@ import org.springframework.transaction.annotation.Transactional;
 
 import java.util.List;
 import java.util.Objects;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
 import java.util.concurrent.atomic.AtomicReference;
 
 /**
@@ -109,33 +112,60 @@ public class LocalBusDeviceService extends BaseService<BusDeviceMapper, BusDevic
      * 根据deviceId更新设备在线状态
      * @param device
      */
-    public boolean updateByDeviceId(BusDeviceEntity device){
+    public boolean updateDevice(BusDeviceEntity device){
         return this.update(device,new QueryWrapper<BusDeviceEntity>().lambda()
                 .eq(BusDeviceEntity::getDeviceId,device.getDeviceId()));
     }
 
     /**
      * @author 龙三郎
-     * 添加设备
+     * 保存一个设备,系统中存在时就更新,不存在时则插入。
      * @param entity
      */
-    public boolean saveByDeviceId(BusDeviceEntity entity) {
+    public boolean saveDevice(BusDeviceEntity entity) {
         // 查询设备是否存在,无视逻辑删除
-        BusDeviceEntity old = deviceMapper.selectOneByDeviceId(entity.getDeviceId());
+        BusDeviceEntity device = deviceMapper.selectOneByDeviceId(entity.getDeviceId());
+        // 判断设备是否存在
+        boolean isExists = Objects.nonNull(device);
         // 设备存在,且处于删除状态,首先去掉逻辑删除标志 ?? 逻辑删除后设备数据是否不再接收
-        if (Objects.nonNull(old) && old.getIsDelete() == 1){
+        if (isExists && device.getIsDelete() == 1){
             deviceMapper.notDelete(entity.getDeviceId());
         }
         // 设备存在
-        if (Objects.nonNull(old)){
+        if (isExists){
             // 更新设备
-            return this.updateByDeviceId(entity);
+            return this.updateDevice(entity);
         }else {
             // 添加设备
             return this.save(entity);
         }
     }
 
+    /**
+     * @author 龙三郎
+     * 更新一个系统中现有的设备
+     * @param deviceId
+     */
+    public boolean updateDeviceByDeviceId(String deviceId) {
+        // 查询设备是否存在
+        BusDeviceEntity device = getByDeviceId(deviceId);
+        // 设备不存在直接退出
+        if (Objects.isNull(device)){
+            return false;
+        }
+        // 从阿里云物联网查询设备
+        QueryDeviceDetailResponse response = aliyunIotSdk.queryDeviceDetail(deviceId);
+        // 设备存在
+        if (response.getSuccess()){
+            // 更新设备参数
+            device.updateFields(response.getData());
+            // 更新设备
+            return this.updateDevice(device);
+        }else {
+            return false;
+        }
+    }
+
     /**
      * @author 龙三郎
      * 根据deviceId获取设备
@@ -155,7 +185,7 @@ public class LocalBusDeviceService extends BaseService<BusDeviceMapper, BusDevic
      * @param deviceId
      * @return
      */
-    public BusDeviceEntity add(String deviceId) {
+    public BusDeviceEntity addDevice(String deviceId) {
         BusDeviceEntity device = new BusDeviceEntity();
         device.setConfig(new AliIotConfig());
         // 从阿里云物联网查询设备
@@ -164,7 +194,7 @@ public class LocalBusDeviceService extends BaseService<BusDeviceMapper, BusDevic
         if (response.getSuccess()){
             device.updateFields(response.getData());
             // 存储设备
-            this.saveByDeviceId(device);
+            this.saveDevice(device);
             return device;
         }
         // 不存在返回null
@@ -180,14 +210,44 @@ public class LocalBusDeviceService extends BaseService<BusDeviceMapper, BusDevic
      * 从阿里云平台获取全部的设备,同步到系统数据库
      * @return
      */
-    public int syncDevice() {
+    public int syncAllDevice(){
+        Integer m = 0;
+        // 创建异步执行任务,有返回值
+        CompletableFuture<Integer> cf = CompletableFuture.supplyAsync(()->{
+            AtomicReference<Integer> n = new AtomicReference<>(0);
+            // 同步所有的设备
+            aliyunIotSdk.queryDevice().forEach(item ->{
+                BusDeviceEntity device = new BusDeviceEntity();
+                device.setConfig(new AliIotConfig());
+                // 更新设备属性
+                device.updateFields(item);
+                n.updateAndGet(v -> v + (this.saveDevice(device)?1:0));
+            });
+            return n.get();
+        });
+        //等待子任务执行完成
+        try {
+            m = cf.get();
+        }catch (Exception e){
+            throw new CustomException(e.getMessage());
+        }
+        return m;
+    }
+
+    /**
+     * @author 龙三郎
+     * 根据ids获取指定的设备,更新本地设备
+     * @return
+     */
+    public int syncDevice(List<String> ids) {
         AtomicReference<Integer> n = new AtomicReference<>(0);
-        aliyunIotSdk.queryDevice().forEach(item ->{
-            BusDeviceEntity device = new BusDeviceEntity();
-            device.setConfig(new AliIotConfig());
-            // 更新设备属性
-            device.updateFields(item);
-            n.updateAndGet(v -> v + (this.saveByDeviceId(device)?1:0));
+        // ids不能为空
+        if (Objects.isNull(ids) || ids.size() <= 0){
+            throw new CustomException("设备id不能为空");
+        }
+        // 同步指定的设备
+        ids.forEach(id->{
+            n.updateAndGet(v -> v + (this.updateDeviceByDeviceId(id)?1:0));
         });
         return n.get();
     }