BasicMessageHandler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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("Validate 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. result.Success = false;
  160. result.Exception = ex;
  161. }
  162. return result;
  163. }
  164. #region 解析收到的訊息
  165. /// <summary>
  166. /// Parse data to OCPP Basic Message
  167. /// </summary>
  168. /// <param name="message"></param>
  169. /// <returns></returns>
  170. private BaseMessage Parse(string message)
  171. {
  172. try
  173. {
  174. if(message.StartsWith("[4,\""))
  175. {
  176. message= message.Replace('{', '"');
  177. message = message.Replace('}', '"');
  178. }
  179. var array = JsonConvert.DeserializeObject<JArray>(message);
  180. BaseMessage msg = null;
  181. switch ((int)array[INDEX_MESSAGEID])
  182. {
  183. case TYPENUMBER_CALL:
  184. {
  185. CallMessage call = new CallMessage();
  186. call.Action = array[INDEX_CALL_ACTION].ToString();
  187. call.Payload = array[INDEX_CALL_PAYLOAD].ToString().Replace("\r\n", "");
  188. msg = call;
  189. }
  190. break;
  191. case TYPENUMBER_CALLRESULT:
  192. {
  193. CallResultMessage callResult = new CallResultMessage();
  194. callResult.Payload = array[INDEX_CALLRESULT_PAYLOAD].ToString().Replace("\r\n", "");
  195. msg = callResult;
  196. }
  197. break;
  198. case TYPENUMBER_CALLERROR:
  199. {
  200. CallErrorMessage callError = new CallErrorMessage();
  201. callError.ErrorCode = array[INDEX_CALLERROR_ERRORCODE].ToString();
  202. callError.ErrorDescription = array[INDEX_CALLERROR_DESCRIPTION].ToString();
  203. callError.ErrorDetails = array[INDEX_CALLERROR_PAYLOAD].ToString().Replace("\r\n", "");
  204. msg = callError;
  205. }
  206. break;
  207. default:
  208. throw new Exception("Message Type notSupported");
  209. }
  210. msg.Id = array[INDEX_UNIQUEID].ToString();
  211. return msg;
  212. }
  213. catch (Exception ex)
  214. {
  215. throw new Exception(string.Format("Error=>Communicator.Parse: {0}", ex.ToString()));
  216. }
  217. }
  218. private BasicMessageResult UnPackPayloadbyCall(string action, string payload)
  219. {
  220. BasicMessageResult result = new BasicMessageResult();
  221. try
  222. {
  223. Feature feature = null;
  224. foreach (var profile in profiles)
  225. {
  226. feature = profile.GetFeaturebyAction(action);
  227. if (feature == null)
  228. {
  229. continue;
  230. }
  231. else
  232. {
  233. break;
  234. }
  235. }
  236. result.Request = JsonConvert.DeserializeObject(payload, feature.GetRequestType()) as IRequest;
  237. }
  238. catch (Exception ex)
  239. {
  240. result.Exception = ex;
  241. logger.Error(string.Format("[{0}]UnPackPayloadbyCall Ex: {1}", action, ex.Message), "UnPack");
  242. }
  243. return result;
  244. }
  245. private BasicMessageResult UnPackPayloadbyCallResult(Queue requestQueue, string uniqueId, string payload)
  246. {
  247. BasicMessageResult result = new BasicMessageResult();
  248. try
  249. {
  250. IRequest request = requestQueue.RestoreRequest(uniqueId);
  251. Feature feature = null;
  252. foreach (var profile in profiles)
  253. {
  254. feature = profile.GetFeaturebyType(request.GetType());
  255. if (feature == null)
  256. {
  257. continue;
  258. }
  259. else
  260. {
  261. break;
  262. }
  263. }
  264. IConfirmation confrim = JsonConvert.DeserializeObject(payload, feature.GetConfirmationType()) as IConfirmation;
  265. confrim.SetRequest(request);
  266. result.Confirmation = confrim;
  267. }
  268. catch (Exception ex)
  269. {
  270. result.Exception = ex;
  271. logger.Error(string.Format("UnPackPayloadbyCallResult Data:[{0},{1}] Ex: {2}", uniqueId, payload, ex.ToString()), "UnPack");
  272. }
  273. return result;
  274. }
  275. private IRequest UnPackPayloadbyCallError(Queue requestQueue, string uniqueId)
  276. {
  277. IRequest sentMsg = requestQueue.RestoreRequest(uniqueId);
  278. return sentMsg;
  279. }
  280. #endregion
  281. internal string GenerateCallError(string uniqueId, string errorCode, string errorDescription)
  282. {
  283. string msg = string.Format(CALLERROR_FORMAT, uniqueId, errorCode, errorDescription, "{}");
  284. return msg;
  285. }
  286. internal string GenerateConfirmation(string uniqueId, IConfirmation confirmation)
  287. {
  288. string msg = string.Empty;
  289. if (confirmation != null && confirmation.Validate())
  290. {
  291. msg = string.Format(CALLRESULT_FORMAT, uniqueId, JsonConvert.SerializeObject(confirmation, new JsonSerializerSettings() { NullValueHandling= NullValueHandling.Ignore, Formatting = Formatting.None }));
  292. }
  293. else
  294. {
  295. logger.Error(string.Format("confirmation is null or InVaild in GenerateConfirmation Method"), "Warning");
  296. }
  297. return msg;
  298. }
  299. internal string GenerateRequest(string uniqueId, string action, IRequest request)
  300. {
  301. string msg = string.Empty;
  302. if (request != null && request.Validate())
  303. {
  304. msg = string.Format(CALL_FORMAT, uniqueId, action, JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }));
  305. }
  306. else
  307. {
  308. logger.Error(string.Format("confirmation is null or InVaild in GenerateRequest Method"), "Warning");
  309. }
  310. return msg;
  311. }
  312. }
  313. }