BasicMessageHandler.cs 15 KB

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