Jelajahi Sumber

fix 添加和删除设备代码

龙三郎 3 tahun lalu
induk
melakukan
129b1314df

+ 2 - 2
coffee-admin/src/main/resources/application.yml

@@ -70,6 +70,6 @@ mybatis-plus:
 
 # 阿里云对接配置
 aliyun:
-  data-access:
-    enable: false  # 是否开启阿里云物联网订阅
+  server-subscription:
+    enable: true  # 是否开启阿里云物联网服务端订阅
 

+ 42 - 0
coffee-admin/src/test/java/com/coffee/admin/BusDeviceTest.java

@@ -0,0 +1,42 @@
+package com.coffee.admin;
+
+import com.coffee.bus.entity.BusDeviceEntity;
+import com.coffee.bus.service.LocalBusDeviceService;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import java.util.Date;
+
+/**
+ * @Author XX
+ * @Date 2022-04-25 19:00:10
+ * @Version 1.0
+ * @Description XXX
+ */
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = AdminApplication.class)
+public class BusDeviceTest {
+
+    @Autowired
+    LocalBusDeviceService deviceService;
+
+    @Test
+    public void test001(){
+        BusDeviceEntity device = new BusDeviceEntity();
+        device.setDeviceId("12345678910");
+        device.setCreateBy("auto");
+        device.setCreateTime(new Date());
+        deviceService.save(device);
+
+    }
+
+
+    @Test
+    public void test002(){
+        deviceService.removeByDeviceId("nbceshi001");
+    }
+
+}

+ 81 - 78
coffee-system/src/main/java/com/coffee/aliyun/AliyunConsumerGroupService.java

@@ -2,22 +2,20 @@ package com.coffee.aliyun;
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
+import com.coffee.bus.bean.AliIotConfig;
+import com.coffee.bus.entity.BusDeviceEntity;
 import com.coffee.bus.entity.BusDeviceRunningEntity;
-import com.coffee.bus.enums.DeviceEnum;
 import com.coffee.bus.listener.event.bean.DeviceInfoEvent;
-import lombok.AllArgsConstructor;
+import com.coffee.bus.service.LocalBusDeviceService;
 import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.context.properties.EnableConfigurationProperties;
 import org.springframework.context.ApplicationContext;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.PostConstruct;
 import javax.jms.Message;
 import javax.jms.MessageListener;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.ExecutorService;
