jiazx0107@163.com
2023-11-18 328eba66ddc6fdf2f324b9cd04cd6acec9f642de
增加HTTP地磅协议实现
已修改8个文件
已添加1个文件
181 ■■■■ 文件已修改
src/main/java/com/fzzy/gateway/GatewayRunner.java 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/GatewayTimerScheduled.java 49 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/GatewayUtils.java 21 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/api/GatewaySyncWeightService.java 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/hx2023/service/HxGatewayRemoteServiceImpl.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/util/GatewayHttpUtil.java 12 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/protocol/ProtocolRunner.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/protocol/weightyh/GatewaySyncWeightImplHttp.java 82 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/protocol/weightyh/MessageConsumer.java 5 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/fzzy/gateway/GatewayRunner.java
@@ -20,10 +20,9 @@
    @Resource
    private ApiInitService apiInitService;
    @Autowired
    @Resource
    private MqttPublishService mqttPublishService;
    @Autowired
    @Resource
    private  GatewayTimerScheduled scheduled;
src/main/java/com/fzzy/gateway/GatewayTimerScheduled.java
@@ -2,13 +2,16 @@
import com.alibaba.fastjson.JSON;
import com.fzzy.api.data.ApiParam;
import com.fzzy.api.data.GatewayDeviceProtocol;
import com.fzzy.api.entity.ApiConfs;
import com.fzzy.api.service.*;
import com.fzzy.api.utils.ContextUtil;
import com.fzzy.api.utils.RedisUtil;
import com.fzzy.gateway.api.GatewayRemoteManager;
import com.fzzy.gateway.data.BaseReqData;
import com.fzzy.gateway.data.WeatherWebDto;
import com.fzzy.gateway.entity.GatewayConf;
import com.fzzy.gateway.entity.GatewayDevice;
import com.fzzy.gateway.service.GatewayConfService;
import com.fzzy.gateway.util.GatewayHttpUtil;
import lombok.extern.slf4j.Slf4j;
@@ -19,6 +22,7 @@
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;
@@ -39,7 +43,6 @@
    @Resource
    private GatewayConfService confService;
    @Resource
    private GatewayRemoteManager gatewayRemoteManager;
@@ -48,13 +51,25 @@
     * <p>
     * å›ºå®šæ—¶é—´ï¼šæ¯é—´éš”10分钟执行一次
     */
    @Scheduled(cron = "0 0/10 * * * ? ")
    @Scheduled(cron = "0 0/10 * * * ?")
    public void scheduled() {
        //网关的心跳执行
        doHeartbeat();
    }
    /**
     * <p>
     * æ¯é—´éš”3秒执行一次事件
     */
    @Scheduled(cron = "0/3 * * * * ?")
    public void scheduled3() {
        //执行HTTP地磅请求
        exeHttpWeightReq();
    }
    /**
     * æ¯é—´éš”30分钟执行一次
@@ -73,7 +88,7 @@
            url = url.replace("{appId}", DEFAULT_APP_ID).replace("{appsecret}", DEFAULT_APP_SECRET).replace("{cityid}", DEFAULT_CITYID);
            log.debug("------气象URL---{}",url);
            log.debug("------气象URL---{}", url);
            String result = GatewayHttpUtil.doGet(url, null);
            if (null == result) {
@@ -89,7 +104,7 @@
            WeatherWebDto.contextMap.put("default", dto);
            log.info("===========================系统定时获获取气象信息===={}==================",dto);
            log.info("===========================系统定时获获取气象信息===={}==================", dto);
        } catch (Exception e) {
@@ -114,4 +129,30 @@
        }
    }
    /**
     * æ‰§è¡Œåœ°ç£…HTTP请求协议
     */
    private void exeHttpWeightReq() {
        //获取设备
        Collection<GatewayDevice> list = GatewayUtils.listDeviceWeight();
        if (null == list || list.isEmpty()) return;
        BaseReqData reqData;
        for (GatewayDevice device : list) {
            if (!GatewayDeviceProtocol.DEVICE_WEIGHT_HTTP.getCode().equals(device.getSyncProtocol())) {
                continue;
            }
            reqData = new BaseReqData();
            reqData.setDevice(device);
            reqData.setDeviceName(device.getDeviceName());
            reqData.setProductId(device.getProductId());
            reqData.setDeviceId(device.getDeviceId());
            gatewayRemoteManager.getSyncWeightService(device.getSyncProtocol()).syncWeightInfo(reqData);
        }
    }
}
src/main/java/com/fzzy/gateway/GatewayUtils.java
@@ -1,12 +1,10 @@
package com.fzzy.gateway;
import com.fzzy.api.data.GatewayDeviceType;
import com.fzzy.gateway.entity.GatewayDevice;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
 * å¸¸é‡
