jiazx0107@163.com
2023-12-12 46203ee88249d9a4046f3d453deb41edc562cf6c
src/main/java/com/fzzy/gateway/service/GatewayDeviceService.java
@@ -1,40 +1,23 @@
package com.fzzy.gateway.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.fzzy.api.data.GatewayDeviceType;
import com.fzzy.api.Constant;
import com.fzzy.api.data.ApiCommonDevice;
import com.fzzy.api.utils.ContextUtil;
import com.fzzy.api.utils.DateUtil;
import com.fzzy.async.fzzy40.Fzzy40CommonService;
import com.fzzy.async.fzzy40.entity.Fz40Grain;
import com.fzzy.gateway.GatewayUtils;
import com.fzzy.gateway.api.DeviceReportService;
import com.fzzy.gateway.api.GatewayRemoteManager;
import com.fzzy.gateway.data.BaseResp;
import com.fzzy.gateway.entity.GatewayDevice;
import com.fzzy.gateway.hx2023.ScConstant;
import com.fzzy.gateway.hx2023.data.*;
import com.fzzy.gateway.service.repository.GatewayDeviceRep;
import com.fzzy.mqtt.MqttProviderConfig;
import com.fzzy.mqtt.MqttPublishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Slf4j
@Component
@@ -42,14 +25,6 @@
    @Resource
    private GatewayDeviceRep gatewayDeviceRep;
    @Resource
    private Fzzy40CommonService fzzy40CommonService;
    @Resource
    private GatewayRemoteManager gatewayRemoteManager;
    @Resource
    private MqttPublishService mqttPublishService;
    @Resource
    private MqttProviderConfig providerClient;
    /**
     * gatewayDeviceService#listAll
@@ -59,7 +34,27 @@
    @DataProvider
    public List<GatewayDevice> listAll() {
        Sort sort = new Sort(Sort.Direction.ASC, "deviceId");
        return gatewayDeviceRep.findAll(sort);
        List<GatewayDevice> list = gatewayDeviceRep.findAll(sort);
        if (null == list || list.isEmpty()) return list;
        List<GatewayDevice> result = new ArrayList<>();
        GatewayDevice cacheDevice;
        for (GatewayDevice device : list) {
            device.setStatus(Constant.YN_Y);
            cacheDevice = GatewayUtils.getCacheByDeviceId(device.getDeviceId());
            if (null != cacheDevice) {
                device.setIp(cacheDevice.getIp());
                device.setPort(cacheDevice.getPort());
                device.setStatus(cacheDevice.getStatus());
                device.setOnlineTime(cacheDevice.getOnlineTime());
            }
            result.add(device);
        }
        return result;
    }
    /**
@@ -106,7 +101,6 @@
        return null;
    }
    public void flushCache() {
        List<GatewayDevice> list = listAll();
        if (null == list || list.isEmpty()) return;
@@ -116,311 +110,42 @@
    }
    /**
     * gatewayDeviceService#ajaxTestWeight
     * 地磅推送测试
     *
     * @param parameter
     * @return
     */
    @Expose
    public String ajaxTestWeight() {
        //double weigh = (double) parameter.getWeight();
        double weigh = Math.random() * (35000 - 16000 + 1) + 16000;
        List<GatewayDevice> devices = listAll();
        if (devices == null || devices.size() <= 0) {
            return "没有设备";
        }
        List<GatewayDevice> weights = devices.stream().filter(s -> (GatewayDeviceType.TYPE_01.getCode().equals(s.getType()))).collect(Collectors.toList());
        if (weights == null || weights.size() <= 0) {
            return "没有获取到地磅设备";
        }
        String topic = "/device/hx-weigh-big-01/91511424746940066Y001_91511424746940066Y0010000_002_004_002_001/message/property/report";
        for (GatewayDevice device : weights) {
            WebSocketPacket packet = new WebSocketPacket();
            //productId的值在webSocket执行发送方法中补充
            WebSocketPacketHeader header = new WebSocketPacketHeader();
            header.setDeviceName(device.getDeviceName());
            header.setProductId("hx-weigh-big-01");
            //header.set
            packet.setHeaders(header);
            packet.setMessageType(ScConstant.MESSAGE_TYPE_REPORT_PROPERTY);
            packet.setDeviceId(device.getDeviceId());
            //设置信息主体
            WeightInfo weightInfo = new WeightInfo();
            weightInfo.setGrossWeight(weigh);
            weightInfo.setNetWeight(weigh);
            weightInfo.setNetWeight(weigh);
            weightInfo.setWeightUnit("KG");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("weightInfo", JSONObject.toJSONString(weightInfo));
            packet.setProperties(jsonObject);
            packet.setTimestamp(System.currentTimeMillis());
            topic = "/device/" + header.getProductId() + "/" + device.getDeviceId() + "/message/property/report";
            mqttPublishService.publishMsg(topic, JSON.toJSONString(packet));
        }
    public String test() {
        log.info("-----------test-------------------");
        return "SUCCESS";
    }
    /**
     * gatewayDeviceService#ajaxTestLpr
     * 地磅推送测试
     * 根据实际通讯分机设置,当前分机在线
     *
     * @return
     * @param commonDevice 实际通讯设备
     */
    @Expose
    public String ajaxTestLpr() {
        //String carNumber = parameter.getCarNumber();
        String carNumber = "川A12345";
        List<GatewayDevice> devices = listAll();
        if (devices == null || devices.size() <= 0) {
            return "没有设备";
        }
        List<GatewayDevice> weights = devices.stream().filter(s -> (GatewayDeviceType.TYPE_02.getCode().equals(s.getType()))).collect(Collectors.toList());
        if (weights == null || weights.size() <= 0) {
            return "没有获取到设备";
        }
        String topic = "/device/hx-weigh-big-01/91511424746940066Y001_91511424746940066Y0010000_002_004_002_001/message/property/report";
    public void onlineByCommonDevice(ApiCommonDevice commonDevice) {
        List<GatewayDevice> list = GatewayUtils.getCacheByDeviceSn2(commonDevice.getSn());
        if (null == list || list.isEmpty()) return;
        for (GatewayDevice device : weights) {
            WebSocketPacket packet = new WebSocketPacket();
            //productId的值在webSocket执行发送方法中补充
            WebSocketPacketHeader header = new WebSocketPacketHeader();
            header.setDeviceName(device.getDeviceName());
            header.setProductId("hx-catch-01");
            //header.set
            packet.setHeaders(header);
            packet.setMessageType(ScConstant.MESSAGE_TYPE_REPORT_PROPERTY);
            packet.setDeviceId(device.getDeviceId());
            packet.setMessageId(System.currentTimeMillis() + "");
            //设置信息主体
            LprData lpr = new LprData();
            lpr.setDeviceId(device.getDeviceId());
            lpr.setCarNumber(carNumber);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("carNumber", carNumber);
            jsonObject.put("position", "big");
            packet.setProperties(jsonObject);
            packet.setTimestamp(System.currentTimeMillis());
            topic = "/device/" + header.getProductId() + "/" + device.getDeviceId() + "/message/property/report";
            mqttPublishService.publishMsg(topic, JSON.toJSONString(packet));
        }
        return "SUCCESS";
    }
    /**
     * gatewayDeviceService#ajaxTestGrain
     * 粮情推送测试
     *
     * @param parameter
     * @return
     */
    @Expose
    public String ajaxTestGrain(GateWayTestParam parameter) {
        //获取设备配置,只针对粮情设备进行执行
        List<GatewayDevice> list = this.listAll();
        if (null == list || list.isEmpty()) {
            return "ERROR:为获取到系统中设备配置,取消执行";
        }
        Date dayTime = (Date) parameter.getDayTime();
        if (null == dayTime) dayTime = new Date();
        Date start = DateUtil.getCurZero(dayTime);
        Date end = DateUtil.getNextZero(dayTime);
        //如果部署FZZY-IGDS-V40版本系统
        return this.pushByV40(list, start, end);
    }
    private String pushByV40(List<GatewayDevice> list, Date start, Date end) {
        String depotIdSys;
        List<Fz40Grain> listGrain;
        Fz40Grain lastData;
        KafaGrainData pushData;
        DeviceReportService deviceReportService = null;
        for (GatewayDevice device : list) {
            depotIdSys = device.getDepotIdSys();
            device.setIp(commonDevice.getIp());
            device.setPort(commonDevice.getPort());
            device.setOnlineTime(new Date());
            device.setStatus(Constant.YN_Y);
            if (StringUtils.isEmpty(depotIdSys)) {
                log.info("--------设备--{}-未配置系统相关仓库编码,无法执行当前操作", device.getDeviceName());
                continue;
            }
            listGrain = fzzy40CommonService.listGrain(depotIdSys, start, end);
            if (null == listGrain || listGrain.isEmpty()) {
                log.info("---------设备---{}--未同步到粮情信息,请确认当前条件下是否有数据", device.getDeviceName());
                continue;
            }
            //获取最后一条粮情作为当前数据
            lastData = listGrain.get(listGrain.size() - 1);
            pushData = this.lastData2PushData(lastData, device);
            if (null == deviceReportService) {
                deviceReportService = gatewayRemoteManager.getDeviceReportService(device.getProvinceProtocol());
            }
            deviceReportService.pushGrainData2Cloud(pushData);
            GatewayUtils.add2Cache(device);
        }
        return "SUCCESS";
    }
    /**
     * 将粮情数据转换为推送需要的数据格式
     *
     * @param lastData
     * @return
     */
    private KafaGrainData lastData2PushData(Fz40Grain lastData, GatewayDevice device) {
        KafaGrainData result = new KafaGrainData();
    public void OfflineByCommonDevice(ApiCommonDevice commonDevice) {
        List<GatewayDevice> list = GatewayUtils.getCacheByDeviceSn2(commonDevice.getSn());
        if (null == list || list.isEmpty()) return;
        result.setMessageId(ScConstant.getMessageId());
        result.setMessgeId(result.getMessageId());
        result.setDeviceID(device.getDeviceId());
        result.setAvgTemperature(lastData.getTempAve() + "");
        result.setMinTemperature(lastData.getTempMin() + "");
        result.setMaxTemperature(lastData.getTempMax() + "");
        result.setCollectTime(DateFormatUtils.format(lastData.getReceiveDate(), "yyyy-MM-dd HH:mm:ss"));
        for (GatewayDevice device : list) {
            device.setIp(commonDevice.getIp());
            device.setPort(commonDevice.getPort());
            //device.setOnlineTime(new Date());
            device.setStatus(Constant.YN_N);
        //层-行-列
        String[] attrCable = lastData.getCable().split("-");
        if (StringUtils.isNotEmpty(lastData.getCableCir())) {
            return lastData2PushData2(lastData, device);
            GatewayUtils.add2Cache(device);
        }
        //层行列
        int cableZ = Integer.valueOf(attrCable[0]);
        int cableY = Integer.valueOf(attrCable[1]);
        int cableX = Integer.valueOf(attrCable[2]);
        //温度集合
        String[] attr = lastData.getPoints().split(",");
        //根号
        int cableNum = 1, position = 0;
        String curTemp;
        List<KafkaGrainDataDetail1> temperature = new ArrayList<>();
        int x = 0, y = 0, z = 0;
        for (int i = 0; i < attr.length; i++) {
            position = i;
            z = i % cableZ + 1;
            x = i / (cableZ * cableY);
            y = x * (cableZ * cableY);
            y = (i - y) / cableZ;
            // 倒转X轴
            x = cableX - 1 - x;
            //根号
            cableNum = (i / cableZ) + 1;
            curTemp = attr[i];
            //判断最大
            if (curTemp.equals(result.getMaxTemperature())) {
                result.setMaxX(x + "");
                result.setMaxY(y + "");
                result.setMaxZ(position + "");
            }
            //判断最小
            if (curTemp.equals(result.getMinTemperature())) {
                result.setMinX(x + "");
                result.setMinY(y + "");
                result.setMinZ(position + "");
            }
            temperature.add(new KafkaGrainDataDetail1(cableNum + "", z + "", curTemp, position + "", x + "", y + ""));
        }
        //粮温信息
        JSONObject trhInfo = new JSONObject();
        // TRHInfo trhInfo = new TRHInfo();
        trhInfo.put("temperature", temperature);
        //仓温度信息
        KafkaGrainTH grainTH = new KafkaGrainTH();
        grainTH.setHumidity(lastData.getHumidityIn() + "");
        grainTH.setTemperature(lastData.getTempIn() + "");
        grainTH.setAirHumidity(lastData.getHumidityOut() + "");
        grainTH.setAirTemperature(lastData.getTempOut() + "");
        List<KafkaGrainTH> temperatureAndhumidity = new ArrayList<>();
        temperatureAndhumidity.add(grainTH);
        trhInfo.put("temperatureAndhumidity", temperatureAndhumidity);
        //trhInfo.put("temperatureAndhumidity",grainTH);
        JSONObject params = new JSONObject();
        params.put("TRHInfo", trhInfo);
        result.setParams(params);
        return result;
    }
    /**
     * 针对筒仓  TODO -----
     *
     * @param lastData
     * @param device
     * @return
     */
    private KafaGrainData lastData2PushData2(Fz40Grain lastData, GatewayDevice device) {
        return null;
    }
    private int getCurCir(int curRoot, String[] cableRuleAtt) {
        int sum = 0;
        for (int i = 0; i < cableRuleAtt.length; i++) {
            sum += Integer.valueOf(cableRuleAtt[i]);
            if (curRoot <= sum) return i + 1;
        }
        return 1;
    }
}