BasicMessageHandler.cs 15 KB

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