@@ -31,10 +29,20 @@
     */
    public static Map<String, GatewayDevice> cacheMapDeviceSn = new HashMap<>();
    /**
     * è®¾å¤‡ç¼“å­˜-只针对
     */
    public static Map<String, GatewayDevice> cacheMapDeviceWeight = new HashMap<>();
    public static void add2Cache(GatewayDevice device) {
        cacheMapDeviceId.put(device.getDeviceId(), device);
        cacheMapDeviceSn.put(device.getDeviceSn(), device);
        //保存地磅
        if (GatewayDeviceType.TYPE_01.getCode().equals(device.getType())) {
            cacheMapDeviceWeight.put(device.getDeviceId(), device);
        }
    }
    public static GatewayDevice getCacheByDeviceId(String deviceId) {
@@ -79,4 +87,9 @@
        if (null == value || "N".equals(value)) return false;
        return true;
    }
    public static Collection<GatewayDevice> listDeviceWeight(){
        return cacheMapDeviceWeight.values();
    }
}
src/main/java/com/fzzy/gateway/api/GatewaySyncWeightService.java
@@ -2,6 +2,7 @@
import com.fzzy.gateway.data.BaseReqData;
import com.fzzy.gateway.data.BaseResp;
import com.fzzy.gateway.hx2023.data.*;
/**
@@ -22,5 +23,5 @@
     *
     * @return
     */
    public WeightInfo syncWeightInfo(BaseReqData reqData);
    public BaseResp syncWeightInfo(BaseReqData reqData);
}
src/main/java/com/fzzy/gateway/hx2023/service/HxGatewayRemoteServiceImpl.java
@@ -120,7 +120,7 @@
            String url = gatewayConf.getApiUrl() + "reserver/api/iot/equipment/heartbeat";
            String jsonStr = GatewayHttpUtil.doGet(url, params);
            log.info("---网关心跳接口-返回---{}", jsonStr);
           // log.info("---网关心跳接口-返回---{}", jsonStr);
        } catch (Exception e) {
            log.error("------网关心跳接口--执行失败-----{}", e);
src/main/java/com/fzzy/gateway/util/GatewayHttpUtil.java
@@ -20,12 +20,13 @@
    /**
     * æ‰§è¡ŒGET请求
     *
     * @param url
     * @param paramsMap
     * @return
     * @throws Exception
     */
    public static String doGet(String url,Map<String, String> paramsMap) throws Exception{
    public static String doGet(String url, Map<String, String> paramsMap) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
@@ -33,7 +34,7 @@
            String getUrl = url + "?";
            if (paramsMap != null) {
                for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                  //  getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(), "UTF-8") + "&";
                    //  getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(), "UTF-8") + "&";
                    getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(), "UTF-8") + "&";
                }
            }
@@ -47,18 +48,17 @@
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity,"UTF-8");
                responseText = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            log.error("http request failed", e);
            log.error("http request failed--{}", e.getMessage());
        } finally {
            try {
                response.close();
                if (null != response) response.close();
            } catch (Exception e) {
                log.error("", e);
            }
        }
        return responseText;
    }
src/main/java/com/fzzy/protocol/ProtocolRunner.java
@@ -17,6 +17,8 @@
    public void run(String... args) throws Exception {
        YhScaleServerEngine.start();
    }
}
src/main/java/com/fzzy/protocol/weightyh/GatewaySyncWeightImplHttp.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,82 @@
package com.fzzy.protocol.weightyh;
import com.alibaba.fastjson2.JSONObject;
import com.fzzy.api.data.GatewayDeviceProtocol;
import com.fzzy.gateway.api.GatewayRemoteManager;
import com.fzzy.gateway.api.GatewaySyncWeightService;
import com.fzzy.gateway.data.BaseReqData;
import com.fzzy.gateway.data.BaseResp;
import com.fzzy.gateway.entity.GatewayDevice;
import com.fzzy.gateway.util.GatewayHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
 * HTTP方式获取地磅信息
 * <p>
 * æ³¨ï¼šå½“前协议包含JSON和JSONP两种支持,自动识别
 */
@Slf4j
@Component
public class GatewaySyncWeightImplHttp implements GatewaySyncWeightService {
    @Resource
    private GatewayRemoteManager gatewayRemoteManager;
    @Override
    public String getWeightProtocol() {
        return GatewayDeviceProtocol.DEVICE_WEIGHT_HTTP.getCode();
    }
    @Override
    public BaseResp syncWeightInfo(BaseReqData reqData) {
        GatewayDevice device = reqData.getDevice();
        if (null == device) return new BaseResp(500, "没有获取到设备信息");
        if (StringUtils.isEmpty(device.getHttpUrl())) new BaseResp(500, "没有配置HTTP请求地址");
        try {
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put("time_", System.currentTimeMillis() + "");
            String responseText = GatewayHttpUtil.doGet(device.getHttpUrl(), paramsMap);
            log.debug("--HTTP-WEIGHT-请求返回--{}", responseText);
            String respJson;
            JSONObject resp;
            //说明是JSONP格式-jsonpCallback({"content":""})
            if (responseText.indexOf("jsonpCallback") >= 0) {
                respJson = responseText.substring(responseText.indexOf("(") + 1, responseText.length() - 1);
                resp = JSONObject.parseObject(respJson);
                resp.put("code", 200);
            } else {
                respJson = responseText;
                resp = JSONObject.parseObject(respJson);
            }
            if (200 == (Integer) resp.get("code")) {
                if (null == resp.get("content") || "".equals(resp.get("content"))) {
                    reqData.setWeight(0.0);
                } else {
                    reqData.setWeight((Double) resp.get("content"));
                }
            }
            //执行推送
            if (reqData.getWeight() > 0) {
                gatewayRemoteManager.getDeviceReportService(device.getPushProtocol()).reportWeightData(reqData);
            }
        } catch (Exception e) {
            log.error("--------------地磅-HTTP协议执行异常----{}", e.getMessage());
        }
        return new BaseResp(500, "后台执行失败");
    }
}
src/main/java/com/fzzy/protocol/weightyh/MessageConsumer.java
@@ -82,7 +82,10 @@
        reqData.setProductId(device.getProductId());
        reqData.setDeviceName(device.getDeviceName());
        reqData.setWeight(weigh);
        gatewayRemoteManager.getDeviceReportService(device.getPushProtocol()).reportWeightData(reqData);
        if (weigh > 0) {
            gatewayRemoteManager.getDeviceReportService(device.getPushProtocol()).reportWeightData(reqData);
        }
    }
    /**