EvHttpClient.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Net.Http.Headers;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Threading.Tasks;
  13. using System.Windows;
  14. namespace CsuWebApiLib
  15. {
  16. public class EvHttpClientResult
  17. {
  18. public bool IsSuccess { get; set; }
  19. public string Msg { get; set; }
  20. }
  21. public class EvAuthMsg
  22. {
  23. public string result { get; set; }
  24. public object message { get; set; }
  25. }
  26. public static class EvHttpClient
  27. {
  28. public static string Account { get; set; } = "admin";
  29. public static string Pass { get; set; } = "1231231238";
  30. //internal static string ServerIpAddress = "192.168.1.10";
  31. internal static string ServerUrl = "https://192.168.1.10";
  32. //internal static string ServerIpAddress = "172.18.13.84";
  33. //internal static string ServerUrl = "https://172.18.13.84";
  34. //updated EV
  35. //internal static string ServerIpAddress = "192.168.80.197";
  36. //internal static string ServerUrl = "https://192.168.80.197";
  37. //original EV
  38. //internal static string ServerIpAddress = "192.168.80.199";
  39. //internal static string ServerUrl = "https://192.168.80.199";
  40. public static void ResetServerIpAddress(string ipAddress = null)
  41. {
  42. if (string.IsNullOrEmpty(ipAddress))
  43. {
  44. ServerUrl = "https://192.168.1.10";
  45. return;
  46. }
  47. if (!ipAddress.StartsWith("http"))
  48. {
  49. ipAddress = $"https://{ipAddress}";
  50. }
  51. ServerUrl = ipAddress;
  52. return;
  53. }
  54. public static Task<EvHttpClientResult> GetQueryActionOpt1String()
  55. {
  56. string api = "get_query_action.php";
  57. Dictionary<string, string> param = new Dictionary<string, string>() {
  58. {"opt","1"}
  59. };
  60. return CallBase(api, param);
  61. }
  62. public static Task<EvHttpClientResult> GetQueryActionOpt2String()
  63. {
  64. string api = "get_query_action.php";
  65. Dictionary<string, string> param = new Dictionary<string, string>() {
  66. {"opt","2"}
  67. };
  68. return CallBase(api, param);
  69. }
  70. public static Task<EvHttpClientResult> GetQueryActionOpt3String()
  71. {
  72. string api = "get_query_action.php";
  73. Dictionary<string, string> param = new Dictionary<string, string>() {
  74. {"opt","3"}
  75. };
  76. return CallBase(api, param);
  77. }
  78. public static Task<EvHttpClientResult> GetQueryActionOpt4String()
  79. {
  80. string api = "get_query_action.php";
  81. Dictionary<string, string> param = new Dictionary<string, string>() {
  82. {"opt","4"}
  83. };
  84. return CallBase(api, param);
  85. }
  86. internal static Task<EvHttpClientResult> GetButtonStatusString()
  87. {
  88. string api = "get_button_action.php";
  89. Dictionary<string, string> param = new Dictionary<string, string>()
  90. {
  91. };
  92. return CallBase(api, param);
  93. }
  94. internal static Task<EvHttpClientResult> GetFactorySetResultString()
  95. {
  96. string api = "set_system_action.php";
  97. Dictionary<string, string> param = new Dictionary<string, string>();
  98. param.Add("FactoryConfiguration", "1");
  99. //param.Add("SystemId", "");
  100. //param.Add("SystemDateTime", "");
  101. //param.Add("PhaseLossPolicy", "");
  102. //param.Add("FactoryConfiguration", "1");
  103. //param.Add("AuthorisationMode", "");
  104. //param.Add("isAPP", "");
  105. //param.Add("isQRCode", "");
  106. //param.Add("isRFID", "");
  107. //param.Add("QRCodeMadeMode", "");
  108. //param.Add("QRCodeContent", "");
  109. //param.Add("Intensity", "");
  110. //param.Add("RfidCardNumEndian", "");
  111. //param.Add("PsuAcInputType", "");
  112. return CallBase(api, param);
  113. }
  114. public static Task<EvHttpClientResult> GetUploadfirmwareResultString(List<string> fileNames)
  115. {
  116. string api = "upgrade_iso_action.php";
  117. Dictionary<string, string> param = new Dictionary<string, string>(){
  118. {"fw_tag","iso"}
  119. };
  120. var httpContentList = new List<HttpContent>();
  121. foreach (var fileName in fileNames)
  122. {
  123. var bytes = File.ReadAllBytes(fileName);
  124. var fileContent = new ByteArrayContent(bytes);
  125. //FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  126. //var fileContent = new StreamContent(file);
  127. fileContent.Headers.ContentDisposition
  128. = new ContentDispositionHeaderValue("attachment")
  129. {
  130. FileName = Path.GetFileName(fileName),
  131. CreationDate = DateTime.Now,
  132. ModificationDate = DateTime.Now,
  133. ReadDate = DateTime.Now,
  134. Name = "files[]"
  135. };
  136. httpContentList.Add(fileContent);
  137. }
  138. return CallBase(api, param, customContents: httpContentList, timeOutSeconds: 3600);
  139. //return CallBase(api, param, firmwareNames: fileNames);
  140. }
  141. internal static Task<EvHttpClientResult> GetSignalUpdateFirmwareResultString()
  142. {
  143. string api = "upgrade_iso_action.php";
  144. Dictionary<string, string> param = new Dictionary<string, string>(){
  145. {"fw_tag","iso"},
  146. };
  147. var dummyFileCotent = new ByteArrayContent(new byte[0]);
  148. dummyFileCotent.Headers.ContentDisposition
  149. = new ContentDispositionHeaderValue("attachment")
  150. {
  151. FileName = "temp.txt",
  152. Size = 0,
  153. CreationDate = DateTime.Now,
  154. ModificationDate = DateTime.Now,
  155. ReadDate = DateTime.Now,
  156. Name = "files[]"
  157. };
  158. return CallBase(api, param, customContents: new List<HttpContent>() { dummyFileCotent });
  159. }
  160. public static Task<EvHttpClientResult> SetSystemAction(string key, string value)
  161. {
  162. string api = "set_system_action.php";
  163. Dictionary<string, string> param = new Dictionary<string, string>(){
  164. {key,value},
  165. };
  166. return CallBase(api, param, customContents: new List<HttpContent>() { });
  167. }
  168. internal static Task<EvHttpClientResult> SetNetworkAction(Dictionary<string, string> param)
  169. {
  170. string api = "set_network_action.php";
  171. //Dictionary<string, string> param = new Dictionary<string, string>(){
  172. // {key,value},
  173. //};
  174. return CallBase(api, param, customContents: new List<HttpContent>() { });
  175. }
  176. internal static Task<EvHttpClientResult> SetRestart()
  177. {
  178. string api = "set_restart_action.php";
  179. //Dictionary<string, string> param = new Dictionary<string, string>(){
  180. // {key,value},
  181. //};
  182. return CallBase(api, new Dictionary<string, string>(), customContents: new List<HttpContent>() { });
  183. }
  184. private static async Task<EvHttpClientResult> CallBase(
  185. string api,
  186. Dictionary<string, string> param,
  187. List<string> firmwareNames = null,
  188. List<HttpContent> customContents = null,
  189. int timeOutSeconds = 5)
  190. {
  191. //if (!await CallWithNewVersion(api, param, firmwareNames, customContents, timeOutSeconds))
  192. //{
  193. // CallWithOldVersion();
  194. //}
  195. try
  196. {
  197. var url = string.Format("{0}/{1}", ServerUrl, api);
  198. EvHttpClientLogger.Instance.Log(url);
  199. Dictionary<string, string> pams = new Dictionary<string, string>
  200. {
  201. { "account", Account },
  202. { "password", Pass }
  203. };
  204. foreach (var pam in param)
  205. {
  206. pams.Add(pam.Key, pam.Value);
  207. }
  208. var formContent = new MultipartFormDataContent();
  209. foreach (var pam in pams)
  210. {
  211. formContent.Add(new StringContent(pam.Value), pam.Key);
  212. }
  213. if (firmwareNames != null)
  214. {
  215. foreach (var fileName in firmwareNames)
  216. {
  217. formContent.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(fileName)), "file[]");
  218. }
  219. }
  220. if (customContents != null)
  221. {
  222. foreach (var content in customContents)
  223. {
  224. formContent.Add(content);
  225. }
  226. }
  227. HttpResponseMessage postResult;
  228. string result = null;
  229. var handler = new HttpClientHandler();
  230. handler.ClientCertificateOptions = ClientCertificateOption.Manual;
  231. handler.ServerCertificateCustomValidationCallback =
  232. (httpRequestMessage, cert, cetChain, policyErrors) =>
  233. {
  234. return true;
  235. };
  236. using (HttpClient evClient = new HttpClient(handler))
  237. {
  238. evClient.Timeout = TimeSpan.FromSeconds(timeOutSeconds);
  239. try
  240. {
  241. EvHttpClientLogger.Instance.Log("post with new version");
  242. postResult = await evClient.PostAsync(url, formContent);
  243. EvHttpClientLogger.Instance.Log(postResult.StatusCode.ToString());
  244. //MessageBox.Show("Rest Result:" + postResult.StatusCode);
  245. if (postResult == null || !postResult.IsSuccessStatusCode)
  246. {
  247. throw new Exception("Post fail");
  248. }
  249. result = await postResult.Content.ReadAsStringAsync();
  250. EvHttpClientLogger.Instance.Log(result);
  251. //MessageBox.Show("Rest Result:" + result);
  252. if (result.Contains("File is uploaded, please wait a moment to upgrade"))
  253. {
  254. return new EvHttpClientResult()
  255. {
  256. IsSuccess = true,
  257. Msg = result,
  258. };
  259. }
  260. if (result.Contains("Charger restarted successfully"))
  261. {
  262. return new EvHttpClientResult()
  263. {
  264. IsSuccess = true,
  265. Msg = result,
  266. };
  267. }
  268. var check = JsonConvert.DeserializeObject<EvAuthMsg>(result);
  269. if (check != null &&
  270. check.result != null &&
  271. check.result.ToLower() == "fail")
  272. {
  273. return new EvHttpClientResult()
  274. {
  275. IsSuccess = false,
  276. Msg = result,
  277. };
  278. }
  279. return new EvHttpClientResult()
  280. {
  281. IsSuccess = true,
  282. Msg = result,
  283. };
  284. }
  285. catch (Exception e)
  286. {
  287. //post fail
  288. EvHttpClientLogger.Instance.Log(e.Message);
  289. EvHttpClientLogger.Instance.Log(e.StackTrace);
  290. }
  291. }
  292. using (WebClientTimeout webClient = new WebClientTimeout())
  293. {
  294. EvHttpClientLogger.Instance.Log("post with old version");
  295. NameValueCollection parameters = new NameValueCollection();
  296. foreach (var inpam in param)
  297. {
  298. parameters.Add(inpam.Key, inpam.Value);
  299. }
  300. webClient.QueryString = parameters;
  301. using (Stream stream = webClient.OpenRead(url))
  302. // 使用 StreamReader 讀取 stream 內的字元
  303. using (StreamReader reader = new StreamReader(stream))
  304. {
  305. // 將 StreamReader 所讀到的字元轉為 string
  306. result = await reader.ReadToEndAsync();
  307. }
  308. EvHttpClientLogger.Instance.Log(result);
  309. var check = JsonConvert.DeserializeObject<EvAuthMsg>(result);
  310. if (check != null &&
  311. check.result != null &&
  312. check.result.ToLower() == "fail")
  313. {
  314. return new EvHttpClientResult()
  315. {
  316. IsSuccess = false,
  317. Msg = result,
  318. };
  319. }
  320. }
  321. return new EvHttpClientResult() { IsSuccess = true, Msg = result };
  322. }
  323. catch (Exception e)
  324. {
  325. return new EvHttpClientResult() { IsSuccess = false, Msg = e.Message }; ;
  326. }
  327. }
  328. private static async Task<EvHttpClientResult> CallWithNewVersion(string api, Dictionary<string, string> param, List<string> firmwareNames, List<HttpContent> customContents, int timeOutSeconds)
  329. {
  330. try
  331. {
  332. var url = string.Format("{0}/{1}", ServerUrl, api);
  333. EvHttpClientLogger.Instance.Log(url);
  334. Dictionary<string, string> pams = new Dictionary<string, string>
  335. {
  336. { "account", Account },
  337. { "password", Pass }
  338. };
  339. foreach (var pam in param)
  340. {
  341. pams.Add(pam.Key, pam.Value);
  342. }
  343. var formContent = new MultipartFormDataContent();
  344. foreach (var pam in pams)
  345. {
  346. formContent.Add(new StringContent(pam.Value), pam.Key);
  347. }
  348. if (firmwareNames != null)
  349. {
  350. foreach (var fileName in firmwareNames)
  351. {
  352. formContent.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(fileName)), "file[]");
  353. }
  354. }
  355. if (customContents != null)
  356. {
  357. foreach (var content in customContents)
  358. {
  359. formContent.Add(content);
  360. }
  361. }
  362. HttpResponseMessage postResult;
  363. string result = null;
  364. var handler = new HttpClientHandler();
  365. handler.ClientCertificateOptions = ClientCertificateOption.Manual;
  366. handler.ServerCertificateCustomValidationCallback =
  367. (httpRequestMessage, cert, cetChain, policyErrors) =>
  368. {
  369. return true;
  370. };
  371. using (HttpClient evClient = new HttpClient(handler))
  372. {
  373. evClient.Timeout = TimeSpan.FromSeconds(timeOutSeconds);
  374. try
  375. {
  376. EvHttpClientLogger.Instance.Log("post with new version");
  377. postResult = await evClient.PostAsync(url, formContent);
  378. EvHttpClientLogger.Instance.Log(postResult.StatusCode.ToString());
  379. //MessageBox.Show("Rest Result:" + postResult.StatusCode);
  380. if (postResult == null || !postResult.IsSuccessStatusCode)
  381. {
  382. throw new Exception("Post fail");
  383. }
  384. result = await postResult.Content.ReadAsStringAsync();
  385. EvHttpClientLogger.Instance.Log(result);
  386. //MessageBox.Show("Rest Result:" + result);
  387. if (result.Contains("File is uploaded, please wait a moment to upgrade"))
  388. {
  389. return new EvHttpClientResult()
  390. {
  391. IsSuccess = true,
  392. Msg = result,
  393. };
  394. }
  395. var check = JsonConvert.DeserializeObject<EvAuthMsg>(result);
  396. if (check != null &&
  397. check.result != null &&
  398. check.result.ToLower() == "fail")
  399. {
  400. return new EvHttpClientResult()
  401. {
  402. IsSuccess = false,
  403. Msg = result,
  404. };
  405. }
  406. return new EvHttpClientResult()
  407. {
  408. IsSuccess = true,
  409. Msg = result,
  410. };
  411. }
  412. catch (Exception e)
  413. {
  414. //post fail
  415. EvHttpClientLogger.Instance.Log(e.Message);
  416. EvHttpClientLogger.Instance.Log(e.StackTrace);
  417. }
  418. }
  419. using (WebClientTimeout webClient = new WebClientTimeout())
  420. {
  421. EvHttpClientLogger.Instance.Log("post with old version");
  422. NameValueCollection parameters = new NameValueCollection();
  423. foreach (var inpam in param)
  424. {
  425. parameters.Add(inpam.Key, inpam.Value);
  426. }
  427. webClient.QueryString = parameters;
  428. using (Stream stream = webClient.OpenRead(url))
  429. // 使用 StreamReader 讀取 stream 內的字元
  430. using (StreamReader reader = new StreamReader(stream))
  431. {
  432. // 將 StreamReader 所讀到的字元轉為 string
  433. result = await reader.ReadToEndAsync();
  434. }
  435. EvHttpClientLogger.Instance.Log(result);
  436. var check = JsonConvert.DeserializeObject<EvAuthMsg>(result);
  437. if (check != null &&
  438. check.result != null &&
  439. check.result.ToLower() == "fail")
  440. {
  441. return new EvHttpClientResult()
  442. {
  443. IsSuccess = false,
  444. Msg = result,
  445. };
  446. }
  447. }
  448. return new EvHttpClientResult() { IsSuccess = true, Msg = result };
  449. }
  450. catch (Exception e)
  451. {
  452. return new EvHttpClientResult() { IsSuccess = false, Msg = e.Message }; ;
  453. }
  454. }
  455. }
  456. }