Sfoglia il codice sorgente

增加2个接口:牧场端新建和编辑设备数据,同时将编辑数据同步到数据中心端。

zhuoning 3 anni fa
parent
commit
f0aa10ea43

+ 41 - 0
huimv-farm-receiver/src/main/java/com/huimv/receiver/farm/controller/CenterDeviceController.java

@@ -0,0 +1,41 @@
+package com.huimv.receiver.farm.controller;
+
+import com.huimv.common.utils.Result;
+import com.huimv.common.utils.ResultCode;
+import com.huimv.receiver.farm.service.ICenterDevice;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.io.UnsupportedEncodingException;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@RestController
+@Slf4j
+@RequestMapping(value = "/center/device")
+public class CenterDeviceController {
+    @Autowired
+    private ICenterDevice iCenterDevice;
+
+    @RequestMapping(value = "/syncAddFarmDevice")
+    public Result syncAddDevice(@RequestBody String deviceData) throws UnsupportedEncodingException {
+        System.out.println("接收远程推送数据>>"+deviceData);
+        return iCenterDevice.syncAddFarmDevice(deviceData);
+    }
+
+    @RequestMapping(value = "/syncEditFarmDevice")
+    public Result syncEditDevice(@RequestBody String deviceData) throws UnsupportedEncodingException {
+        System.out.println("接收远程推送数据>>"+deviceData);
+        return iCenterDevice.syncEditFarmDevice(deviceData);
+    }
+}

+ 200 - 0
huimv-farm-receiver/src/main/java/com/huimv/receiver/farm/dao/entity/FarmDeviceEntity.java

@@ -0,0 +1,200 @@
+package com.huimv.receiver.farm.dao.entity;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.sql.Timestamp;
+
+@Entity
+@Table(name = "farm_device")
+public class FarmDeviceEntity implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id", nullable = false)
+    private Integer id;
+
+    @Column(name = "device_name")
+    private String deviceName;
+
+    @Column(name = "device_code")
+    private String deviceCode;
+
+    @Column(name = "device_type")
+    private String deviceType;
+
+    @Column(name = "factory")
+    private String factory;
+
+    @Column(name = "worker")
+    private String worker;
+
+    @Column(name = "main_params")
+    private String mainParams;
+
+    @Column(name = "state")
+    private Integer state;
+
+    @Column(name = "record")
+    private String record;
+
+    @Column(name = "last_time")
+    private Timestamp lastTime;
+
+    @Column(name = "up_time")
+    private Timestamp upTime;
+
+    @Column(name = "down_time")
+    private Timestamp downTime;
+
+    @Column(name = "lockin_state")
+    private Integer lockinState;
+
+    @Column(name = "farm_id")
+    private Integer farmId;
+
+    @Column(name = "data_id")
+    private Long dataId;
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setDeviceName(String deviceName) {
+        this.deviceName = deviceName;
+    }
+
+    public String getDeviceName() {
+        return deviceName;
+    }
+
+    public void setDeviceCode(String deviceCode) {
+        this.deviceCode = deviceCode;
+    }
+
+    public String getDeviceCode() {
+        return deviceCode;
+    }
+
+    public void setDeviceType(String deviceType) {
+        this.deviceType = deviceType;
+    }
+
+    public String getDeviceType() {
+        return deviceType;
+    }
+
+    public void setFactory(String factory) {
+        this.factory = factory;
+    }
+
+    public String getFactory() {
+        return factory;
+    }
+
+    public void setWorker(String worker) {
+        this.worker = worker;
+    }
+
+    public String getWorker() {
+        return worker;
+    }
+
+    public void setMainParams(String mainParams) {
+        this.mainParams = mainParams;
+    }
+
+    public String getMainParams() {
+        return mainParams;
+    }
+
+    public void setState(Integer state) {
+        this.state = state;
+    }
+
+    public Integer getState() {
+        return state;
+    }
+
+    public void setRecord(String record) {
+        this.record = record;
+    }
+
+    public String getRecord() {
+        return record;
+    }
+
+    public void setLastTime(Timestamp lastTime) {
+        this.lastTime = lastTime;
+    }
+
+    public Timestamp getLastTime() {
+        return lastTime;
+    }
+
+    public void setUpTime(Timestamp upTime) {
+        this.upTime = upTime;
+    }
+
+    public Timestamp getUpTime() {
+        return upTime;
+    }
+
+    public void setDownTime(Timestamp downTime) {
+        this.downTime = downTime;
+    }
+
+    public Timestamp getDownTime() {
+        return downTime;
+    }
+
+    public void setLockinState(Integer lockinState) {
+        this.lockinState = lockinState;
+    }
+
+    public Integer getLockinState() {
+        return lockinState;
+    }
+
+    public void setFarmId(Integer farmId) {
+        this.farmId = farmId;
+    }
+
+    public Integer getFarmId() {
+        return farmId;
+    }
+
+    public Long getDataId() {
+        return dataId;
+    }
+
+    public void setDataId(Long dataId) {
+        this.dataId = dataId;
+    }
+
+    @Override
+    public String toString() {
+        return "FarmDeviceEntity{" +
+                "id=" + id +
+                ", deviceName='" + deviceName + '\'' +
+                ", deviceCode='" + deviceCode + '\'' +
+                ", deviceType='" + deviceType + '\'' +
+                ", factory='" + factory + '\'' +
+                ", worker='" + worker + '\'' +
+                ", mainParams='" + mainParams + '\'' +
+                ", state=" + state +
+                ", record='" + record + '\'' +
+                ", lastTime=" + lastTime +
+                ", upTime=" + upTime +
+                ", downTime=" + downTime +
+                ", lockinState=" + lockinState +
+                ", farmId=" + farmId +
+                ", dataId=" + dataId +
+                '}';
+    }
+}

