CenterCommServerReceiver.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. package com.its.op.xnetudp.thread;
  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.its.op.dto.its.common.NotifyDto;
  5. import com.its.op.global.TbIfscManager;
  6. import com.its.op.global.TbLinkManager;
  7. import com.its.op.global.TbRoadManager;
  8. import com.its.op.websocket.ItsWebSocketMessage;
  9. import com.its.op.websocket.ItsWebSocketSessionManager;
  10. import com.its.op.xnetudp.protocol.CENTER_COMM_DEFINE;
  11. import com.its.op.xnetudp.protocol.CENTER_COMM_MESSAGE;
  12. import com.its.utils.ItsUtils;
  13. import lombok.RequiredArgsConstructor;
  14. import lombok.extern.slf4j.Slf4j;
  15. import org.springframework.scheduling.annotation.Async;
  16. import org.springframework.stereotype.Service;
  17. import org.springframework.web.socket.TextMessage;
  18. import javax.annotation.PostConstruct;
  19. import java.nio.ByteBuffer;
  20. import java.nio.ByteOrder;
  21. import java.nio.charset.StandardCharsets;
  22. @Slf4j
  23. @RequiredArgsConstructor
  24. @Service
  25. public class CenterCommServerReceiver {
  26. private final ItsWebSocketSessionManager itsWebSocketSessionManager;
  27. private final TbLinkManager linkManager;
  28. private final TbIfscManager ifscManager;
  29. private final TbRoadManager roadManager;
  30. private ObjectMapper mapper;
  31. @PostConstruct
  32. private void init() {
  33. this.mapper = new ObjectMapper();
  34. }
  35. @Async("centerCommExecutor")
  36. public void run(CENTER_COMM_MESSAGE data) {
  37. if (data == null) {
  38. log.error("@@@ UDP Data Receive: CenterCommServerReceiver: RECV Data Packet NULL");
  39. return;
  40. }
  41. log.info("@@@ -UDP Data Receive: CenterCommServerReceiver: Sender[{}], OpCode[{}], SenderIp[{}]", String.format("0x%02X", data.getSendId()), String.format("0x%02X", data.getOpCode()), data.getSenderIp());
  42. if (CENTER_COMM_DEFINE.INT_ID_TRAFFIC_SERVER == data.getSendId()) {
  43. if (CENTER_COMM_DEFINE.INT_OP_TRAFFIC_CHANGE == data.getOpCode()) {
  44. String prcsTm = ItsUtils.getCurrFiveMinString();
  45. String currTm = ItsUtils.getCurrFiveMinString();
  46. if (data.getLength() >= CENTER_COMM_DEFINE.INT_TRAFFIC_TIME_SIZE) {
  47. ByteBuffer byteBuffer = ByteBuffer.wrap(data.getBody());
  48. byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
  49. byte[] recvTm = new byte[CENTER_COMM_DEFINE.INT_TRAFFIC_TIME_SIZE];
  50. byteBuffer.get(recvTm);
  51. //prcsTm = new String(recvTm);
  52. prcsTm = new String(recvTm, StandardCharsets.UTF_8);
  53. if (data.getLength() >= (CENTER_COMM_DEFINE.INT_TRAFFIC_TIME_SIZE+CENTER_COMM_DEFINE.INT_TRAFFIC_TIME_SIZE)) {
  54. byteBuffer.get(recvTm);
  55. //currTm = new String(recvTm);
  56. currTm = new String(recvTm, StandardCharsets.UTF_8);
  57. }
  58. }
  59. log.info("@@@ RECV TRF Server Message: Processing Completed, {}/{}", prcsTm, currTm);
  60. // 소통정보 메모리 로딩
  61. this.linkManager.loadTraf(true);
  62. this.ifscManager.loadTraf(true);
  63. this.roadManager.loadTraf(true);
  64. NotifyDto notifyDto = NotifyDto.builder()
  65. .notify("traffic")
  66. .notifyTm(currTm)
  67. .notifyCount(0)
  68. .notifyMsg(prcsTm)
  69. .build();
  70. ItsWebSocketMessage socketMessage = new ItsWebSocketMessage("traffic", notifyDto);
  71. try {
  72. String jsonData = this.mapper.writeValueAsString(socketMessage);
  73. this.itsWebSocketSessionManager.sendBroadcastMessage(socketMessage.getCommand(), new TextMessage(jsonData));
  74. }
  75. catch(JsonProcessingException e){
  76. log.error("@@@ RECV TRF Server Message: Processing Completed, Exception: {}", notifyDto);
  77. }
  78. }
  79. return;
  80. }
  81. // VMS 통신 서버는 Sender, Receiver 위치가 바뀌었음. ==> 서버 수정했음.
  82. //if (CENTER_COMM_DEFINE.INT_ID_VMS_OPER == data.getSendId() && CENTER_COMM_DEFINE.INT_ID_VMS_SERVER == data.getRecvId()) {
  83. if (CENTER_COMM_DEFINE.INT_ID_VMS_SERVER == data.getSendId()) {
  84. //log.info("@@@ RECV VMS Server Message: OpCode: {}, Length: {} Bytes.", data.getOpCode(), data.getLength());
  85. //log.error("VMS PACKET: {}", SysUtils.byteArrayToHex(data.getBody()));
  86. if (data.getLength() > 0) {
  87. ByteBuffer byteBuffer = ByteBuffer.wrap(data.getBody());
  88. byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
  89. byte[] vmsId;
  90. byte count;
  91. byte opCode = data.getOpCode();
  92. //byte msgSeq = data.getMsgSeq();
  93. //log.info("OP CODE: {}, MsgSeq: {}", opCode, msgSeq);
  94. switch(opCode) {
  95. case CENTER_COMM_DEFINE.INT_OP_PG_STATE_RES:
  96. log.info("@@@ RECV VMS Server Message: INT_OP_PG_STATE_RES");
  97. break;
  98. case CENTER_COMM_DEFINE.INT_OP_VMS_FORM_SAVE:
  99. byte[] saveDt = new byte[CENTER_COMM_DEFINE.INT_VMS_MAX_DATETIME];
  100. byteBuffer.get(saveDt);
  101. // VMS 폼을 데이터베이스에 저장(다운로드 결과는 알수 없음)
  102. String command = "form-save";
  103. //String notifyTm = new String(saveDt);
  104. String notifyTm = new String(saveDt, StandardCharsets.UTF_8);
  105. log.info("@@@ RECV VMS Server Message: INT_OP_VMS_FORM_SAVE: SaveTime: {}", notifyTm);
  106. NotifyDto notifyDto1 = NotifyDto.builder()
  107. .notify(command)
  108. .notifyTm(notifyTm)
  109. .notifyCount(0)
  110. .notifyMsg(command)
  111. .build();
  112. ItsWebSocketMessage socketMessage1 = new ItsWebSocketMessage(command, notifyDto1);
  113. try {
  114. String jsonData = this.mapper.writeValueAsString(socketMessage1);
  115. this.itsWebSocketSessionManager.sendBroadcastMessage(socketMessage1.getCommand(), new TextMessage(jsonData));
  116. }
  117. catch(JsonProcessingException e){
  118. log.error("@@@ RECV VMS Server Message: CenterCommServerReceiver: INT_OP_VMS_FORM_SAVE, NotifyDto Json parsing Exception: {}", notifyDto1);
  119. }
  120. break;
  121. case CENTER_COMM_DEFINE.INT_OP_VMS_FORM_DOWNLOAD:
  122. count = byteBuffer.get();
  123. // VMS 폼 다운로드 결과 데이터베이스 저장
  124. log.info("@@@ RECV VMS Server Message: INT_OP_VMS_FORM_DOWNLOAD: Count: {} EA", count);
  125. NotifyDto notifyDto2 = NotifyDto.builder()
  126. .notify("form-download")
  127. .notifyTm(ItsUtils.getSysTime())
  128. .notifyCount(0)
  129. .notifyMsg("form-download")
  130. .build();
  131. ItsWebSocketMessage socketMessage2 = new ItsWebSocketMessage("form-download", notifyDto2);
  132. try {
  133. String jsonData = this.mapper.writeValueAsString(socketMessage2);
  134. this.itsWebSocketSessionManager.sendBroadcastMessage(socketMessage2.getCommand(), new TextMessage(jsonData));
  135. }
  136. catch(JsonProcessingException e){
  137. log.error("@@@ RECV VMS Server Message: CenterCommServerReceiver: INT_OP_VMS_FORM_DOWNLOAD, NotifyDto Json parsing Exception: {}", notifyDto2);
  138. }
  139. /* for (int ii = 0; ii < count; ii++) {
  140. vmsId = new byte[CENTER_COMM_DEFINE.INT_VMS_MAX_ID];
  141. byte[] downloadDt = new byte[CENTER_COMM_DEFINE.INT_VMS_MAX_DATETIME];
  142. byteBuffer.get(vmsId);
  143. byteBuffer.get(downloadDt);
  144. byte result = byteBuffer.get();
  145. for (int jj = 0; jj < vmsId.length; jj++) {
  146. if (vmsId[jj] < '0' || vmsId[jj] > '9') {
  147. vmsId[jj] = ' ';
  148. }
  149. }
  150. //log.error("{}, {}, {}, {}", ii+1, new String(vmsId).trim(), new String(downloadDt), result);
  151. }*/
  152. break;
  153. case CENTER_COMM_DEFINE.INT_OP_VMS_STATE_RES:
  154. short total = byteBuffer.getShort();
  155. short error = byteBuffer.getShort();
  156. short normal = byteBuffer.getShort();
  157. short module = byteBuffer.getShort();
  158. count = byteBuffer.get();
  159. log.info("@@@ RECV VMS Server Message: INT_OP_VMS_STATE_RES: total({}), error({}), normal({}), module({}), count: {} EA.", total, error, normal, module, count);
  160. // for (int ii = 0; ii < count; ii++) {
  161. // vmsId = new byte[CENTER_COMM_DEFINE.INT_VMS_MAX_ID];
  162. // byteBuffer.get(vmsId);
  163. // byte OprMode = byteBuffer.get(); /* VMS운영모드, 0:auto, 1:Fix */
  164. // byte Comm = byteBuffer.get(); /* 유선통신상태, 0:정상 1:장애 */
  165. // byte Wcomm = byteBuffer.get(); /* 무선통신상태, 0:정상 1:장애 */
  166. //
  167. // byte DoorStatus = byteBuffer.get(); /* 도어상태정보코드, 0:열림 1:닫힘 2:알수없음 */
  168. // byte ModulePowerStatus = byteBuffer.get(); /* 모듈전원상태정보코드, 0:켜짐 1:꺼짐 2:알수없음 */
  169. // short BodyTemp = byteBuffer.getShort(); /* 함체온도값(℃), 범위(-128~127) */
  170. // byte LuminanceStatus = byteBuffer.get(); /* 화면의 밝기값 (최대 휘도값을 100으로 했을 때의 백분율 값), 범위(0~100) */
  171. // byte FanStatus = byteBuffer.get(); /* Fan 동작상태정보코드, 0:켜짐, 1:꺼짐 2:알수없음 */
  172. // byte HeaterStatus = byteBuffer.get(); /* Heater 동작상태정보코드, 0:켜짐, 1:꺼짐 2:알수없음 */
  173. //
  174. // byte ExternalLightStatus = byteBuffer.get(); /* 선택 외부조명 동작상태정보코드 0:켜짐, 1:꺼짐, 2:자동(공단은 미사용) */
  175. // byte AlarmLightStatus = byteBuffer.get(); /* 선택 경광등 동작상태정보코드 0:켜짐, 1:꺼짐 */
  176. // byte SpeakerStatus = byteBuffer.get(); /* 선택 스피커 동작상태정보코드 0:켜짐, 1:꺼짐 */
  177. // byte[] ControllerCurrentTime = new byte[CENTER_COMM_DEFINE.INT_VMS_MAX_DATETIME];
  178. // byteBuffer.get(ControllerCurrentTime);
  179. // byte Voltage = byteBuffer.get(); /* 전압, 범위(0~255), 사용안함 */
  180. //
  181. // byte ModuleState = byteBuffer.get(); /* 모듈 상태, 0:정상 1:장애 2:알수없음 */
  182. // byte ModuleHorizontal = byteBuffer.get(); /* 가로 모듈수 */
  183. // byte ModuleVertical = byteBuffer.get(); /* 세로 모듈수 */
  184. // byte[] ModuleStatus = new byte[CENTER_COMM_DEFINE.INT_VMS_MAX_MODULE_BIT]; /* 모듈 개별 상태, 0:정상 1:장애 2:알수없음 */
  185. // byteBuffer.get(ModuleStatus);
  186. // byte PowerCount = byteBuffer.get(); /* 전원 갯수 */
  187. // byte[] PowerStatus = new byte[CENTER_COMM_DEFINE.INT_VMS_MAX_POWER_BIT]; /* 전원 개별 상태, 0:켜짐 1:꺼짐 2:알수없음 */
  188. // byteBuffer.get(PowerStatus);
  189. // byte[] Dummy = new byte[CENTER_COMM_DEFINE.INT_VMS_STATUE_DUMMY]; /* protocol dummy bytes */
  190. // byteBuffer.get(Dummy);
  191. // short ScheduledMessageOperatingTime = byteBuffer.getShort(); /* 필수 계획된 메시지의 동작시간(초) */
  192. // short ModuleOperatingTemperature = byteBuffer.getShort(); /* 필수 모듈 전원이 꺼지는 온도값(℃) */
  193. // short FanOperatingTemperature = byteBuffer.getShort(); /* 필수 Fan 동작 기준 온도값(℃) */
  194. // short HeaterOperatingTemperature = byteBuffer.getShort(); /* 필수 Heater 동작 기준 온도값(℃) */
  195. // short ExternalLightOperatingLuminance = byteBuffer.getShort(); /* 선택 외부전등 동작 기준 휘도값 */
  196. // short ModuleBasicFailureRate = byteBuffer.getShort(); /* 선택 모듈 장애율 (한 개의 모듈을 장애로 처리하기 위한 픽셀의 백분율값) */
  197. // short MaximumRetry = byteBuffer.getShort(); /* 선택 최대 재시도 횟수(회) */
  198. // short ResponseTimeOut = byteBuffer.getShort(); /* 선택 최대응답대기시간 (초) */
  199. // short BlinkingCycleTime = byteBuffer.getShort(); /* 선택 점멸시간 주기 ( 1/10초단위) */
  200. //
  201. // for (int jj = 0; jj < vmsId.length; jj++) {
  202. // if (vmsId[jj] < '0' || vmsId[jj] > '9') {
  203. // vmsId[jj] = ' ';
  204. // }
  205. // }
  206. // //log.info("{}, VmsId: {}, ModuleHor: {}, ModuleVer: {}", ii+1, new String(vmsId).trim(), ModuleHorizontal, ModuleVertical);
  207. // }
  208. break;
  209. default:
  210. log.info("RECV VMS Server Message: Other opCode: {}", opCode);
  211. break;
  212. }
  213. }
  214. return;
  215. }
  216. String reqIpAddr = data.getSenderIp();
  217. int reqPort = 4603;
  218. /*UnitSystService unitSystService = (UnitSystService) AppUtils.getBean(UnitSystService.class);
  219. ConcurrentHashMap<String, voUnitSyst> untiSystMap = unitSystService.getUntiSystMap();
  220. for (Map.Entry<String, voUnitSyst> e : untiSystMap.entrySet()) {
  221. if (reqIpAddr.equals(e.getValue().getSYST_IP_1())) {
  222. reqPort = e.getValue().getPRGM_PORT();
  223. break;
  224. }
  225. }*/
  226. /*byte opCode = data.getOpCode();
  227. if (opCode == CENTER_COMM_DEFINE.INT_OP_DSRC_CONTROL_REQ) {
  228. CENTER_DSRC_REQ_CONTROL req = new CENTER_DSRC_REQ_CONTROL(data.getBody());
  229. log.info("DSRC REQ CONTROL: [{}] [{},{},{},{}], {}",
  230. req.getCtlrNmbr(), req.getOperId(), req.getCmdTime(), req.getDeviceType(), req.getControlType(), Thread.currentThread().getName());
  231. int devcType = req.getDeviceType();
  232. int cntlType = req.getControlType();
  233. voDsrcCtlrCntl cntl = new voDsrcCtlrCntl();
  234. cntl.setReq(req);
  235. cntl.setReqIpAddress(data.getSender().getAddress().getHostAddress());
  236. cntl.setReqPort(data.getSender().getPort());
  237. cntl.setID(req.getCtlrNmbr());
  238. cntl.setCNTL_DT(SysUtils.getSysTime());
  239. cntl.setDEVC_TYPE(String.valueOf(devcType));
  240. cntl.setCNTL_TYPE(String.valueOf(cntlType));
  241. voDsrcCtlr dsrcCtlr = AppRepository.getInstance().getCtlrMap().get(String.valueOf(req.getCtlrNmbr()).toString());
  242. if (dsrcCtlr == null) {
  243. log.info("DSRC REQ CONTROL Unknown DSRC ID: [{}] [{},{},{},{}]",
  244. req.getCtlrNmbr(), req.getOperId(), req.getCmdTime(), req.getDeviceType(), req.getControlType());
  245. responseOperator(null, cntl, (byte)0x01);
  246. return;
  247. }
  248. if (dsrcCtlr.getChannel() == null || dsrcCtlr.getNetState() != NET.LOGINED) {
  249. // 여기 들어오면 안된다. 운영단말에서 통신이 정상인 것만 제어를 내릴수 있도록 한다.
  250. log.error("DSRC REQ CONTROL Not Connect: [{}] [{},{},{},{}]",
  251. req.getCtlrNmbr(), req.getOperId(), req.getCmdTime(), req.getDeviceType(), req.getControlType());
  252. responseOperator(dsrcCtlr, cntl, (byte)0x01);
  253. return;
  254. }
  255. // 제어요청 패킷을 만든다
  256. eControlDeviceId controlDeviceId = eControlDeviceId.getByValue(devcType);
  257. eControlCommand commandType = eControlCommand.getByValue(cntlType);
  258. if (controlDeviceId == null || commandType == null) {
  259. log.error("DSRC REQ CONTROL Value Error: [{}] [{},{},{},{}]",
  260. req.getCtlrNmbr(), req.getOperId(), req.getCmdTime(), req.getDeviceType(), req.getControlType());
  261. responseOperator(dsrcCtlr, cntl, (byte)0x01);
  262. return;
  263. }
  264. log.warn("{}, {}, controlDeviceId: {}, commandType: {}", dsrcCtlr.getID(), dsrcCtlr.getRSE_ID(), controlDeviceId.toString(), commandType.toString());
  265. boolean res = ControlDeviceService.getInstance().requestSubscriptionDeviceCommand(true, dsrcCtlr, dsrcCtlr.getChannel(), controlDeviceId.getValue(), commandType.getValue());
  266. if (res) {
  267. log.info("DSRC REQ CONTROL SEND OK: [{}] [{},{},{},{}]",
  268. req.getCtlrNmbr(), req.getOperId(), req.getCmdTime(), req.getDeviceType(), req.getControlType());
  269. responseOperator(dsrcCtlr, cntl, (byte)0x00);
  270. } else {
  271. log.error("DSRC REQ CONTROL SEND Error: [{}] [{},{},{},{}]",
  272. req.getCtlrNmbr(), req.getOperId(), req.getCmdTime(), req.getDeviceType(), req.getControlType());
  273. responseOperator(dsrcCtlr, cntl, (byte)0x01);
  274. }
  275. }
  276. else {
  277. log.error("UDP RECV UNKNOWN MESSAGE: {}", opCode);
  278. }*/
  279. }
  280. /*
  281. private int responseOperator(voDsrcCtlr obj, voDsrcCtlrCntl cntl, byte error) {
  282. CenterCommResponseService responseService = (CenterCommResponseService) AppUtils.getBean(CenterCommResponseService.class);
  283. return responseService.response(obj, cntl, error);
  284. }*/
  285. }