MainWindow.xaml.cs 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. using EVCB_OCPP.Domain;
  2. using EVCB_OCPP.Domain.Models.Database;
  3. using EVCB_OCPP.Packet.Features;
  4. using EVCB_OCPP.Packet.Messages;
  5. using EVCB_OCPP.Packet.Messages.Core;
  6. using Microsoft.Win32;
  7. using Newtonsoft.Json;
  8. using OCPPPackage.Profiles;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Configuration;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net;
  15. using System.Security.Cryptography;
  16. using System.Text;
  17. using System.Threading.Tasks;
  18. using System.Windows;
  19. using System.Windows.Controls;
  20. using System.Windows.Data;
  21. using System.Windows.Documents;
  22. using System.Windows.Input;
  23. using System.Windows.Media;
  24. using System.Windows.Media.Imaging;
  25. using System.Windows.Navigation;
  26. using System.Windows.Shapes;
  27. using System.Data.Entity;
  28. using EVCB_OCPP.Packet.Messages.RemoteTrigger;
  29. using EVCB_OCPP.Packet.Messages.SubTypes;
  30. using EVCB_OCPP.Packet.Messages.LocalAuthListManagement;
  31. using EVCB_OCPP.Packet.Messages.FirmwareManagement;
  32. using EVCB_OCPP.Packet.Messages.Reservation;
  33. using EVCB_OCPP.Packet.Messages.SmartCharging;
  34. using System.Threading;
  35. using System.Net.Http;
  36. namespace TestTool.RemoteTriggerAPP
  37. {
  38. /// <summary>
  39. /// MainWindow.xaml 的互動邏輯
  40. /// </summary>
  41. public partial class MainWindow : Window
  42. {
  43. string action = "";
  44. List<PublishVersion> publishes = new List<PublishVersion>();
  45. FTPClient UploadClient = new FTPClient(@"ftp://test.evsocket.phihong.com.cn", "testocpp", "testocpp");
  46. string chargingProfilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "chargingProfile.json");
  47. int selectedPublish = -1;
  48. public MainWindow()
  49. {
  50. InitializeComponent();
  51. UploadClient.OnUploadProgress += UploadClient_OnUploadProgress;
  52. }
  53. private void UxSubmitBtn_Click(object sender, RoutedEventArgs e)
  54. {
  55. switch (action)
  56. {
  57. #region Core Profile
  58. case "ChangeAvailability_Inoperative":
  59. {
  60. SetChangeAvailability_Inoperative();
  61. }
  62. break;
  63. case "ChangeAvailability_Operative":
  64. {
  65. SetChangeAvailability_Operative();
  66. }
  67. break;
  68. case "GetConfiguration":
  69. {
  70. if (uxConfigKeyTb.Text == "")
  71. {
  72. SetGetConfiguration_ALL();
  73. }
  74. else
  75. {
  76. SetGetConfiguration();
  77. }
  78. }
  79. break;
  80. case "ChangeConfiguration":
  81. {
  82. SetChangeConfiguration();
  83. }
  84. break;
  85. case "ClearCache":
  86. {
  87. SetClearCache();
  88. }
  89. break;
  90. case "RemoteStartTransaction":
  91. {
  92. SetRemoteStartTransaction();
  93. }
  94. break;
  95. case "RemoteStartTransaction_ChargingProfile":
  96. {
  97. var chargingProfile = VerifyChargingProfile(chargingProfilePath);
  98. if (chargingProfile != null)
  99. {
  100. SetRemoteStartTransaction(chargingProfile);
  101. }
  102. else
  103. {
  104. uxMsgTb.Text = "Please check chargingProfile.json exist in " + AppDomain.CurrentDomain.BaseDirectory;
  105. }
  106. }
  107. break;
  108. case "RemoteStopTransaction":
  109. {
  110. SetRemoteStopTransaction();
  111. }
  112. break;
  113. case "HardReset":
  114. {
  115. SetHardReset();
  116. }
  117. break;
  118. case "SoftReset":
  119. {
  120. SetSoftReset();
  121. }
  122. break;
  123. case "UnlockConnector":
  124. {
  125. SetUnlockConnector();
  126. }
  127. break;
  128. #endregion
  129. #region Local Authorization
  130. case "GetLocalListVersion":
  131. {
  132. GetLocalListVersion();
  133. }
  134. break;
  135. case "SendLocalAuthorizationList_Full":
  136. {
  137. SendLocalAuthorizationList(true);
  138. }
  139. break;
  140. case "SendLocalAuthorizationList_Diff":
  141. {
  142. SendLocalAuthorizationList(false);
  143. }
  144. break;
  145. #endregion
  146. case "GetDiagnostics_FTP":
  147. {
  148. GetDiagnostics(true);
  149. }
  150. break;
  151. case "GetDiagnostics_HTTP":
  152. {
  153. GetDiagnostics(false);
  154. }
  155. break;
  156. case "ReserveNow":
  157. {
  158. ReserveNow();
  159. }
  160. break;
  161. case "CancelReservation":
  162. {
  163. CancelReservation();
  164. }
  165. break;
  166. case "ClearChargingProfile":
  167. {
  168. ClearChargingProfile();
  169. }
  170. break;
  171. case "GetCompositeSchedule":
  172. {
  173. GetCompositeSchedule();
  174. }
  175. break;
  176. case "SetChargingProfile":
  177. {
  178. var chargingProfile = VerifyChargingProfile(chargingProfilePath);
  179. if (chargingProfile != null)
  180. {
  181. SetChargingProfile(chargingProfile);
  182. }
  183. else
  184. {
  185. uxMsgTb.Text = "Please check chargingProfile.json exist in " + AppDomain.CurrentDomain.BaseDirectory;
  186. }
  187. }
  188. break;
  189. #region Trigger Profile
  190. case "TriggerMessage_BootNotification":
  191. case "TriggerMessage_DiagnosticsStatusNotification":
  192. case "TriggerMessage_FirmwareStatusNotification":
  193. case "TriggerMessage_Heartbeat":
  194. case "TriggerMessage_MeterValues":
  195. case "TriggerMessage_StatusNotification":
  196. {
  197. SetRemoteTrigger(action);
  198. }
  199. break;
  200. #endregion
  201. default:
  202. break;
  203. }
  204. }
  205. private SetChargingProfileRequest VerifyChargingProfile(string path)
  206. {
  207. SetChargingProfileRequest request = null;
  208. if (!File.Exists(path)) return request;
  209. try
  210. {
  211. request = JsonConvert.DeserializeObject<SetChargingProfileRequest>(File.ReadAllText(path));
  212. }
  213. catch
  214. {
  215. }
  216. return request;
  217. }
  218. private void SetChargingProfile(SetChargingProfileRequest csProfile)
  219. {
  220. try
  221. {
  222. var uuid = Guid.NewGuid().ToString();
  223. WritetoDB(uuid, csProfile);
  224. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  225. }
  226. catch (Exception ex)
  227. {
  228. MessageBox.Show(ex.ToString());
  229. }
  230. }
  231. private void GetCompositeSchedule()
  232. {
  233. try
  234. {
  235. var uuid = Guid.NewGuid().ToString();
  236. var request = new GetCompositeScheduleRequest()
  237. {
  238. connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
  239. duration = 300
  240. };
  241. WritetoDB(uuid, request);
  242. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  243. }
  244. catch (Exception ex)
  245. {
  246. MessageBox.Show(ex.ToString());
  247. }
  248. }
  249. private void ClearChargingProfile()
  250. {
  251. try
  252. {
  253. var uuid = Guid.NewGuid().ToString();
  254. var request = new ClearChargingProfileRequest()
  255. {
  256. connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
  257. };
  258. WritetoDB(uuid, request);
  259. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  260. }
  261. catch (Exception ex)
  262. {
  263. MessageBox.Show(ex.ToString());
  264. }
  265. }
  266. private void CancelReservation()
  267. {
  268. try
  269. {
  270. var uuid = Guid.NewGuid().ToString();
  271. var request = new CancelReservationRequest()
  272. {
  273. reservationId = Convert.ToInt32(uxReservationTb.Text),
  274. };
  275. WritetoDB(uuid, request);
  276. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  277. }
  278. catch (Exception ex)
  279. {
  280. MessageBox.Show(ex.ToString());
  281. }
  282. }
  283. private void ReserveNow()
  284. {
  285. bool isError = false;
  286. DateTime expiryTime = DateTime.Now;
  287. try
  288. {
  289. try
  290. {
  291. expiryTime = Convert.ToDateTime(uxExpiryTimeTb.Text);
  292. if (expiryTime < DateTime.Now.AddSeconds(60))
  293. {
  294. isError = true;
  295. uxMsgTb.Text = string.Format("ExpiryTime is too close or too early to the current time (60 seconds).");
  296. }
  297. }
  298. catch (Exception ex)
  299. {
  300. if (ex is FormatException)
  301. {
  302. isError = true;
  303. uxMsgTb.Text = string.Format("ExpiryTime's Format is wrong Example:{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
  304. }
  305. }
  306. if (!isError)
  307. {
  308. var uuid = Guid.NewGuid().ToString();
  309. var request = new ReserveNowRequest()
  310. {
  311. connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
  312. expiryDate = expiryTime.ToUniversalTime(),
  313. idTag = uxIdTagTb.Text,
  314. parentIdTag = "PTAG",
  315. reservationId = Convert.ToInt32(expiryTime.ToUniversalTime().ToString("yyMMddHHmm")),
  316. };
  317. WritetoDB(uuid, request);
  318. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  319. }
  320. }
  321. catch (Exception ex)
  322. {
  323. MessageBox.Show(ex.ToString());
  324. }
  325. }
  326. private void GetDiagnostics(bool ftp)
  327. {
  328. try
  329. {
  330. var uuid = Guid.NewGuid().ToString();
  331. var request = new GetDiagnosticsRequest()
  332. {
  333. location = new Uri(ftp ? "ftp://evseocpp:evseocpp@test.evsocket.phihong.com.cn/" : "http://test.evsocket.phihong.com.cn:9003/api/file/"),
  334. retries = 1,
  335. retryInterval = 30,
  336. startTime = DateTime.Now.AddHours(-1).ToUniversalTime(),
  337. stopTime = DateTime.Now.ToUniversalTime()
  338. };
  339. WritetoDB(uuid, request);
  340. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  341. }
  342. catch (Exception ex)
  343. {
  344. MessageBox.Show(ex.ToString());
  345. }
  346. }
  347. #region Local Authorization
  348. private void GetLocalListVersion()
  349. {
  350. try
  351. {
  352. var uuid = Guid.NewGuid().ToString();
  353. var request = new GetLocalListVersionRequest()
  354. {
  355. };
  356. WritetoDB(uuid, request);
  357. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  358. }
  359. catch (Exception ex)
  360. {
  361. MessageBox.Show(ex.ToString());
  362. }
  363. }
  364. private void SendLocalAuthorizationList(bool isFull)
  365. {
  366. try
  367. {
  368. var uuid = Guid.NewGuid().ToString();
  369. var request = new SendLocalListRequest()
  370. {
  371. listVersion = Convert.ToInt32(DateTime.Now.ToUniversalTime().ToString("yyMMddHHmm")),
  372. updateType = isFull ? UpdateType.Full : UpdateType.Differential,
  373. localAuthorizationList = new List<AuthorizationData>()
  374. //localAuthorizationList = new List<AuthorizationData>()
  375. //{
  376. // new AuthorizationData()
  377. // {
  378. // idTagInfo=new IdTagInfo(){ expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status= AuthorizationStatus.Accepted},
  379. // idTag="F5902677"
  380. // }, new AuthorizationData()
  381. // {
  382. // idTagInfo=new IdTagInfo(){ expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status= AuthorizationStatus.Expired},
  383. // idTag="772690F5"
  384. // }
  385. //}
  386. };
  387. request.localAuthorizationList.Add(new AuthorizationData()
  388. {
  389. idTag="F5902677",
  390. idTagInfo = new IdTagInfo()
  391. {
  392. parentIdTag = "0000000000000000001",
  393. expiryDate = DateTime.UtcNow.AddMonths(1),
  394. status = AuthorizationStatus.ConcurrentTx
  395. }
  396. });
  397. request.localAuthorizationList.Add(new AuthorizationData()
  398. {
  399. idTag = "772690F5",
  400. idTagInfo = new IdTagInfo()
  401. {
  402. parentIdTag = "0000000000000000001",
  403. expiryDate = DateTime.UtcNow.AddMonths(1),
  404. status = AuthorizationStatus.Accepted
  405. }
  406. });
  407. for (int i = 0; i < 23; i++)
  408. {
  409. request.localAuthorizationList.Add(new AuthorizationData()
  410. {
  411. idTag = DateTime.Now.ToString("yyyyMMddHHmmss" + i.ToString("00000")),
  412. idTagInfo = new IdTagInfo()
  413. {
  414. parentIdTag = "0000000000000000001",
  415. expiryDate = DateTime.UtcNow.AddMonths(1),
  416. status = AuthorizationStatus.Accepted
  417. }
  418. });
  419. }
  420. WritetoDB(uuid, request);
  421. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  422. }
  423. catch (Exception ex)
  424. {
  425. MessageBox.Show(ex.ToString());
  426. }
  427. }
  428. #endregion
  429. private void SetRemoteTrigger(string action)
  430. {
  431. try
  432. {
  433. string type = action.Split('_').Last();
  434. var uuid = Guid.NewGuid().ToString();
  435. var request = new TriggerMessageRequest()
  436. {
  437. requestedMessage = (MessageTrigger)Enum.Parse(typeof(MessageTrigger), type, false)
  438. };
  439. WritetoDB(uuid, request);
  440. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  441. }
  442. catch (Exception ex)
  443. {
  444. MessageBox.Show(ex.ToString());
  445. }
  446. }
  447. private void SetGetConfiguration()
  448. {
  449. try
  450. {
  451. string uuid = Guid.NewGuid().ToString();
  452. var request = new GetConfigurationRequest()
  453. {
  454. key = uxConfigKeyTb.Text.Split('/').ToList()
  455. };
  456. WritetoDB(uuid, request);
  457. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  458. }
  459. catch (Exception ex)
  460. {
  461. MessageBox.Show(ex.ToString());
  462. }
  463. }
  464. private void UxCmdCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
  465. {
  466. var item = uxCmdCb.SelectedValue as ComboBoxItem;
  467. action = item.Content as string;
  468. }
  469. private void SetRemoteStartTransaction(SetChargingProfileRequest csProfile = null)
  470. {
  471. try
  472. {
  473. var uuid = Guid.NewGuid().ToString();
  474. var request = new RemoteStartTransactionRequest()
  475. {
  476. connectorId = byte.Parse(uxConnectorIdTb.Text),
  477. idTag = uxIdTagTb.Text
  478. };
  479. if (csProfile != null)
  480. {
  481. request.chargingProfile = csProfile.csChargingProfiles;
  482. }
  483. WritetoDB(uuid, request);
  484. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  485. }
  486. catch (Exception ex)
  487. {
  488. MessageBox.Show(ex.ToString());
  489. }
  490. }
  491. private void SetUnlockConnector()
  492. {
  493. try
  494. {
  495. var uuid = Guid.NewGuid().ToString();
  496. var request = new UnlockConnectorRequest()
  497. {
  498. connectorId = byte.Parse(uxConnectorIdTb.Text),
  499. };
  500. WritetoDB(uuid, request);
  501. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  502. }
  503. catch (Exception ex)
  504. {
  505. MessageBox.Show(ex.ToString());
  506. }
  507. }
  508. private void SetChangeAvailability_Inoperative()
  509. {
  510. try
  511. {
  512. var uuid = Guid.NewGuid().ToString();
  513. var request = new ChangeAvailabilityRequest()
  514. {
  515. connectorId = byte.Parse(uxConnectorIdTb.Text),
  516. type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Inoperative
  517. };
  518. WritetoDB(uuid, request);
  519. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  520. }
  521. catch (Exception ex)
  522. {
  523. MessageBox.Show(ex.ToString());
  524. }
  525. }
  526. private void SetChangeAvailability_Operative()
  527. {
  528. try
  529. {
  530. var uuid = Guid.NewGuid().ToString();
  531. var request = new ChangeAvailabilityRequest()
  532. {
  533. connectorId = byte.Parse(uxConnectorIdTb.Text),
  534. type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Operative
  535. };
  536. WritetoDB(uuid, request);
  537. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  538. }
  539. catch (Exception ex)
  540. {
  541. MessageBox.Show(ex.ToString());
  542. }
  543. }
  544. private void SetChangeConfiguration()
  545. {
  546. try
  547. {
  548. var uuid = Guid.NewGuid().ToString();
  549. var request = new ChangeConfigurationRequest()
  550. {
  551. key = uxConfigKeyTb.Text,
  552. value = uxConfigValueTb.Text,
  553. };
  554. WritetoDB(uuid, request);
  555. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  556. }
  557. catch (Exception ex)
  558. {
  559. MessageBox.Show(ex.ToString());
  560. }
  561. }
  562. private void SetClearCache()
  563. {
  564. try
  565. {
  566. var uuid = Guid.NewGuid().ToString();
  567. var request = new ClearCacheRequest()
  568. {
  569. };
  570. WritetoDB(uuid, request);
  571. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  572. }
  573. catch (Exception ex)
  574. {
  575. MessageBox.Show(ex.ToString());
  576. }
  577. }
  578. private void SetGetConfiguration_ALL()
  579. {
  580. try
  581. {
  582. var uuid = Guid.NewGuid().ToString();
  583. var request = new GetConfigurationRequest()
  584. {
  585. key = new List<string>() { }
  586. };
  587. WritetoDB(uuid, request);
  588. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  589. }
  590. catch (Exception ex)
  591. {
  592. MessageBox.Show(ex.ToString());
  593. }
  594. }
  595. private void SetHardReset()
  596. {
  597. try
  598. {
  599. var uuid = Guid.NewGuid().ToString();
  600. var request = new ResetRequest()
  601. {
  602. type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Hard
  603. };
  604. WritetoDB(uuid, request);
  605. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  606. }
  607. catch (Exception ex)
  608. {
  609. MessageBox.Show(ex.ToString());
  610. }
  611. }
  612. private void SetSoftReset()
  613. {
  614. try
  615. {
  616. var uuid = Guid.NewGuid().ToString();
  617. var request = new ResetRequest()
  618. {
  619. type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Soft
  620. };
  621. WritetoDB(uuid, request);
  622. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  623. }
  624. catch (Exception ex)
  625. {
  626. MessageBox.Show(ex.ToString());
  627. }
  628. }
  629. private void SetRemoteStopTransaction()
  630. {
  631. try
  632. {
  633. var uuid = Guid.NewGuid().ToString();
  634. var request = new RemoteStopTransactionRequest()
  635. {
  636. transactionId = int.Parse(uxTransactionIdTb.Text)
  637. };
  638. WritetoDB(uuid, request);
  639. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  640. }
  641. catch (Exception ex)
  642. {
  643. MessageBox.Show(ex.ToString());
  644. }
  645. }
  646. private void WritetoDB(string uuid, IRequest request)
  647. {
  648. using (var db = new MainDBContext())
  649. {
  650. db.MachineOperateRecord.Add(new MachineOperateRecord()
  651. {
  652. CreatedOn = DateTime.Now.ToUniversalTime(),
  653. ChargeBoxId = uxChargeBoxIdTb.Text,
  654. SerialNo = uuid,
  655. RequestContent = JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  656. EVSE_Status = 0,
  657. Status = 0,
  658. RequestType = 1,
  659. Action = request.Action.ToString()
  660. });
  661. db.ServerMessage.Add(new ServerMessage()
  662. {
  663. ChargeBoxId = uxChargeBoxIdTb.Text,
  664. CreatedBy = "TestTool",
  665. CreatedOn = DateTime.Now.ToUniversalTime(),
  666. OutAction = request.Action.ToString(),
  667. OutRequest = JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  668. SerialNo = uuid,
  669. InMessage = string.Empty
  670. });
  671. db.SaveChanges();
  672. }
  673. }
  674. private void uxFileSubmitBtn_Click(object sender, RoutedEventArgs e)
  675. {
  676. OpenFileDialog openFileDialog = new OpenFileDialog();
  677. openFileDialog.Title = "Select file";
  678. var result = openFileDialog.ShowDialog();
  679. if (result == true)
  680. {
  681. uxUploadFileTb.Text = openFileDialog.FileName;
  682. }
  683. }
  684. private void uxUploadBtn_Click(object sender, RoutedEventArgs e)
  685. {
  686. if (string.IsNullOrEmpty(uxUploadFileTb.Text))
  687. {
  688. uxMsgTb.Text = "Please select upload file!";
  689. return;
  690. }
  691. FileInfo f = new FileInfo(uxUploadFileTb.Text);
  692. int size = (int)f.Length;
  693. string md5 = "";
  694. string filePreUrl = ConfigurationManager.AppSettings["FilePreUrl"];
  695. using (WebClient client = new WebClient())
  696. {
  697. client.UseDefaultCredentials = false;
  698. client.Headers.Add("Content-Type", "application/octet-stream");
  699. using (Stream fileStream = File.OpenRead(uxUploadFileTb.Text))
  700. {
  701. var _md5 = MD5.Create();
  702. var hash = _md5.ComputeHash(fileStream);
  703. md5 = BitConverter.ToString(hash).Replace("-", String.Empty).ToLowerInvariant();
  704. }
  705. }
  706. UploadFile ufObj = new UploadFile();
  707. ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
  708. ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
  709. ufObj.Id = Guid.NewGuid();
  710. ufObj.FileName = md5 + ufObj.FileExtensionName;
  711. ufObj.FilePath = "~/UploadFiles/Fw/" + ufObj.FileName;
  712. ufObj.FileSize = size;
  713. ufObj.FileMD5 = md5;
  714. ufObj.CustomerId = new Guid("8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7");
  715. ufObj.OriginName = System.IO.Path.GetFileName(uxUploadFileTb.Text);
  716. ufObj.FileUrl = new Uri(Properties.Settings.Default.FilePreUrl + ufObj.FilePath.Replace("~/", "")).ToString();
  717. ufObj.IsOnline = true;
  718. using (var db = new MainDBContext())
  719. {
  720. db.UploadFile.Add(ufObj);
  721. db.SaveChanges();
  722. var pvQry = db.PublishVersion.Where(x => x.CustomerMachineComponentId == 1).OrderByDescending(c => c.Version).FirstOrDefault();
  723. PublishVersion pv = new PublishVersion { CustomerMachineComponentId = 1, CreatedOn = DateTime.Now.ToUniversalTime(), Version = 1 };
  724. if (pvQry != null)
  725. {
  726. pv.Version = pvQry.Version + 1;
  727. }
  728. pv.PublishVersionFiles.Add(new PublishVersionFile() { UploadFileId = ufObj.Id });
  729. db.PublishVersion.Add(pv);
  730. db.SaveChanges();
  731. }
  732. string filePath = uxUploadFileTb.Text;
  733. uxMsgTb.Text = "Uploading........";
  734. Task.Run(async () =>
  735. {
  736. await UploadTask(filePath, ufObj.FileName);
  737. });
  738. }
  739. private async Task UploadTask(string filePath, string fileName)
  740. {
  741. bool uploadResult = UploadClient.FtpUploadBroken(filePath, @"ftp://test.evsocket.phihong.com.cn/" + fileName);
  742. await Dispatcher.BeginInvoke(new Action(() =>
  743. {
  744. if (uploadResult)
  745. {
  746. uxMsgTb.Text = "Current Progress :100 %";
  747. Thread.CurrentThread.Join(100);
  748. }
  749. uxMsgTb.Text = "Upload File Result :" + (uploadResult ? "Success" : "Fail");
  750. }));
  751. }
  752. private void UploadClient_OnUploadProgress(double percent)
  753. {
  754. Dispatcher.BeginInvoke(new Action(() =>
  755. {
  756. uxMsgTb.Text = "Current Progress :" + (int)percent + " %";
  757. }));
  758. }
  759. private void uxFTPUploadBtn_Click(object sender, RoutedEventArgs e)
  760. {
  761. if (string.IsNullOrEmpty(uxUploadFileTb.Text))
  762. {
  763. uxMsgTb.Text = "Please select upload file!";
  764. return;
  765. }
  766. FileInfo f = new FileInfo(uxUploadFileTb.Text);
  767. int size = (int)f.Length;
  768. string md5 = "";
  769. using (WebClient client = new WebClient())
  770. {
  771. client.UseDefaultCredentials = false;
  772. client.Headers.Add("Content-Type", "application/octet-stream");
  773. using (Stream fileStream = File.OpenRead(uxUploadFileTb.Text))
  774. {
  775. var _md5 = MD5.Create();
  776. var hash = _md5.ComputeHash(fileStream);
  777. md5 = BitConverter.ToString(hash).Replace("-", String.Empty).ToLowerInvariant();
  778. }
  779. }
  780. UploadFile ufObj = new UploadFile();
  781. ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
  782. ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
  783. ufObj.Id = Guid.NewGuid();
  784. ufObj.FileName = md5 + ufObj.FileExtensionName;
  785. ufObj.FilePath = "~/UploadFiles/Fw/" + ufObj.FileName;
  786. ufObj.FileSize = size;
  787. ufObj.FileMD5 = md5;
  788. ufObj.CustomerId = new Guid("8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7");
  789. ufObj.OriginName = System.IO.Path.GetFileName(uxUploadFileTb.Text);
  790. ufObj.FileUrl = new Uri(Properties.Settings.Default.FTPFilePreUrl + ufObj.FileName).ToString();
  791. ufObj.IsOnline = true;
  792. using (var db = new MainDBContext())
  793. {
  794. db.UploadFile.Add(ufObj);
  795. db.SaveChanges();
  796. var pvQry = db.PublishVersion.Where(x => x.CustomerMachineComponentId == 1).OrderByDescending(c => c.Version).FirstOrDefault();
  797. PublishVersion pv = new PublishVersion { CustomerMachineComponentId = 1, CreatedOn = DateTime.Now.ToUniversalTime(), Version = 1 };
  798. if (pvQry != null)
  799. {
  800. pv.Version = pvQry.Version + 1;
  801. }
  802. pv.PublishVersionFiles.Add(new PublishVersionFile() { UploadFileId = ufObj.Id });
  803. db.PublishVersion.Add(pv);
  804. db.SaveChanges();
  805. }
  806. string filePath = uxUploadFileTb.Text;
  807. uxMsgTb.Text = "Uploading........";
  808. Task.Run(async () =>
  809. {
  810. await UploadTask(filePath, ufObj.FileName);
  811. });
  812. }
  813. private void uxRefreshBtn_Click(object sender, RoutedEventArgs e)
  814. {
  815. using (var db = new MainDBContext())
  816. {
  817. publishes = db.PublishVersion
  818. .Include(c => c.PublishVersionFiles)
  819. .Include(c => c.PublishVersionFiles.Select(z => z.UploadFile))
  820. .Include(c => c.CustomerMachineComponent)
  821. .Include(c => c.CustomerMachineComponent.MachineComponent)
  822. .Include(c => c.CustomerMachineComponent.MachineComponent.MachineModel)
  823. .Include(c => c.CustomerMachineComponent.MachineComponent.MachinePart)
  824. .Where(c => c.CustomerMachineComponent.CustomerId == new Guid("8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7") && c.CustomerMachineComponent.Id == 1 && c.CustomerMachineComponent.Id == 1).OrderByDescending(c => c.Id).Take(20).ToList();
  825. StringBuilder sb = new StringBuilder();
  826. uxPublishCb.Items.Clear();
  827. foreach (var i in publishes)
  828. {
  829. string prefix = i.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl.StartsWith("ftp") ? "FTP" : "HTTP";
  830. sb.Clear();
  831. sb.Append(string.Format("[{0}]", prefix));
  832. sb.Append("_版本號:");
  833. sb.Append(i.Version);
  834. sb.Append("_上傳日期:");
  835. sb.Append(i.PublishVersionFiles.First().UploadFile.CreatedOn.ToString());
  836. sb.Append("_檔名:");
  837. foreach (var f in i.PublishVersionFiles)
  838. {
  839. sb.Append(f.UploadFile.OriginName);
  840. sb.Append("、");
  841. }
  842. uxPublishCb.Items.Add(sb.ToString());
  843. uxPublishCb.SelectedIndex = 0;
  844. }
  845. }
  846. }
  847. private void uxPublishBtn_Click(object sender, RoutedEventArgs e)
  848. {
  849. if (selectedPublish < 0)
  850. {
  851. uxMsgTb.Text = "Please choose publish version!";
  852. return;
  853. }
  854. using (var db = new MainDBContext())
  855. {
  856. var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
  857. MachineVersion obj = new MachineVersion()
  858. {
  859. MachineId = machine.Id,
  860. PublishVersionId = publishes[selectedPublish].Id,
  861. CreatedOn = DateTime.Now.ToUniversalTime()
  862. };
  863. obj.MachineVersionFiles.Add(new MachineVersionFile()
  864. {
  865. UploadFileId = publishes[selectedPublish].PublishVersionFiles.First().UploadFileId,
  866. CreatedOn = DateTime.Now.ToUniversalTime()
  867. });
  868. db.MachineVersion.Add(obj);
  869. //將machine的軟體更新更新到這個值
  870. machine.FW_AssignedVersion = publishes[selectedPublish].Version;
  871. machine.FW_MachineVersion = obj;
  872. db.SaveChanges();
  873. }
  874. uxMsgTb.Text = "Publish Complete";
  875. }
  876. private void uxPublishCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
  877. {
  878. selectedPublish = uxPublishCb.SelectedIndex;
  879. }
  880. private void uxClearPublishBtn_Click(object sender, RoutedEventArgs e)
  881. {
  882. using (var db = new MainDBContext())
  883. {
  884. var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
  885. machine.FW_AssignedVersion = null;
  886. machine.FW_AssignedMachineVersionId = null;
  887. db.SaveChanges();
  888. }
  889. uxMsgTb.Text = "Clear Publish";
  890. }
  891. }
  892. }