+ 15 - 0
huimv-farm-receiver/src/main/java/com/huimv/receiver/farm/dao/repo/FarmDeviceRepo.java

@@ -0,0 +1,15 @@
+package com.huimv.receiver.farm.dao.repo;
+
+import com.huimv.receiver.farm.dao.entity.FarmDeviceEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+
+import java.util.Optional;
+
+public interface FarmDeviceRepo extends JpaRepository<FarmDeviceEntity, Integer>, JpaSpecificationExecutor<FarmDeviceEntity> {
+
+    //查询
+    @Query(nativeQuery = true,value = "SELECT * FROM farm_device WHERE data_id=?1")
+    Optional<FarmDeviceEntity> getByDataId(Long dataId);
+}

+ 13 - 0
huimv-farm-receiver/src/main/java/com/huimv/receiver/farm/service/ICenterDevice.java

@@ -0,0 +1,13 @@
+package com.huimv.receiver.farm.service;
+
+import com.huimv.common.utils.Result;
+
+import java.io.UnsupportedEncodingException;
+
+public interface ICenterDevice {
+    //同步添加牧场设备数据
+    Result syncAddFarmDevice(String deviceData) throws UnsupportedEncodingException;
+
+    //同步编辑牧场设备数据
+    Result syncEditFarmDevice(String deviceData) throws UnsupportedEncodingException;
+}

+ 87 - 0
huimv-farm-receiver/src/main/java/com/huimv/receiver/farm/service/impl/CenterDeviceImpl.java