@@ -38,15 +36,20 @@ public class AliyunConsumerGroupService {
     private final ApplicationContext applicationContext;
 
     // 初始化订阅客户端
-    // 阿里云账号信息
     private final AliyunIotSubscribeClient client;
 
-    public AliyunConsumerGroupService(ApplicationContext applicationContext, AliyunIotSubscribeClient client) {
+    // 设备Service
+    private final LocalBusDeviceService deviceService;
+
+    public AliyunConsumerGroupService(ApplicationContext applicationContext,
+                                      AliyunIotSubscribeClient client,
+                                      LocalBusDeviceService deviceService) {
         this.applicationContext = applicationContext;
         this.client = client;
+        this.deviceService = deviceService;
     }
 
-    @Value("${aliyun.data-access.enable:false}")
+    @Value("${aliyun.server-subscription.enable:false}")
     private boolean isEnable;
 
     // 开启服务端订阅
@@ -94,76 +97,69 @@ public class AliyunConsumerGroupService {
      */
     private static final String IOTID = "iotId";
     private static final String PRODUCTKEY = "productKey";
+    private static final String DEVICENAME = "deviceName";
     private static final String TOPIC = "topic";
     private static final String MESSAGEID = "messageId";
     private static final String ITEMS = "items";
     private static final String VALUE = "value";
     private static final String STATUS = "status";
+    private static final String CONTENT = "content";
 
-    private synchronized void processMessage(Message message) {
+    private void processMessage(Message message) {
 
-        PlatformDataLog dataLog = new PlatformDataLog();
+        PlatformLog platformLog = new PlatformLog();
         Map<String, Object> platformData = new HashMap<>();
         try {
-            byte[] body = message.getBody(byte[].class);
-            String contentString = new String(body);
+            // 获取主题,消息id和内容
             String topic = message.getStringProperty(TOPIC);
             String messageId = message.getStringProperty(MESSAGEID);
+            JSONObject content = JSON.parseObject(new String(message.getBody(byte[].class)));
+            // 平台数据
             platformData.put(TOPIC,topic);
             platformData.put(MESSAGEID,messageId);
-            platformData.put("content",contentString);
-
+            platformData.put(CONTENT,content);
             log.info("阿里云物联网发送的数据:"+JSON.toJSONString(platformData));
 
-            /**
-             * platformData:
-             * {
-             * "topic":"/a1M7k1TAECc/ceshi001/thing/event/property/post",
-             * "messageId":"1496410088574460416",
-             * "content":"{\"deviceType\":\"CustomCategory\",
-             * \"iotId\":\"0syOzMqwkGebZBGKa08d000000\",
-             * \"requestId\":\"254\",\"checkFailedData\":{},
-             * \"productKey\":\"a1M7k1TAECc\",\"gmtCreate\":1645606941721,
-             * \"deviceName\":\"ceshi001\",
-             * \"items\":{
-             * \"total\":{\"value\":100,\"time\":1645606941717},
-             * \"pumpCode\":{\"value\":\"5719512336330299\",\"time\":1645606941717},
-             * \"dataNumber\":{\"value\":254,\"time\":1645606941717},
-             * \"PCAInvalid\":{\"value\":0,\"time\":1645606941717},
-             * \"alarm\":{\"value\":0,\"time\":1645606941717},
-             * \"flowRate\":{\"value\":2,\"time\":1645606941717},
-             * \"PCAValid\":{\"value\":0,\"time\":1645606941717},
-             * \"forecast\":{\"value\":0,\"time\":1645606941717},
-             * \"finished\":{\"value\":17,\"time\":1645606941717},
-             * \"battery\":{\"value\":65,\"time\":1645606941717},
-             * \"runStatus\":{\"value\":2,\"time\":1645606941717},
-             * \"patientCode\":{\"value\":111110000,\"time\":1645606941717}}}"
-             * }
-             */
-            // 日志编号
-            dataLog.setCode(messageId);
-            // 平台数据
-            dataLog.setPlatformData(JSON.toJSONString(platformData));
-            // 将内容转换成对象
-            JSONObject content = JSON.parseObject(contentString);
-            // 设备编号
-            String deviceCode = content.getString(IOTID);
-            String productKey = content.getString(PRODUCTKEY);
-            // 设置平台和设备
-            dataLog.setPlatformCode(PlatformType.ALIYUN);
-            dataLog.setDeviceCode(deviceCode);
-            dataLog.setPlatformProductCode(productKey);
+            // 设备名称
+            String deviceName = content.getString(DEVICENAME);
+            // 创建设备对象
+            Date now = new Date();
             // 根据topic判断数据类型
             if (topic.matches("^/as/mqtt/status/[\\w\\/]*")){//设备上下线状态
                 String status = content.getString(STATUS);
                 if (status.equals("online")){
-                    log.info(deviceCode+"设备上线");
+                    log.info(deviceName+"设备上线");
                 }else if (status.equals("offline")){
-                    log.info(deviceCode+"设备下线");
+                    log.info(deviceName+"设备下线");
                 }else {
-                    log.info(deviceCode+"设备未激活");
+                    log.info(deviceName+"设备未激活");
                 }
             }else if (topic.matches("[\\w\\/]*event/property/post$")){//设备属性上报
+                /**
+                 * platformData:
+                 * {
+                 * "topic":"/a1M7k1TAECc/ceshi001/thing/event/property/post",
+                 * "messageId":"1496410088574460416",
+                 * "content":"{\"deviceType\":\"CustomCategory\",
+                 * \"iotId\":\"0syOzMqwkGebZBGKa08d000000\",
+                 * \"requestId\":\"254\",\"checkFailedData\":{},
+                 * \"productKey\":\"a1M7k1TAECc\",\"gmtCreate\":1645606941721,
+                 * \"deviceName\":\"ceshi001\",
+                 * \"items\":{
+                 * \"total\":{\"value\":100,\"time\":1645606941717},
+                 * \"pumpCode\":{\"value\":\"5719512336330299\",\"time\":1645606941717},
+                 * \"dataNumber\":{\"value\":254,\"time\":1645606941717},
+                 * \"PCAInvalid\":{\"value\":0,\"time\":1645606941717},
+                 * \"alarm\":{\"value\":0,\"time\":1645606941717},
+                 * \"flowRate\":{\"value\":2,\"time\":1645606941717},
+                 * \"PCAValid\":{\"value\":0,\"time\":1645606941717},
+                 * \"forecast\":{\"value\":0,\"time\":1645606941717},
+                 * \"finished\":{\"value\":17,\"time\":1645606941717},
+                 * \"battery\":{\"value\":65,\"time\":1645606941717},
+                 * \"runStatus\":{\"value\":2,\"time\":1645606941717},
+                 * \"patientCode\":{\"value\":111110000,\"time\":1645606941717}}}"
+                 * }
+                 */
                 // 设备属性上报
 
 
@@ -171,36 +167,43 @@ public class AliyunConsumerGroupService {
                 DeviceInfoEvent deviceInfoEvent = new DeviceInfoEvent(this,new BusDeviceRunningEntity(),"123456");
                 applicationContext.publishEvent(deviceInfoEvent);
 
-            }else if(topic.matches("[\\w\\/]+thing/liftcycle$")){// 设备生命周期
+            }else if(topic.matches("[\\w\\/]+thing/lifecycle$")){// 设备生命周期
+                // 获取生命周期类型
+                String action = content.getString("action");
+                if ("create".equals(action)){
+                    // 创建设备
+                    BusDeviceEntity device = new BusDeviceEntity();
+                    device.setDeviceId(deviceName);
+                    device.setCreateBy("1");
+                    device.setUpdateBy("1");
+                    device.setUpdateTime(now);
+                    device.setTenantId("1");
+
+                    // 配置信息
+                    AliIotConfig config = new AliIotConfig();
+                    config.setDeviceName(deviceName);
+                    config.setDeviceSecret(content.getString("deviceSecret"));
+                    config.setIotId(content.getString("iotId"));
+                    config.setProductKey(content.getString("productKey"));
+
+                    // 设置配置信息
+                    device.setConfig(config);
+                    deviceService.saveByDeviceId(device);
+                }else if ("delete".equals(action)){
+                    // 删除设备
+                    deviceService.removeByDeviceId(deviceName);
+                }
 
-                /**
-                 * 生命周期,删除设备
-                 * {"topic":"/a1M7k1TAECc/456789/thing/lifecycle",
-                 * "messageId":"1511903665358296576",
-                 * "content":"{\"iotId\":\"hGMEfTMBv9O6gyvpMSvi000000\",\"action\":\"delete\",
-                 * \"messageCreateTime\":1649300898278,\"productKey\":\"a1M7k1TAECc\",
-                 * \"deviceName\":\"456789\"}"}
-                 *
-                 * 生命周期,添加设备
-                 * {"topic":"/a1M7k1TAECc/ceshidevice007/thing/lifecycle",
-                 * "messageId":"1511904535630241792",
-                 * "content":"{\"iotId\":\"KsCWSsSf86fjD6ux16sC000000\",
-                 * \"deviceSecret\":\"989561a8d3bd939bfb8321bafc61b64c\",
-                 * \"action\":\"create\",\"messageCreateTime\":1649301105776,
-                 * \"productKey\":\"a1M7k1TAECc\",\"deviceName\":\"ceshidevice007\"}"}
-                 *
-                 */
 
 
             }else {
-                log.info("未知的topic:"+topic);
+                log.error("未知的topic:"+topic);
             }
 
         } catch (Exception e) {
-//            e.printStackTrace();
             // 错误标志
-            dataLog.setIsError("1");
-            dataLog.setErrorLog(e.getMessage());
+            platformLog.setIsError("1");
+            platformLog.setErrorLog(e.getMessage());
             log.error("数据处理失败 ", e);
         }
         // 存储日志

+ 14 - 21
coffee-system/src/main/java/com/coffee/aliyun/AliyunIotSubscribeClient.java

@@ -43,11 +43,13 @@ public class AliyunIotSubscribeClient {
         this.consumerGroupId = platformAccount.getConsumerGroupId();
         this.aliyunUid = platformAccount.getAliyunUid();
         this.iotInstanceId = platformAccount.getIotInstanceId();
-        //
-//        setClientIdAndHost();
+
+        this.host = aliyunUid+".iot-amqp."+ regionId +".aliyuncs.com";
+        // 设置客户端id
+        setClientIdAndHost();
     }
 
-    // 设置客户端id和host
+    // 设置客户端id
     private void setClientIdAndHost(){
         // 获取ip地址
         InetAddress addr = null;
@@ -57,31 +59,29 @@ public class AliyunIotSubscribeClient {
             e.printStackTrace();
         }
         String ip = addr.getHostAddress();
-
         this.clientId = consumerGroupId + ip;
-        this.host = aliyunUid+".iot-amqp."+ regionId +".aliyuncs.com";
     }
 
-    private String accessKey = "LTAI4FhB19MgQuviGxwA3aod";
-    private String accessSecret = "cQQVkATR0yv2G9CEtfjAhEGBepPDRs";
-    private String consumerGroupId = "DEFAULT_GROUP";
-    private String aliyunUid = "1177450762772738";
-    private String regionId = "cn-shanghai";
+    private String accessKey;
+    private String accessSecret;
+    private String consumerGroupId;
+    private String aliyunUid;
+    private String regionId;
 
     //iotInstanceId:企业版实例请填写实例ID,公共实例请填空字符串""。
-    private String iotInstanceId = "";
+    private String iotInstanceId;
 
     //控制台服务端订阅中消费组状态页客户端ID一栏将显示clientId参数。
     //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。
-    private String clientId = "123456789";
+    private String clientId;
 
     //${YourHost}为接入域名,请参见AMQP客户端接入说明文档。
-    private String host = "1177450762772738.iot-amqp.cn-shanghai.aliyuncs.com";
+    private String host;
 
     // 指定单个进程启动的连接数
     // 单个连接消费速率有限,请参考使用限制,最大64个连接
     // 连接数和消费速率及rebalance相关,建议每500QPS增加一个连接
-    private static int connectionCount = 4;
+    private static int connectionCount = 1;
 
     @Getter
     private List<Connection> connections = null;
@@ -155,7 +155,6 @@ public class AliyunIotSubscribeClient {
         public void onConnectionEstablished(URI remoteURI) {
             log.info("连接成功, remoteUri:{}", remoteURI);
         }
-
         /**
          * 尝试过最大重试次数之后,最终连接失败。
          */
@@ -163,7 +162,6 @@ public class AliyunIotSubscribeClient {
         public void onConnectionFailure(Throwable error) {
             log.error("连接失败, {}", error.getMessage());
         }
-
         /**
          * 连接中断。
          */
@@ -171,7 +169,6 @@ public class AliyunIotSubscribeClient {
         public void onConnectionInterrupted(URI remoteURI) {
             log.info("连接中断, remoteUri:{}", remoteURI);
         }
-
         /**
          * 连接中断后又自动重连上。
          */
@@ -179,16 +176,12 @@ public class AliyunIotSubscribeClient {
         public void onConnectionRestored(URI remoteURI) {
             log.info("自动重连, remoteUri:{}", remoteURI);
         }
-
         @Override
         public void onInboundMessage(JmsInboundMessageDispatch envelope) {}
-
         @Override
         public void onSessionClosed(Session session, Throwable cause) {}
-
         @Override
         public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {}
-
         @Override
         public void onProducerClosed(MessageProducer producer, Throwable cause) {}
     };

+ 1 - 1
coffee-system/src/main/java/com/coffee/aliyun/PlatformAccount.java

@@ -23,7 +23,7 @@ import org.springframework.context.annotation.Configuration;
 public class PlatformAccount {
     private String accessKey = "LTAI4FhB19MgQuviGxwA3aod";
     private String accessSecret = "cQQVkATR0yv2G9CEtfjAhEGBepPDRs";
-    private String consumerGroupId = "DEFAULT_GROUP";
+    private String consumerGroupId = "nalavzBm4RuVJc0BUij7000100";
     private String aliyunUid = "1177450762772738";
     private String regionId = "cn-shanghai";
     //iotInstanceId:企业版实例请填写实例ID,公共实例请填空字符串""。

+ 1 - 1
coffee-system/src/main/java/com/coffee/aliyun/PlatformDataLog.java → coffee-system/src/main/java/com/coffee/aliyun/PlatformLog.java

@@ -16,7 +16,7 @@ import lombok.NoArgsConstructor;
 @Data
 @NoArgsConstructor
 @AllArgsConstructor
-public class PlatformDataLog {
+public class PlatformLog {
     @TableId(value = "id",type = IdType.AUTO)
     private Long id;
     private String code;

+ 6 - 1
coffee-system/src/main/java/com/coffee/bus/entity/BusDeviceEntity.java

@@ -53,7 +53,7 @@ public class BusDeviceEntity extends TenantGenericEntity<String,String> implemen
     private DeviceAlarmEnum alarm;
 
     @ApiModelProperty(value = "第三方平台返回配置")
-    @TableField(typeHandler = FastjsonTypeHandler.class,updateStrategy = FieldStrategy.NEVER)
+    @TableField(typeHandler = FastjsonTypeHandler.class,updateStrategy = FieldStrategy.DEFAULT)
     private AliIotConfig config;
 
     @ApiModelProperty(value = "是否启用,0、不启用 1、启用 ")
@@ -70,4 +70,9 @@ public class BusDeviceEntity extends TenantGenericEntity<String,String> implemen
 
     @TableField(fill = FieldFill.UPDATE)
     private Date updateTime;
+
+
+    @TableField(fill = FieldFill.INSERT)
+    @TableLogic(value = "0",delval = "1")
+    private Integer isDelete;
 }

+ 15 - 0
coffee-system/src/main/java/com/coffee/bus/mapper/BusDeviceMapper.java

@@ -3,6 +3,7 @@ package com.coffee.bus.mapper;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.coffee.bus.entity.BusDeviceEntity;
 import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Select;
 
 /**
  * @author lifang
@@ -14,4 +15,18 @@ import org.apache.ibatis.annotations.Mapper;
 @Mapper
 public interface BusDeviceMapper extends BaseMapper<BusDeviceEntity> {
 
+    /**
+     * 获取设备,无视逻辑删除
+     * @param deviceId
+     * @return
+     */
+    BusDeviceEntity selectOneByDeviceId(String deviceId);
+
+    /**
+     * 去掉逻辑删除标志
+     * @param deviceId
+     * @return
+     */
+    Integer notDelete(String deviceId);
+
 }

+ 42 - 0
coffee-system/src/main/java/com/coffee/bus/service/LocalBusDeviceService.java

@@ -1,6 +1,8 @@
 package com.coffee.bus.service;
 
 import cn.hutool.core.util.StrUtil;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.coffee.bus.entity.BusClinicEntity;
 import com.coffee.bus.registry.device.DeviceRegistry;
 import com.coffee.bus.entity.BusDeviceEntity;
 import com.coffee.bus.mapper.BusDeviceMapper;
@@ -11,6 +13,9 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Lazy;
 import org.springframework.stereotype.Service;
 
+import java.util.Date;
+import java.util.Objects;
+
 /**
  * @author lifang
  * @version 1.0.0
@@ -25,6 +30,10 @@ public class LocalBusDeviceService extends BaseService<BusDeviceMapper, BusDevic
     @Autowired
     @Lazy
     private DeviceRegistry deviceRegistry;
+
+    @Autowired
+    private BusDeviceMapper deviceMapper;
+
     @Override
     public void validateBeforeSave(BusDeviceEntity entity) {
 
@@ -65,4 +74,37 @@ public class LocalBusDeviceService extends BaseService<BusDeviceMapper, BusDevic
         BusDeviceEntity registeredEntity = this.getById(id);
         deviceRegistry.remove(registeredEntity.getDeviceId());
     }
+
+    /**
+     * 根据deviceId删除设备
+     * @param deviceId
+     */
+    public void removeByDeviceId(String deviceId){
+        this.remove(new QueryWrapper<BusDeviceEntity>().lambda()
+                .eq(BusDeviceEntity::getDeviceId,deviceId));
+    }
+
+    /**
+     * 添加设备
+     * @param entity
+     */
+    public void saveByDeviceId(BusDeviceEntity entity) {
+        // 查询设备是否存在,无视逻辑删除
+        BusDeviceEntity old = deviceMapper.selectOneByDeviceId(entity.getDeviceId());
+        // 设备存在,且处于删除状态,首先去掉逻辑删除标志
+        if (Objects.nonNull(old) && old.getIsDelete() == 1){
+            deviceMapper.notDelete(entity.getDeviceId());
+        }
+        // 设备存在
+        if (Objects.nonNull(old)){
+            // 添加时间
+            entity.setCreateTime(new Date());
+            // 更新设备
+            this.update(entity,new QueryWrapper<BusDeviceEntity>().lambda()
+                    .eq(BusDeviceEntity::getDeviceId,entity.getDeviceId()));
+        }else {
+            // 添加设备
+            this.save(entity);
+        }
+    }
 }

+ 18 - 0
coffee-system/src/main/resources/mapper/bus/BusDeviceMapper.xml

@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.coffee.bus.mapper.BusDeviceMapper">
+
+
+    <resultMap id="deviceResult" type="com.coffee.bus.entity.BusDeviceEntity" autoMapping="true">
+        <result property="config" column="config" typeHandler="com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler"></result>
+    </resultMap>
+    <select id="selectOneByDeviceId" resultMap="deviceResult">
+        SELECT * from bus_device
+        WHERE device_id = #{deviceId}
+    </select>
+    <update id="notDelete">
+        UPDATE bus_device
+        SET is_delete = 0
+        WHERE device_id = #{deviceId}
+    </update>
+</mapper>