OCPP16MessageHandler.cs 14 KB

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