فهرست منبع

牧场端增加设备信息同步功能:编辑设备数据

zhuoning 3 سال پیش
والد
کامیت
c41be42c06

+ 96 - 0
huimv-farm-device/huimv-farm-business/src/main/java/com/huimv/business/farm/controller/FarmDeviceController.java

@@ -0,0 +1,96 @@
+package com.huimv.business.farm.controller;
+
+import com.huimv.business.farm.service.IFarmDevice;
+import com.huimv.common.utils.Result;
+import com.huimv.common.utils.ResultCode;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+
+import java.io.UnsupportedEncodingException;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@CrossOrigin
+@RestController
+@Slf4j
+@RequestMapping(value = "/farm/device")
+public class FarmDeviceController {
+    @Autowired
+    private IFarmDevice iFarmDevice;
+
+    /**
+     * @Method      : newDevice
+     * @Description : 新建设备信息
+     * @Params      : [deviceData]
+     * @Return      : com.huimv.common.utils.Result
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2021/12/16       
+     * @Time        : 14:42
+     */
+    @RequestMapping(value = "/newDevice",method = RequestMethod.POST)
+    public Result newDevice(@RequestBody String deviceData) throws UnsupportedEncodingException {
+        log.info("接收前端参数>>"+deviceData);
+        //新建设备信息
+        return iFarmDevice.newDevice(deviceData);
+    }
+
+    /**
+     * @Method      : editDevice
+     * @Description : 编辑设备信息
+     * @Params      : [deviceData]
+     * @Return      : com.huimv.common.utils.Result
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2021/12/16       
+     * @Time        : 14:43
+     */
+    @RequestMapping(value = "/editDevice",method = RequestMethod.POST)
+    public Result editDevice(@RequestBody String deviceData) throws UnsupportedEncodingException {
+        log.info("接收前端参数>>"+deviceData);
+        //编辑设备信息
+        return iFarmDevice.editDevice(deviceData);
+    }
+
+    /**
+     * @Method      : removeDevice
+     * @Description : 删除设备信息
+     * @Params      : [deviceData]
+     * @Return      : com.huimv.common.utils.Result
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2021/12/16       
+     * @Time        : 14:43
+     */
+    @RequestMapping(value = "/removeDevice",method = RequestMethod.POST)
+    public Result removeDevice(@RequestBody String deviceData){
+        log.info("接收前端参数>>"+deviceData);
+        //删除设备信息
+        return iFarmDevice.removeDevice(deviceData);
+    }
+
+    /**
+     * @Method      : listDevice
+     * @Description : 展示设备列表
+     * @Params      : [deviceData]
+     * @Return      : com.huimv.common.utils.Result
+     *
+     * @Author      : ZhuoNing
+     * @Date        : 2021/12/16
+     * @Time        : 14:43
+     */
+    @RequestMapping(value = "/listDevice",method = RequestMethod.POST)
+    public Result listDevice(@RequestBody String deviceData){
+        log.info("接收前端参数>>"+deviceData);
+        //列表展示设备信息
+        return iFarmDevice.listDevice(deviceData);
+    }
+
+}

+ 19 - 0
huimv-farm-device/huimv-farm-business/src/main/java/com/huimv/business/farm/service/IFarmDevice.java

@@ -0,0 +1,19 @@
+package com.huimv.business.farm.service;
+
+import com.huimv.common.utils.Result;
+
+import java.io.UnsupportedEncodingException;
+
+public interface IFarmDevice {
+    //新建设备信息
+    Result newDevice(String deviceData) throws UnsupportedEncodingException;
+
+    //编辑设备信息
+    Result editDevice(String deviceData) throws UnsupportedEncodingException;
+
+    //删除设备信息
+    Result removeDevice(String deviceData);
+
+    //列表展示设备信息
+    Result listDevice(String deviceData);
+}

+ 140 - 0
huimv-farm-device/huimv-farm-business/src/main/java/com/huimv/business/farm/service/impl/FarmDeviceImpl.java

