FirmwareBundleUploadProcedure.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using AwInitilizer.Model;
  7. using AwInitilizer.Assist;
  8. using System.Collections.Specialized;
  9. using System.Globalization;
  10. using System.Net;
  11. using System.Web;
  12. using System.IO;
  13. namespace AwInitilizer.Procedure.FirmwareBundleUpload
  14. {
  15. public enum ErrorType
  16. {
  17. None,
  18. StartWaitTimeout,
  19. UploadFailed,
  20. }
  21. public enum LogEvent
  22. {
  23. UploadStartWait,
  24. FirmwareUpload
  25. }
  26. public class FirmwareBundleUploadProcedure : ProcedureBase
  27. {
  28. public ErrorType Error { get; set; } = ErrorType.None;
  29. private ProcedureLog.LogWriter<FirmwareBundleUploadProcedure, LogEvent> LogWriter;
  30. private readonly static Dictionary<LogEvent, string> ReportDict = new Dictionary<LogEvent, string>()
  31. {
  32. { LogEvent.UploadStartWait, "UploadStartWait" },
  33. { LogEvent.FirmwareUpload, "FirmwareUpload" },
  34. };
  35. private readonly static Dictionary<LogEvent, string> LogDict = new Dictionary<LogEvent, string>()
  36. {
  37. { LogEvent.UploadStartWait, "Wait restart {0}" },
  38. { LogEvent.FirmwareUpload, "Firmware Upload {0}" },
  39. };
  40. public FirmwareBundleUploadProcedure() : base()
  41. {
  42. Name = string.Format("Firmware Upload");
  43. Content = string.Format("Upload all Firemware");
  44. LogWriter = new ProcedureLog.LogWriter<FirmwareBundleUploadProcedure, LogEvent>(this)
  45. {
  46. ReportPair = ReportDict,
  47. LogPair = LogDict
  48. };
  49. }
  50. internal override async Task<bool> Run()
  51. {
  52. bool response = false;
  53. int pollingCnt = 0;
  54. for (pollingCnt = 0; pollingCnt < 56; pollingCnt++)
  55. {
  56. await Task.Delay(TimeSpan.FromSeconds(15));
  57. response = await CheckGetQuertyAction();
  58. if (response)
  59. break;
  60. }
  61. LogWriter.Log(string.Format("EVSE connet elapsed minute(s) : {0}, Expect:<14", pollingCnt * 0.25));
  62. //timeout
  63. if (pollingCnt >= 56)
  64. {
  65. LogWriter.Report(LogEvent.UploadStartWait, "fail", isError: true);
  66. Error = ErrorType.StartWaitTimeout;
  67. return false;
  68. }
  69. LogWriter.Report(LogEvent.UploadStartWait, "success");
  70. //upload firmware
  71. bool result = false;
  72. for (int tryCnt = 0; tryCnt < 10; tryCnt++)
  73. {
  74. result = await UploadWithRestSharp();
  75. if (result)
  76. break;
  77. else
  78. await Task.Delay(1000);
  79. }
  80. if(!result)
  81. {
  82. Error = ErrorType.UploadFailed;
  83. return false;
  84. }
  85. return result;
  86. }
  87. private async Task<bool> UploadWithHttpWebRequest()
  88. {
  89. var updateList = UpdateData.FirmwareUpdateModels;
  90. //open all file stream
  91. //List<FileStream> firmwareFileStream = new List<FileStream>();
  92. List<UploadFile> UploadFileList = new List<UploadFile>();
  93. try
  94. {
  95. for (int modelIndex = 0; modelIndex < updateList.Count; modelIndex++) //foreach (var model in updateList)
  96. {
  97. var model = updateList[modelIndex];
  98. var stream = File.Open(model.FirmwareFileName, FileMode.Open);
  99. var uploadFile = new UploadFile()
  100. {
  101. Name = string.Format("files[]", modelIndex + 1),
  102. Filename = Path.GetFileName(model.FirmwareFileName),
  103. Stream = stream
  104. };
  105. UploadFileList.Add(uploadFile);
  106. }
  107. }
  108. catch (Exception e)
  109. {
  110. InfoLog += $"create file stream failed";
  111. MesLogData.Add($"FirmwareUpload", "0" , false);
  112. return false;
  113. }
  114. Logger.Print("Uploading Firmware", isError: false);
  115. //upload
  116. try
  117. {
  118. var uploadResult = await UploadFiles(
  119. $"https://{ServerIpAddress}/upgrade_iso_action.php",
  120. files: UploadFileList,
  121. new NameValueCollection() {
  122. {"fw_tag","iso" }
  123. }
  124. );
  125. var responseStr = Encoding.ASCII.GetString(uploadResult).ToLower();
  126. InfoLog += $"get firmware update response {responseStr}\n";
  127. if (responseStr.Contains("file is uploaded"))
  128. return true;
  129. return false;
  130. }
  131. catch
  132. {
  133. InfoLog += $"file upload failed";
  134. MesLogData.Add($"FirmwareUpload", "0", false);
  135. }
  136. Logger.Print("Firmware Upload Complete", isError: false);
  137. MesLogData.Add($"FirmwareUpload", "1" , true);
  138. //release all
  139. foreach (var uploadFile in UploadFileList)
  140. {
  141. if (uploadFile != null && uploadFile.Stream != null)
  142. {
  143. Logger.Print($"Close {uploadFile.Filename}", isError: false);
  144. try
  145. {
  146. uploadFile.Stream.Close();
  147. uploadFile.Stream.Dispose();
  148. }
  149. catch
  150. {
  151. }
  152. }
  153. }
  154. return true;
  155. }
  156. private async Task<bool> UploadWithRestSharp()
  157. {
  158. var updateList = UpdateData.FirmwareUpdateModels;
  159. var restClient = new RestSharp.RestClient($"https://{ServerIpAddress}");
  160. restClient.ConfigureWebRequest((r) => { r.KeepAlive = true; });
  161. var request = new RestSharp.RestRequest("upgrade_iso_action.php", RestSharp.Method.POST);
  162. request.AlwaysMultipartFormData = true;
  163. request.AddHeader("Content-Type", "multipart/form-data");
  164. request.AddParameter("fw_tag", "iso");
  165. foreach (var file in updateList)
  166. {
  167. request.AddFile("files[]", file.FirmwareFileName);
  168. }
  169. RestSharp.IRestResponse response = await restClient.ExecuteAsync(request);
  170. if (response.IsSuccessful)
  171. {
  172. LogWriter.Report(LogEvent.FirmwareUpload,"success");
  173. return true;
  174. }
  175. else
  176. {
  177. LogWriter.Report(LogEvent.FirmwareUpload, "fail", isError: true);
  178. if (response.ErrorException!= null)
  179. {
  180. LogWriter.Log(response.ErrorException.Message,isError:true,isDebugLog: true);
  181. if (response.ErrorException.InnerException != null)
  182. {
  183. LogWriter.Log(response.ErrorException.InnerException.Message, isError: true, isDebugLog: true);
  184. }
  185. LogWriter.Log(response.StatusCode.ToString(), isError: true, isDebugLog: true);
  186. }
  187. return false;
  188. }
  189. }
  190. public async Task<byte[]> UploadFilesRestSharp(string address, IEnumerable<string> files, NameValueCollection values)
  191. {
  192. var restClient = new RestSharp.RestClient(address);
  193. var request = new RestSharp.RestRequest(RestSharp.Method.POST);
  194. request.AlwaysMultipartFormData = true;
  195. request.AddHeader("Content-Type", "multipart/form-data");
  196. request.AddParameter("fw_tag", "iso");
  197. foreach (var file in files)
  198. {
  199. request.AddFile("files[]", file);
  200. }
  201. RestSharp.IRestResponse response = restClient.Execute(request);
  202. if(response.IsSuccessful)
  203. {
  204. }
  205. return response.RawBytes;
  206. }
  207. public async Task<byte[]> UploadFiles(string address, IEnumerable<UploadFile> files, NameValueCollection values)
  208. {
  209. var request = (HttpWebRequest)HttpWebRequest.Create(address);
  210. request.Timeout = 2 * 60 * 1000;
  211. request.KeepAlive = true;
  212. request.Accept = "*/*";
  213. request.Method = "POST";
  214. request.Referer = address;
  215. request.Expect = "";
  216. var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
  217. request.ContentType = "multipart/form-data; boundary=" + boundary;
  218. boundary = "--" + boundary;
  219. string sendString = "";
  220. using (var requestStream = request.GetRequestStream())
  221. {
  222. // Write the values
  223. foreach (string name in values.Keys)
  224. {
  225. var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
  226. requestStream.Write(buffer, 0, buffer.Length);
  227. buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"{1}{1}", name, Environment.NewLine));
  228. requestStream.Write(buffer, 0, buffer.Length);
  229. buffer = Encoding.ASCII.GetBytes(values[name] + Environment.NewLine);
  230. requestStream.Write(buffer, 0, buffer.Length);
  231. }
  232. // Write the files
  233. foreach (var file in files)
  234. {
  235. var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
  236. requestStream.Write(buffer, 0, buffer.Length);
  237. buffer = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", file.Name, file.Filename, Environment.NewLine));
  238. requestStream.Write(buffer, 0, buffer.Length);
  239. var ctype = MimeMapping.GetMimeMapping(file.Filename);
  240. buffer = Encoding.ASCII.GetBytes(string.Format("Content-Type: {0}{1}{1}", MimeMapping.GetMimeMapping(file.Filename), Environment.NewLine));
  241. requestStream.Write(buffer, 0, buffer.Length);
  242. file.Stream.CopyTo(requestStream);
  243. buffer = Encoding.ASCII.GetBytes(Environment.NewLine);
  244. requestStream.Write(buffer, 0, buffer.Length);
  245. }
  246. var boundaryBuffer = Encoding.ASCII.GetBytes(boundary + "--");
  247. requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length);
  248. }
  249. using (var response = await request.GetResponseAsync())
  250. using (var responseStream = response.GetResponseStream())
  251. using (var stream = new MemoryStream())
  252. {
  253. responseStream.CopyTo(stream);
  254. return stream.ToArray();
  255. }
  256. }
  257. }
  258. }