OCPP16MessageHandler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using EVCB_OCPP.Packet.Features;
  2. using EVCB_OCPP.Packet.Messages;
  3. using EVCB_OCPP.Packet.Messages.Basic;
  4. using EVCB_OCPP.WSServer.Service.WsService;
  5. using Microsoft.Extensions.Logging;
  6. using Newtonsoft.Json;
  7. using Newtonsoft.Json.Linq;
  8. using OCPPServer.Protocol;
  9. using System;
  10. using System.Collections.Generic;
  11. namespace EVCB_OCPP.WSServer.Message
  12. {
  13. /// <summary>
  14. /// 實現 OCPP16 基本傳送規範,
  15. /// 1.訊息 基本格式,將訊息包裝成 Call 、CallResult、CallError 三種格式
  16. /// 2.OCPP 定義的傳送規則:交易相關的訊息必須依照時序性傳送,一個傳完才能接著送下一個(忽略規則 由Center System定義)
  17. /// </summary>
  18. internal class OCPP16MessageHandler
  19. {
  20. static protected ILogger logger;
  21. #region 傳送 or 解析訊息需要欄位
  22. private const int INDEX_MESSAGEID = 0;
  23. private const int INDEX_UNIQUEID = 1;
  24. internal const int TYPENUMBER_CALL = 2;
  25. private const int INDEX_CALL_ACTION = 2;
  26. private const int INDEX_CALL_PAYLOAD = 3;
  27. internal const int TYPENUMBER_CALLRESULT = 3;
  28. private const int INDEX_CALLRESULT_PAYLOAD = 2;
  29. internal const int TYPENUMBER_CALLERROR = 4;
  30. private const int INDEX_CALLERROR_ERRORCODE = 2;
  31. private const int INDEX_CALLERROR_DESCRIPTION = 3;
  32. private const int INDEX_CALLERROR_PAYLOAD = 4;
  33. private const string CALL_FORMAT = "[2,\"{0}\",\"{1}\",{2}]";
  34. private const string CALLRESULT_FORMAT = "[3,\"{0}\",{1}]";
  35. private const string CALLERROR_FORMAT = "[4,\"{0}\",\"{1}\",\"{2}\",{3}]";
  36. private const string DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
  37. private const string DATE_FORMAT_WITH_MS = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
  38. #endregion
  39. private List<Profile> profiles = new List<Profile>()
  40. {
  41. new CoreProfile(),
  42. new FirmwareManagementProfile(),
  43. new ReservationProfile(),
  44. new RemoteTriggerProfile(),
  45. new SmartChargingProfile(),
  46. new LocalAuthListManagementProfile(),
  47. new SecurityProfile()
  48. };
  49. /// <summary>
  50. /// 將收到的封包做基本的拆解分成 Call 、CallResult、CallError
  51. /// </summary>
  52. /// <param name="client"></param>
  53. /// <param name="data"></param>
  54. /// <returns></returns>
  55. internal MessageResult AnalysisReceiveData(WsClientData client, string data)
  56. {
  57. MessageResult result = new MessageResult();
  58. try
  59. {
  60. var msg = Parse(data);
  61. if (msg != null)
  62. {
  63. result.UUID = msg.Id;
  64. switch (msg.TypeId)
  65. {
  66. case TYPENUMBER_CALL:
  67. {
  68. //只有CallMessage 才有在RawData有Action
  69. BasicMessageResult baseResult = UnPackPayloadbyCall(msg.Action, msg.Payload.ToString());
  70. Actions action = Actions.None;
  71. Enum.TryParse<Actions>(msg.Action, out action);
  72. result.Action = msg.Action;
  73. if (baseResult.Request != null)
  74. {
  75. if (baseResult.Request.Validate())
  76. {
  77. result.Id = TYPENUMBER_CALL;
  78. result.Message = baseResult.Request;
  79. }
  80. else
  81. {
  82. string replyMsg = BasicMessageHandler.GenerateCallError(msg.Id, OCPPErrorCodes.OccurenceConstraintViolation.ToString(),
  83. OCPPErrorDescription.OccurenceConstraintViolation);
  84. result.Id = TYPENUMBER_CALL;
  85. result.Message = baseResult.Request;
  86. result.Success = false;
  87. result.CallErrorMsg = replyMsg;
  88. result.Exception = new Exception("Validation Failed");
  89. }
  90. }
  91. else
  92. {
  93. string replyMsg = BasicMessageHandler.GenerateCallError(msg.Id, OCPPErrorCodes.OccurenceConstraintViolation, OCPPErrorDescription.OccurenceConstraintViolation);
  94. result.Id = TYPENUMBER_CALL;
  95. result.Message = baseResult.Request;
  96. result.Success = false;
  97. result.CallErrorMsg = replyMsg;
  98. result.Exception = baseResult.Exception;
  99. }
  100. }
  101. break;
  102. case TYPENUMBER_CALLRESULT:
  103. {
  104. BasicMessageResult baseResult = UnPackPayloadbyCallResult(client.queue, msg.Id, msg.Payload.ToString());
  105. if (baseResult.Confirmation != null)
  106. {
  107. if (baseResult.Confirmation.Validate())
  108. {
  109. result.Id = TYPENUMBER_CALLRESULT;
  110. result.Message = baseResult.Confirmation;
  111. result.Action = baseResult.Confirmation.GetRequest().Action;
  112. //return data
  113. }
  114. else
  115. {
  116. string replyMsg = BasicMessageHandler.GenerateCallError(msg.Id, OCPPErrorCodes.OccurenceConstraintViolation.ToString(),
  117. OCPPErrorDescription.OccurenceConstraintViolation);
  118. result.Id = TYPENUMBER_CALLRESULT;
  119. result.Message = baseResult.Confirmation;
  120. result.Success = false;
  121. result.CallErrorMsg = replyMsg;
  122. result.Exception = new Exception("Validate Failed");
  123. }
  124. }
  125. else
  126. {
  127. string replyMsg = BasicMessageHandler.GenerateCallError(msg.Id, OCPPErrorCodes.OccurenceConstraintViolation.ToString(),
  128. OCPPErrorDescription.OccurenceConstraintViolation);
  129. result.Id = TYPENUMBER_CALLRESULT;
  130. result.Message = baseResult.Confirmation;
  131. result.Success = false;
  132. result.CallErrorMsg = replyMsg;
  133. result.Exception = baseResult.Exception;
  134. }
  135. }
  136. break;
  137. case TYPENUMBER_CALLERROR:
  138. {
  139. result.Id = TYPENUMBER_CALLERROR;
  140. var sentRequest = UnPackPayloadbyCallError(client.queue, msg.Id);
  141. if (sentRequest != null)
  142. {
  143. IRequest request = sentRequest as IRequest;
  144. result.Action = request.Action;
  145. result.Message = sentRequest;
  146. result.ReceivedErrorCode = string.Format("ErrorMsg {0}:{1}", ((CallErrorMessage)msg).ErrorCode, ((CallErrorMessage)msg).ErrorDescription);
  147. }
  148. }
  149. break;
  150. default:
  151. break;
  152. }
  153. // if (msg != null) Console.WriteLine(string.Format("Receieved Message : {0}", msg.ToString()));
  154. }
  155. }
  156. catch (Exception ex)
  157. {
  158. if (string.IsNullOrEmpty(result.UUID))
  159. {
  160. result.UUID = data.Substring(4, 39);
  161. result.UUID = result.UUID.Split(new string[] { "\"," }, StringSplitOptions.None)[0];
  162. }
  163. result.Success = false;
  164. result.Exception = ex;
  165. }
  166. return result;
  167. }
  168. #region 解析收到的訊息
  169. /// <summary>
  170. /// Parse data to OCPP Basic Message
  171. /// </summary>
  172. /// <param name="message"></param>
  173. /// <returns></returns>
  174. private BaseMessage Parse(string message)
  175. {
  176. try
  177. {
  178. if (message.StartsWith("[4,\""))
  179. {
  180. message = message.Replace('{', '"');
  181. message = message.Replace('}', '"');
  182. }
  183. var array = JsonConvert.DeserializeObject<JArray>(message);
  184. BaseMessage msg = null;
  185. switch ((int)array[INDEX_MESSAGEID])
  186. {
  187. case TYPENUMBER_CALL:
  188. {
  189. CallMessage call = new CallMessage();
  190. call.Action = array[INDEX_CALL_ACTION].ToString();
  191. call.Payload = array[INDEX_CALL_PAYLOAD].ToString().Replace("\r\n", "");
  192. msg = call;
  193. }
  194. break;
  195. case TYPENUMBER_CALLRESULT:
  196. {
  197. CallResultMessage callResult = new CallResultMessage();
  198. callResult.Payload = array[INDEX_CALLRESULT_PAYLOAD].ToString().Replace("\r\n", "");
  199. msg = callResult;
  200. }
  201. break;
  202. case TYPENUMBER_CALLERROR:
  203. {
  204. CallErrorMessage callError = new CallErrorMessage();
  205. callError.ErrorCode = array[INDEX_CALLERROR_ERRORCODE].ToString();
  206. callError.ErrorDescription = array[INDEX_CALLERROR_DESCRIPTION].ToString();
  207. callError.ErrorDetails = array[INDEX_CALLERROR_PAYLOAD].ToString().Replace("\r\n", "");
  208. msg = callError;
  209. }
  210. break;
  211. default:
  212. throw new Exception("Message Type notSupported");
  213. }
  214. msg.Id = array[INDEX_UNIQUEID].ToString();
  215. return msg;
  216. }
  217. catch (Exception ex)
  218. {
  219. throw new Exception(string.Format("Parse Error=> Problem: {0}", ex.Message));
  220. }
  221. }
  222. private BasicMessageResult UnPackPayloadbyCall(string action, string payload)
  223. {
  224. BasicMessageResult result = new BasicMessageResult();
  225. try
  226. {
  227. Feature feature = null;
  228. foreach (var profile in profiles)
  229. {
  230. feature = profile.GetFeaturebyAction(action);
  231. if (feature == null)
  232. {
  233. continue;
  234. }
  235. else
  236. {
  237. break;
  238. }
  239. }
  240. result.Request = JsonConvert.DeserializeObject(payload, feature.GetRequestType()) as IRequest;
  241. }
  242. catch (Exception ex)
  243. {
  244. result.Exception = ex;
  245. logger.LogError(string.Format("[{0}]UnPackPayloadbyCall Ex: {1}", action, ex.Message), "UnPack");
  246. }
  247. return result;
  248. }
  249. private BasicMessageResult UnPackPayloadbyCallResult(Queue requestQueue, string uniqueId, string payload)
  250. {
  251. int i = 1;
  252. BasicMessageResult result = new BasicMessageResult();
  253. try
  254. {
  255. i = -1 ;
  256. IRequest request = requestQueue.RestoreRequest(uniqueId);
  257. if (request == null)
  258. {
  259. result.Exception = new Exception("Can't find request");
  260. return result;
  261. }
  262. i = 2;
  263. Feature feature = null;
  264. foreach (var profile in profiles)
  265. {
  266. i = 3;
  267. feature = profile.GetFeaturebyType(request.GetType());
  268. i = 4;
  269. if (feature == null)
  270. {
  271. continue;
  272. }
  273. else
  274. {
  275. break;
  276. }
  277. }
  278. i = 5;
  279. IConfirmation confrim = JsonConvert.DeserializeObject(payload, feature.GetConfirmationType()) as IConfirmation;
  280. i = 6;
  281. confrim.SetRequest(request);
  282. i = 7;
  283. result.Confirmation = confrim;
  284. }
  285. catch (Exception ex)
  286. {
  287. result.Exception = ex;
  288. logger.LogError(string.Format(i+"UnPackPayloadbyCallResult Data:[{0},{1}] Ex: {2}", uniqueId, payload, ex.ToString()), "UnPack");
  289. }
  290. return result;
  291. }
  292. private IRequest UnPackPayloadbyCallError(Queue requestQueue, string uniqueId)
  293. {
  294. IRequest sentMsg = requestQueue.RestoreRequest(uniqueId);
  295. return sentMsg;
  296. }
  297. #endregion
  298. }
  299. }