@@ -0,0 +1,140 @@
+package com.huimv.business.farm.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.business.farm.service.IFarmDevice;
+import com.huimv.business.server.dao.entity.FarmDeviceEntity;
+import com.huimv.business.server.dao.repo.FarmDeviceRepo;
+import com.huimv.business.utils.HttpTemplete;
+import com.huimv.business.utils.SnowflakeIdWorker;
+import com.huimv.business.utils.TextUtil;
+import com.huimv.common.utils.Result;
+import com.huimv.common.utils.ResultCode;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import java.io.UnsupportedEncodingException;
+import java.sql.Timestamp;
+import java.util.Date;
+import java.util.Optional;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Service
+@Slf4j
+public class FarmDeviceImpl implements IFarmDevice {
+    @Autowired
+    private FarmDeviceRepo deviceRepo;
+    @Autowired
+    private TextUtil textUtil;
+    @Autowired
+    private HttpTemplete httpTemplete;
+    @Value("${dataCenter.ipAddr}")
+    private String DATA_CENTER_IP_ADDR;
+    @Value("${dataCenter.device.port}")
+    private String PORT;
+    @Value("${dataCenter.device.sync}")
+    private boolean dataSync;
+    @Value("${dataCenter.device.addService}")
+    private String deviceAddService;
+    @Value("${dataCenter.device.editService}")
+    private String deviceEditService;
+    @Value("${dataCenter.device.removeService}")
+    private String deviceRemoveService;
+    @Value("${local.farmID}")
+    private Integer FARM_ID;
+
+    @Override
+    public Result newDevice(String deviceData) throws UnsupportedEncodingException {
+        //
+        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(1, 0);
+        JSONObject deviceDataJo = JSON.parseObject(deviceData);
+        FarmDeviceEntity deviceEntity = new FarmDeviceEntity();
+        deviceEntity.setDeviceCode(deviceDataJo.getString("deviceCode"));
+        deviceEntity.setDeviceName(deviceDataJo.getString("deviceName"));
+        deviceEntity.setDeviceType(deviceDataJo.getString("deviceType"));
+        deviceEntity.setFactory(deviceDataJo.getString("factory"));
+        deviceEntity.setFarmId(FARM_ID);
+        deviceEntity.setMainParams(deviceDataJo.getString("mainParams"));
+        deviceEntity.setRecord(deviceDataJo.getString("record"));
+        deviceEntity.setWorker(deviceDataJo.getString("worker"));
+        deviceEntity.setState(deviceDataJo.getInteger("state"));
+        deviceEntity.setLastTime(new Timestamp(new Date().getTime()));
+        deviceEntity.setUpTime(new Timestamp(new Date().getTime()));
+        deviceEntity.setLockinState(1);
+        deviceEntity.setDataId(idWorker.newId());
+        FarmDeviceEntity addDeviceEntity = deviceRepo.saveAndFlush(deviceEntity);
+        log.info("牧场端添加设备信息>>"+addDeviceEntity);
+        //同步更新数据中心端设备数据
+        if(dataSync){
+            log.info("同步数据中心端设备数据。");
+            String serviceUrl = DATA_CENTER_IP_ADDR + PORT + deviceAddService;
+            log.info("serviceUrl>>"+serviceUrl);
+            String data = textUtil.encode(JSON.toJSONString(addDeviceEntity));
+            log.info("base64密文>>"+data);
+            //提交请求
+            httpTemplete.doPostSimple(serviceUrl,data);
+        }
+        return new Result(ResultCode.SUCCESS, addDeviceEntity);
+    }
+
+    @Override
+    public Result editDevice(String deviceData) throws UnsupportedEncodingException {
+        //
+        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(1, 0);
+        JSONObject deviceDataJo = JSON.parseObject(deviceData);
+        //查询记录是否存在
+        Optional<FarmDeviceEntity> optional = deviceRepo.findById(deviceDataJo.getInteger("id"));
+        if(!optional.isPresent()){
+            String ERR_INFO_NOEXIST = "该记录不存在.";
+            log.error(ERR_INFO_NOEXIST);
+            return new Result(10001,ERR_INFO_NOEXIST,false);
+        }
+        //编辑记录
+        FarmDeviceEntity deviceEntity =  optional.get();
+        deviceEntity.setDeviceCode(deviceDataJo.getString("deviceCode"));
+        deviceEntity.setDeviceName(deviceDataJo.getString("deviceName"));
+        deviceEntity.setDeviceType(deviceDataJo.getString("deviceType"));
+        deviceEntity.setFactory(deviceDataJo.getString("factory"));
+        deviceEntity.setMainParams(deviceDataJo.getString("mainParams"));
+        deviceEntity.setRecord(deviceDataJo.getString("record"));
+        deviceEntity.setWorker(deviceDataJo.getString("worker"));
+        deviceEntity.setState(deviceDataJo.getInteger("state"));
+        deviceEntity.setLastTime(new Timestamp(new Date().getTime()));
+        deviceEntity.setUpTime(new Timestamp(new Date().getTime()));
+        deviceEntity.setLockinState(1);
+        FarmDeviceEntity addDeviceEntity = deviceRepo.saveAndFlush(deviceEntity);
+        log.info("牧场端添加设备信息>>"+addDeviceEntity);
+        //同步更新数据中心端设备数据
+        if(dataSync){
+            log.info("同步数据中心端设备数据。");
+            String serviceUrl = DATA_CENTER_IP_ADDR + PORT + deviceEditService;
+            log.info("serviceUrl>>"+serviceUrl);
+            String data = textUtil.encode(JSON.toJSONString(addDeviceEntity));
+            log.info("base64密文>>"+data);
+            //提交请求
+            httpTemplete.doPostSimple(serviceUrl,data);
+        }
+        return new Result(ResultCode.SUCCESS, addDeviceEntity);
+    }
+
+    @Override
+    public Result removeDevice(String deviceData){
+
+        return new Result(ResultCode.SUCCESS);
+    }
+
+    @Override
+    public Result listDevice(String deviceData){
+
+        return new Result(ResultCode.SUCCESS);
+    }
+}

