SocketService.java 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. package com.ruoyi.sim.service.impl;
  2. import com.ruoyi.common.core.domain.AjaxResult;
  3. import com.ruoyi.sim.config.SimConfig;
  4. import com.ruoyi.sim.config.SimDebugConfig;
  5. import com.ruoyi.sim.domain.Seat;
  6. import com.ruoyi.sim.domain.vo.SimSocketParamVo;
  7. import com.ruoyi.sim.domain.vo.SocketWrapCacheVo;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.security.core.parameters.P;
  12. import org.springframework.stereotype.Service;
  13. import java.io.IOException;
  14. import java.net.InetAddress;
  15. import java.net.Socket;
  16. import java.util.HashMap;
  17. import java.util.List;
  18. import java.util.concurrent.atomic.AtomicInteger;
  19. import static com.ruoyi.sim.constant.CommConst.SOCKET_TIME_OUT;
  20. /**
  21. * 1.所有Socket常开。
  22. * todo: connectedTimeMillis 时间。
  23. * <p>
  24. * 创建Socket重试,用failed开始方法去操作。
  25. */
  26. @Service
  27. public class SocketService {
  28. private static final Logger l = LoggerFactory.getLogger(SocketService.class);
  29. /**
  30. * 硬件孙总北京办公室,测试远程地址
  31. * <p>
  32. * 孙总办公室域名
  33. * nas.yichiot.com
  34. */
  35. public static final String IP_TEST = "221.218.215.73";
  36. public static final int PORT_TEST = 8899;
  37. private static final int LOCAL_PORT = 9000;
  38. private static final int INIT_SIZE = 32;
  39. /**
  40. * 6 hours
  41. * 1000L * 60 * 60 * 6
  42. * 1000L * 60 * 5
  43. */
  44. private static final long TIMEOUT_LIMIT = 1000L * 60 * 60 * 6;
  45. public static final int SOCKET_CONNECT_RETRY_COUNT_LIMIT = 4;
  46. /**
  47. * key: ip:port
  48. * value:
  49. */
  50. private static HashMap<String, SocketWrapCacheVo> cachedMap = new HashMap<>(INIT_SIZE);
  51. /**
  52. * 每个Socket都有。
  53. * 重试次数。
  54. * default 0.
  55. */
  56. private static HashMap<String, AtomicInteger> failedMap = new HashMap<>(INIT_SIZE);
  57. @Autowired
  58. private SimConfig config;
  59. @Autowired
  60. private SeatService seatService;
  61. /**
  62. * @param sspv
  63. * @return true:socket ok!
  64. */
  65. public boolean isOk(final SimSocketParamVo sspv) {
  66. final String key = sspv.toKey();
  67. if (cachedMap.containsKey(key) && cachedMap.get(key) != null) {
  68. Socket s = cachedMap.get(key).getSocket();
  69. if (s != null) {
  70. return (s.isConnected() &&
  71. s.isBound() &&
  72. !s.isClosed() &&
  73. !s.isInputShutdown() &&
  74. !s.isOutputShutdown()
  75. );
  76. }
  77. }
  78. return false;
  79. }
  80. public boolean isNotOk(final SimSocketParamVo sspv) {
  81. return !isOk(sspv);
  82. }
  83. /**
  84. * 暂时不考虑超时周期。
  85. * todo:
  86. *
  87. * @param ssv
  88. * @return
  89. */
  90. public boolean isTimeout(SimSocketParamVo ssv) {
  91. if (cachedMap.containsKey(ssv.toKey())) {
  92. Long cached = cachedMap.get(ssv.toKey()).getOkTimeMillis();
  93. if (cached == null || cached == 0L) {
  94. return true;
  95. }
  96. return System.currentTimeMillis() - cached <= TIMEOUT_LIMIT;
  97. }
  98. return true;
  99. }
  100. /**
  101. * @param sspv
  102. * @return
  103. */
  104. public AjaxResult openOne(final SimSocketParamVo sspv) {
  105. // check.
  106. if (!config.isCommGlobal()) {
  107. l.warn("isCommGlobal == {} [模拟器通信被禁用!]", config.isCommGlobal());
  108. return AjaxResult.error("模拟器通信被禁用!");
  109. }
  110. //
  111. try {
  112. if (isNotOk(sspv)) {
  113. final String key = sspv.toKey();
  114. l.info("openSocket cachedSocket is not ok!try new socket ip = {}:{}!", sspv.getIp(), sspv.getPort());
  115. closeOne(sspv, false);
  116. // 不指定本地端口实现。
  117. Socket s = new Socket(sspv.getIp(), sspv.getPort());
  118. // todo: LOCAL_PORT
  119. // Socket s = new Socket(sspv.getIp(), sspv.getPort(), InetAddress.getLocalHost(), SimDebugConfig.TCP_LOCAL_PORT);
  120. s.setSoTimeout(SOCKET_TIME_OUT);
  121. SocketWrapCacheVo value = new SocketWrapCacheVo(sspv.getIp(), sspv.getPort(), s, System.currentTimeMillis());
  122. // 新建Socket需要挂起 2s后再发指令。
  123. value.setPreviousSendSleep(2000L);
  124. cachedMap.put(key, value);
  125. // socket failed count reset.
  126. failedReset0(sspv);
  127. } else {
  128. l.info("openSocket cachedSocket cache ok!cached socket ip = {}:{}!", sspv.getIp(), sspv.getPort());
  129. }
  130. Seat seat = seatService.uniqueByRs485IpAndPort(sspv.getIp(), sspv.getPort());
  131. seat.setSeatRs485SocketState(Seat.SocketState.ONLINE);
  132. seatService.updateSeat(seat);
  133. return AjaxResult.success("Socket[" + sspv.getIp() + ":" + sspv.getPort() + "],创建成功!");
  134. } catch (IOException e) {
  135. l.error("IOException = {}", sspv);
  136. if (failedIsReachedMax(sspv, SOCKET_CONNECT_RETRY_COUNT_LIMIT)) {
  137. return AjaxResult.error("Socket[" + sspv.getIp() + ":" + sspv.getPort() + "],重试[" + failedGet(sspv) + "]次,创建失败!");
  138. } else {
  139. failedPlus1(sspv);
  140. AjaxResult ar = openOne(sspv);
  141. if (ar.isSuccess()) {
  142. return ar;
  143. } else {
  144. return AjaxResult.error("Socket[" + sspv.getIp() + ":" + sspv.getPort() + "],进行重试,创建失败!");
  145. }
  146. }
  147. }
  148. }
  149. public AjaxResult tryOpenOne(final SimSocketParamVo sspv) {
  150. if (!config.isCommGlobal()) {
  151. l.warn("isCommGlobal == {} [模拟器通信被禁用!]", config.isCommGlobal());
  152. return AjaxResult.error("模拟器通信被禁用!");
  153. }
  154. return openOne(sspv);
  155. }
  156. /**
  157. * todo:部分返回Aj结果。
  158. *
  159. * @return
  160. */
  161. public AjaxResult tryOpenAll() {
  162. if (!config.isCommGlobal()) {
  163. l.warn("isCommGlobal == {} [模拟器通信被禁用!]", config.isCommGlobal());
  164. return AjaxResult.error("模拟器通信被禁用!");
  165. }
  166. List<Seat> allSeat = seatService.listAllEnable();
  167. for (Seat s : allSeat) {
  168. AjaxResult ar = openOne(s.toSimSocketParamVo());
  169. l.debug("AjaxResult = {}", ar);
  170. }
  171. return AjaxResult.success("所有Socket,创建成功!");
  172. }
  173. public AjaxResult closeOne(final SimSocketParamVo sspv, boolean failedReset) {
  174. if (!config.isCommGlobal()) {
  175. l.warn("isCommGlobal == {} [模拟器通信被禁用!]", config.isCommGlobal());
  176. return AjaxResult.error("模拟器通信被禁用!");
  177. }
  178. final String key = sspv.toKey();
  179. try {
  180. if (cachedMap.containsKey(key)) {
  181. Socket s = cachedMap.get(key).getSocket();
  182. s.getInputStream().close();
  183. s.shutdownInput();
  184. s.getOutputStream().close();
  185. s.shutdownOutput();
  186. s.close();
  187. }
  188. } catch (IOException e) {
  189. e.printStackTrace();
  190. } finally {
  191. if (failedReset) {
  192. // failed count reset.
  193. failedReset0(sspv);
  194. }
  195. cachedMap.remove(key);
  196. return AjaxResult.success("关闭Socket成功!");
  197. }
  198. }
  199. public AjaxResult closeAll() {
  200. if (!config.isCommGlobal()) {
  201. l.warn("isCommGlobal == {} [模拟器通信被禁用!]", config.isCommGlobal());
  202. return AjaxResult.error("模拟器通信被禁用!");
  203. }
  204. final String msgOk = "关闭所有Socket成功!";
  205. List<Seat> allSeat = seatService.listAllEnable();
  206. for (Seat s : allSeat) {
  207. closeOne(new SimSocketParamVo(s.getSeatRs485Ip(), s.getSeatRs485Port()), true);
  208. }
  209. return AjaxResult.success(msgOk);
  210. }
  211. /**
  212. * @param seat
  213. * @return todo:null
  214. */
  215. public SocketWrapCacheVo get(final Seat seat) {
  216. if (seat == null) {
  217. throw new IllegalArgumentException("seat为空。");
  218. }
  219. return get(new SimSocketParamVo(seat.getSeatRs485Ip(), seat.getSeatRs485Port()));
  220. }
  221. /**
  222. * @param sspv
  223. * @return
  224. */
  225. public SocketWrapCacheVo get(final SimSocketParamVo sspv) {
  226. if (isNotOk(sspv)) {
  227. AjaxResult ar = openOne(sspv);
  228. if (ar.isError()) {
  229. // todo: isError
  230. }
  231. }
  232. return cachedMap.get(sspv.toKey());
  233. }
  234. /**
  235. * 初始化。todo:
  236. */
  237. public void clear(final SimSocketParamVo sspv) {
  238. }
  239. private static final int SOCKET_FAILED_COUNT_0 = 0;
  240. private static final int SOCKET_FAILED_COUNT_ADD_1 = 1;
  241. /**
  242. * @param sspv
  243. * @param limit include limit
  244. * @return
  245. */
  246. public boolean failedIsReachedMax(final SimSocketParamVo sspv, final int limit) {
  247. final String key = sspv.toKey();
  248. return (failedMap.containsKey(key) && failedMap.get(key).get() >= limit);
  249. }
  250. public int failedPlus1(final SimSocketParamVo sspv) {
  251. final String key = sspv.toKey();
  252. if (!failedMap.containsKey(key)) {
  253. failedMap.put(key, new AtomicInteger(SOCKET_FAILED_COUNT_ADD_1));
  254. } else {
  255. failedMap.get(key).addAndGet(SOCKET_FAILED_COUNT_ADD_1);
  256. }
  257. return failedMap.get(key).get();
  258. }
  259. public int failedGet(final SimSocketParamVo sspv) {
  260. final String key = sspv.toKey();
  261. if (failedMap.containsKey(key)) {
  262. return failedMap.get(key).get();
  263. } else {
  264. return SOCKET_FAILED_COUNT_0;
  265. }
  266. }
  267. public void failedReset0(final SimSocketParamVo sspv) {
  268. final String key = sspv.toKey();
  269. if (failedMap.containsKey(key)) {
  270. failedMap.get(key).set(SOCKET_FAILED_COUNT_0);
  271. } else {
  272. l.debug("not containsKey SimSocketParamVo sspv:" + sspv);
  273. }
  274. }
  275. }