FirmwareBundleUploadProcedure.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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");
  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. LogPair.Add($"FirmwareUpload", "0");
  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. LogPair.Add($"FirmwareUpload", "0");
  135. }
  136. Logger.Print("Firmware Upload Complete", isError: false);
  137. LogPair.Add($"FirmwareUpload", "1");
  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. var request = new RestSharp.RestRequest("upgrade_iso_action.php", RestSharp.Method.POST);
  161. request.AlwaysMultipartFormData = true;
  162. request.AddHeader("Content-Type", "multipart/form-data");
  163. request.AddParameter("fw_tag", "iso");
  164. foreach (var file in updateList)
  165. {
  166. request.AddFile("files[]", file.FirmwareFileName);
  167. }
  168. RestSharp.IRestResponse response = await restClient.ExecuteAsync(request);
  169. if (response.IsSuccessful)
  170. {
  171. LogWriter.Report(LogEvent.FirmwareUpload,"success");
  172. return true;
  173. }
  174. else
  175. {
  176. LogWriter.Report(LogEvent.FirmwareUpload, "fail");
  177. return false;
  178. }
  179. }
  180. public async Task<byte[]> UploadFilesRestSharp(string address, IEnumerable<string> files, NameValueCollection values)
  181. {
  182. var restClient = new RestSharp.RestClient(address);
  183. var request = new RestSharp.RestRequest(RestSharp.Method.POST);
  184. request.AlwaysMultipartFormData = true;
  185. request.AddHeader("Content-Type", "multipart/form-data");
  186. request.AddParameter("fw_tag", "iso");
  187. foreach (var file in files)
  188. {
  189. request.AddFile("files[]", file);
  190. }
  191. RestSharp.IRestResponse response = restClient.Execute(request);
  192. if(response.IsSuccessful)
  193. {
  194. }
  195. return response.RawBytes;
  196. }
  197. public async Task<byte[]> UploadFiles(string address, IEnumerable<UploadFile> files, NameValueCollection values)
  198. {
  199. var request = (HttpWebRequest)HttpWebRequest.Create(address);
  200. request.Timeout = 2 * 60 * 1000;
  201. request.KeepAlive = true;
  202. request.Accept = "*/*";
  203. request.Method = "POST";
  204. request.Referer = address;
  205. request.Expect = "";
  206. var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
  207. request.ContentType = "multipart/form-data; boundary=" + boundary;
  208. boundary = "--" + boundary;
  209. string sendString = "";
  210. using (var requestStream = request.GetRequestStream())
  211. {
  212. // Write the values
  213. foreach (string name in values.Keys)
  214. {
  215. var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
  216. requestStream.Write(buffer, 0, buffer.Length);
  217. buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"{1}{1}", name, Environment.NewLine));
  218. requestStream.Write(buffer, 0, buffer.Length);
  219. buffer = Encoding.ASCII.GetBytes(values[name] + Environment.NewLine);
  220. requestStream.Write(buffer, 0, buffer.Length);
  221. }
  222. // Write the files
  223. foreach (var file in files)
  224. {
  225. var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
  226. requestStream.Write(buffer, 0, buffer.Length);
  227. buffer = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", file.Name, file.Filename, Environment.NewLine));
  228. requestStream.Write(buffer, 0, buffer.Length);
  229. var ctype = MimeMapping.GetMimeMapping(file.Filename);
  230. buffer = Encoding.ASCII.GetBytes(string.Format("Content-Type: {0}{1}{1}", MimeMapping.GetMimeMapping(file.Filename), Environment.NewLine));
  231. requestStream.Write(buffer, 0, buffer.Length);
  232. file.Stream.CopyTo(requestStream);
  233. buffer = Encoding.ASCII.GetBytes(Environment.NewLine);
  234. requestStream.Write(buffer, 0, buffer.Length);
  235. }
  236. var boundaryBuffer = Encoding.ASCII.GetBytes(boundary + "--");
  237. requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length);
  238. }
  239. using (var response = await request.GetResponseAsync())
  240. using (var responseStream = response.GetResponseStream())
  241. using (var stream = new MemoryStream())
  242. {
  243. responseStream.CopyTo(stream);
  244. return stream.ToArray();
  245. }
  246. }
  247. }
  248. }