@@ -0,0 +1,87 @@
+package com.huimv.receiver.farm.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.common.utils.Result;
+import com.huimv.common.utils.ResultCode;
+import com.huimv.receiver.farm.dao.entity.FarmDeviceEntity;
+import com.huimv.receiver.farm.dao.repo.FarmDeviceRepo;
+import com.huimv.receiver.farm.service.ICenterDevice;
+import com.huimv.receiver.utils.TextUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.io.UnsupportedEncodingException;
+import java.sql.Timestamp;
+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 CenterDeviceImpl implements ICenterDevice {
+    @Autowired
+    private FarmDeviceRepo deviceRepo;
+    @Autowired
+    private TextUtil textUtil;
+
+    @Override
+    public Result syncAddFarmDevice(String deviceData) throws UnsupportedEncodingException {
+        //转义符号处理
+        JSONObject deviceDataJo = JSON.parseObject(textUtil.translateSymbol(deviceData));
+        FarmDeviceEntity deviceEntity = new FarmDeviceEntity();
+        deviceEntity.setDataId(deviceDataJo.getLong("dataId"));
+        deviceEntity.setDeviceCode(deviceDataJo.getString("deviceCode"));
+        deviceEntity.setDeviceName(deviceDataJo.getString("deviceName"));
+        deviceEntity.setDeviceType(deviceDataJo.getString("deviceType"));
+        deviceEntity.setUpTime(new Timestamp(new  java.util.Date().getTime()));
+        deviceEntity.setFactory(deviceDataJo.getString("factory"));
+        deviceEntity.setFarmId(deviceDataJo.getInteger("farmId"));
+        deviceEntity.setLastTime(new Timestamp(new  java.util.Date().getTime()));
+        deviceEntity.setLockinState(deviceDataJo.getInteger("lockinState"));
+        deviceEntity.setMainParams(deviceDataJo.getString("mainParams"));
+        deviceEntity.setRecord(deviceDataJo.getString("record"));
+        deviceEntity.setState(deviceDataJo.getInteger("state"));
+        deviceEntity.setWorker(deviceDataJo.getString("worker"));
+        FarmDeviceEntity addEntity = deviceRepo.saveAndFlush(deviceEntity);
+        log.info("同步添加数据中心端设备数据>>"+addEntity);
+        return new Result(ResultCode.SUCCESS,addEntity);
+    }
+
+    @Override
+    public Result syncEditFarmDevice(String deviceData) throws UnsupportedEncodingException {
+        //转义符号处理
+        JSONObject deviceDataJo = JSON.parseObject(textUtil.translateSymbol(deviceData));
+        //查找已经存在的记录
+        Optional<FarmDeviceEntity> optional = deviceRepo.getByDataId(deviceDataJo.getLong("dataId"));
+        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.setUpTime(new Timestamp(new  java.util.Date().getTime()));
+        deviceEntity.setFactory(deviceDataJo.getString("factory"));
+        deviceEntity.setFarmId(deviceDataJo.getInteger("farmId"));
+        deviceEntity.setLastTime(new Timestamp(new  java.util.Date().getTime()));
+        deviceEntity.setLockinState(deviceDataJo.getInteger("lockinState"));
+        deviceEntity.setMainParams(deviceDataJo.getString("mainParams"));
+        deviceEntity.setRecord(deviceDataJo.getString("record"));
+        deviceEntity.setState(deviceDataJo.getInteger("state"));
+        deviceEntity.setWorker(deviceDataJo.getString("worker"));
+        FarmDeviceEntity editEntity = deviceRepo.saveAndFlush(deviceEntity);
+        log.info("同步更新数据中心端设备数据>>"+editEntity);
+        return new Result(ResultCode.SUCCESS,editEntity);
+    }
+}

+ 216 - 0
huimv-farm-receiver/src/main/java/com/huimv/receiver/utils/SnowflakeIdWorker.java

@@ -0,0 +1,216 @@
+package com.huimv.receiver.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;
+    }
+
+    /**
+     * @Method      : newId
+     * @Description : 
+     * @Params      : []
+     * @Return      : long
+     * 
+     * @Author      : ZhuoNing
+     * @Date        : 2021/12/16       
+     * @Time        : 20:37
+     */
+    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);
+    }
+}

+ 36 - 0
huimv-farm-receiver/src/main/java/com/huimv/receiver/utils/TextUtil.java

@@ -0,0 +1,36 @@
+package com.huimv.receiver.utils;
+
+import org.springframework.stereotype.Component;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Base64;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@Component
+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();
+        final byte[] textByte = text.replaceAll(" ", "").getBytes("UTF-8");
+        return encoder.encodeToString(textByte);
+    }
+
+    //base64解码
+    public String decode(String encodedText) throws UnsupportedEncodingException {
+        final Base64.Decoder decoder = Base64.getDecoder();
+        return new String(decoder.decode(encodedText.toString().replace("\r\n", "")), "UTF-8");
+    }
+}

+ 1 - 1
huimv-farm-receiver/src/main/resources/application-dev.yml

@@ -5,7 +5,7 @@ spring:
     name: huimv-farm-receiver
   #------DataSource-----
   datasource:
-    url: jdbc:mysql://192.168.1.7:3306/huimv-farm-device?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai
+    url: jdbc:mysql://192.168.1.7:3306/huimv-farm-center?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai
     username: root
     password: hm123456
     driver-class-name: com.mysql.cj.jdbc.Driver