+ 1 - 1
huimv-farm-device/huimv-farm-business/src/main/java/com/huimv/business/server/controller/DeviceController.java

@@ -21,7 +21,7 @@ import java.io.UnsupportedEncodingException;
 @CrossOrigin
 @RestController
 @Slf4j
-@RequestMapping(value = "/farm/local/device")
+@RequestMapping(value = "/farm/device")
 public class DeviceController {
     @Autowired
     private IDevice iDevice;

+ 3 - 3
huimv-farm-device/huimv-farm-business/src/main/java/com/huimv/business/server/dao/entity/FarmDeviceEntity.java

@@ -55,7 +55,7 @@ public class FarmDeviceEntity implements Serializable {
     private Integer farmId;
 
     @Column(name = "data_id")
-    private Integer dataId;
+    private Long dataId;
 
     public void setId(Integer id) {
         this.id = id;
@@ -169,11 +169,11 @@ public class FarmDeviceEntity implements Serializable {
         return farmId;
     }
 
-    public void setDataId(Integer dataId) {
+    public void setDataId(Long dataId) {
         this.dataId = dataId;
     }
 
-    public Integer getDataId() {
+    public Long getDataId() {
         return dataId;
     }
 

+ 2 - 2
huimv-farm-device/huimv-farm-business/src/main/java/com/huimv/business/server/service/impl/DeviceImpl.java

@@ -38,7 +38,7 @@ public class DeviceImpl implements IDevice {
         //转义符号处理
         JSONObject deviceDataJo = JSON.parseObject(textUtil.translateSymbol(deviceData));
         FarmDeviceEntity deviceEntity = new FarmDeviceEntity();
-        deviceEntity.setDataId(deviceDataJo.getInteger("id"));
+        deviceEntity.setDataId(deviceDataJo.getLong("id"));
         deviceEntity.setDeviceCode(deviceDataJo.getString("deviceCode"));
         deviceEntity.setDeviceName(deviceDataJo.getString("deviceName"));
         deviceEntity.setDeviceType(deviceDataJo.getString("deviceType"));
@@ -74,7 +74,7 @@ public class DeviceImpl implements IDevice {
             //更新目标设备数据
             FarmDeviceEntity deviceEntity = new FarmDeviceEntity();
             deviceEntity.setId(id);
-            deviceEntity.setDataId(deviceDataJo.getInteger("id"));
+            deviceEntity.setDataId(deviceDataJo.getLong("id"));
             deviceEntity.setDeviceCode(deviceDataJo.getString("deviceCode"));
             deviceEntity.setDeviceName(deviceDataJo.getString("deviceName"));
             deviceEntity.setDeviceType(deviceDataJo.getString("deviceType"));

+ 206 - 0
huimv-farm-device/huimv-farm-business/src/main/java/com/huimv/business/utils/SnowflakeIdWorker.java

@@ -0,0 +1,206 @@
+package com.huimv.business.utils;
+
+import org.springframework.stereotype.Component;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public class SnowflakeIdWorker {
+    // ==============================Fields===========================================
+    /**
+     * 开始时间截 (2015-01-01)
+     */
+    private final long twepoch = 1420041600000L;
+    /**
+     * 机器id所占的位数
+     */
+    private final long workerIdBits = 5L;
+    /**
+     * 数据标识id所占的位数
+     */
+    private final long datacenterIdBits = 5L;
+    /**
+     * 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
+     */
+    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
+    /**
+     * 支持的最大数据标识id,结果是31
+     */
+    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
+    /**
+     * 序列在id中占的位数
+     */
+    private final long sequenceBits = 12L;
+    /**
+     * 机器ID向左移12位
+     */
+    private final long workerIdShift = sequenceBits;
+    /**
+     * 数据标识id向左移17位(12+5)
+     */
+    private final long datacenterIdShift = sequenceBits + workerIdBits;
+    /**
+     * 时间截向左移22位(5+5+12)
+     */
+    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
+    /**
+     * 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095)
+     */
+    private final long sequenceMask = -1L ^ (-1L << sequenceBits);
+    /**
+     * 工作机器ID(0~31)
+     */
+    private long workerId;
+    /**
+     * 数据中心ID(0~31)
+     */
+    private long datacenterId;
+    /**
+     * 毫秒内序列(0~4095)
+     */
+    private long sequence = 0L;
+    /**
+     * 上次生成ID的时间截
+     */
+    private long lastTimestamp = -1L;
+    //==============================Constructors=====================================
+
+    /**
+     * 构造函数
+     *
+     * @param workerId     工作ID (0~31)
+     * @param datacenterId 数据中心ID (0~31)
+     */
+    public SnowflakeIdWorker(long workerId, long datacenterId) {
+        if (workerId > maxWorkerId || workerId < 0) {
+            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
+        }
+        if (datacenterId > maxDatacenterId || datacenterId < 0) {
+            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
+        }
+        this.workerId = workerId;
+        this.datacenterId = datacenterId;
+    }
+
+    // ==============================Methods==========================================
+
+    /**
+     * 获得下一个ID (该方法是线程安全的)
+     *
+     * @return SnowflakeId
+     */
+    public synchronized long nextId() {
+        long timestamp = timeGen();
+
+        //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
+        if (timestamp < lastTimestamp) {
+            throw new RuntimeException(
+                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
+        }
+        //如果是同一时间生成的,则进行毫秒内序列
+        if (lastTimestamp == timestamp) {
+            sequence = (sequence + 1) & sequenceMask;
+            //毫秒内序列溢出
+            if (sequence == 0) {
+                //阻塞到下一个毫秒,获得新的时间戳
+                timestamp = tilNextMillis(lastTimestamp);
+            }
+        }
+        //时间戳改变,毫秒内序列重置
+        else {
+            sequence = 0L;
+        }
+
+        //上次生成ID的时间截
+        lastTimestamp = timestamp;
+
+        //移位并通过或运算拼到一起组成64位的ID
+        return ((timestamp - twepoch) << timestampLeftShift) //
+                | (datacenterId << datacenterIdShift) //
+                | (workerId << workerIdShift) //
+                | sequence;
+    }
+
+    public synchronized long newId() {
+        long timestamp = timeGen();
+
+        //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
+        if (timestamp < lastTimestamp) {
+            throw new RuntimeException(
+                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
+        }
+        //如果是同一时间生成的,则进行毫秒内序列
+        if (lastTimestamp == timestamp) {
+            sequence = (sequence + 1) & sequenceMask;
+            //毫秒内序列溢出
+            if (sequence == 0) {
+                //阻塞到下一个毫秒,获得新的时间戳
+                timestamp = tilNextMillis(lastTimestamp);
+            }
+        }
+        //时间戳改变,毫秒内序列重置
+        else {
+            sequence = 0L;
+        }
+
+        //上次生成ID的时间截
+        lastTimestamp = timestamp;
+
+        //移位并通过或运算拼到一起组成64位的ID
+        return ((timestamp - twepoch) << timestampLeftShift) //
+                | (datacenterId << datacenterIdShift) //
+                | (workerId << workerIdShift) //
+                | sequence;
+    }
+
+    /**
+     * 阻塞到下一个毫秒,直到获得新的时间戳
+     *
+     * @param lastTimestamp 上次生成ID的时间截
+     * @return 当前时间戳
+     */
+    protected long tilNextMillis(long lastTimestamp) {
+        long timestamp = timeGen();
+        while (timestamp <= lastTimestamp) {
+            timestamp = timeGen();
+        }
+        return timestamp;
+    }
+
+    /**
+     * 返回以毫秒为单位的当前时间
+     *
+     * @return 当前时间(毫秒)
+     */
+    protected long timeGen() {
+        return System.currentTimeMillis();
+    }
+
+    //==============================Test=============================================
+
+    /**
+     * 测试
+     */
+    public static void main(String[] args) {
+        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
+        for (int i = 0; i < 5; i++) {
+            long id = idWorker.nextId();
+            System.out.println(Long.toBinaryString(id));
+            System.out.println(id);
+        }
+        System.out.println("");
+        SnowflakeIdWorker idWorker1 = new SnowflakeIdWorker(1, 0);
+        for (int i = 0; i < 5; i++) {
+            long id = idWorker1.nextId();
+            System.out.println(Long.toBinaryString(id));
+            System.out.println(id);
+        }
+        long abc = 921133285172576260L;
+        System.out.println("abc>>"+abc);
+    }
+}

+ 1 - 0
huimv-farm-device/huimv-farm-business/src/main/java/com/huimv/business/utils/TextUtil.java

@@ -20,6 +20,7 @@ public class TextUtil {
     public String translateSymbol(String data) throws UnsupportedEncodingException {
         return decode(data.replace("data=","").replace("%3D","="));
     }
+
     //base64编码
     public String encode(String text) throws UnsupportedEncodingException {
         final Base64.Encoder encoder = Base64.getEncoder();

+ 7 - 4
huimv-farm-device/huimv-farm-business/src/main/resources/application.properties

@@ -6,7 +6,9 @@ spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
 spring.jackson.time-zone=GMT+8
 
 # 数据中心数据推送地址
-dataCenter.ipAddr=http://115.238.57.190
+#dataCenter.ipAddr=http://115.238.57.190
+#测试IP
+dataCenter.ipAddr=http://192.168.1.49
 dataCenter.port=:10091
 # 日总称重数据服务
 dataCenter.service.dayWeight=/receiver/farm/weight/putDayWeight
@@ -21,6 +23,7 @@ weight.batchCode.spacemark=-
 
 #数据中心端设备数据是否同步(true/false),默认是true(同步数据)
 dataCenter.device.sync=true
-dataCenter.device.addService=/farm/local/device/syncAddFarmDevice
-dataCenter.device.editService=/farm/local/device/syncEditFarmDevice
-dataCenter.device.removeService=/farm/local/device/syncRemoveFarmDevice
+dataCenter.device.addService=/center/device/syncAddFarmDevice
+dataCenter.device.editService=/center/device/syncEditFarmDevice
+dataCenter.device.removeService=/center/device/syncRemoveFarmDevice
+dataCenter.device.port=:8098