package com.ruoyi.sim.service.impl; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.sim.config.SimConfig; import jdk.jfr.Description; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.net.Socket; import java.util.HashMap; import static com.ruoyi.sim.constant.CommConst.OFFLINE_LIMIT; import static com.ruoyi.sim.constant.CommConst.SOCKET_TIME_OUT; @Service @Deprecated public class SocketOldService { private static final Logger l = LoggerFactory.getLogger(SocketOldService.class); /** * 缓存的Socket连接。 */ private Socket cachedSocket = null; @Autowired private SimConfig config; public Socket getCachedSocket() { return cachedSocket; } public void setCachedSocket(Socket cachedSocket) { this.cachedSocket = cachedSocket; } /** * openSocket * * @return */ public AjaxResult openSocket() { // check if (!config.isCommGlobal()) { l.warn("isCommGlobal == false [模拟器通信被禁用!]"); return AjaxResult.error("模拟器通信被禁用!"); } try { if (!isCachedSocketOk()) { l.info("openSocket cachedSocket is not ok!new socket!"); cachedSocket = new Socket(config.getRs485Ip(), config.getRs485Port()); cachedSocket.setSoTimeout(SOCKET_TIME_OUT); commFailCountClearAll(); } else { l.info("openSocket cachedSocket is ok!"); } } catch (IOException e) { e.printStackTrace(); return AjaxResult.error("开启连接失败!请检查物联网网关连接或配置。"); } finally { } return AjaxResult.success("开启连接成功!"); } /** * closeSocket * * @return */ public AjaxResult closeSocket() { if (!config.isCommGlobal()) { l.warn("isCommGlobal == false [模拟器通信被禁用!]"); return AjaxResult.error("模拟器通信被禁用!"); } try { if (cachedSocket != null) { // todo:判断shutdown cachedSocket.getInputStream().close(); cachedSocket.getOutputStream().close(); cachedSocket.close(); } else { l.info("cachedSocket == null!"); } } catch (IOException e) { e.printStackTrace(); return AjaxResult.success("关闭连接失败!请检查物联网网关连接或配置。"); } finally { cachedSocket = null; commFailCountClearAll(); } return AjaxResult.success("关闭连接成功!"); } /** * cachedSocket is ok * * @return */ public boolean isCachedSocketOk() { return (cachedSocket != null && cachedSocket.isConnected() && cachedSocket.isBound() && !cachedSocket.isClosed()); } private HashMap map = new HashMap<>(); /** * @param simId * @return true超过通信失败次数限制 */ public boolean commFailCountAdd1(long simId) { l.info("map.containsKey(simId) = {}", map.containsKey(simId)); if (map.containsKey(simId)) { map.put(simId, map.get(simId) + 1); } else { map.put(simId, 1); } return (map.get(simId) >= OFFLINE_LIMIT); } public void commFailCountClearOne(long simId) { map.remove(simId); } public void commFailCountClearAll() { map.clear(); } }