MainWindow.xaml.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  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. using Newtonsoft.Json.Converters;
  37. namespace TestTool.RemoteTriggerAPP
  38. {
  39. /// <summary>
  40. /// MainWindow.xaml 的互動邏輯
  41. /// </summary>
  42. public partial class MainWindow : Window
  43. {
  44. string action = "";
  45. List<UploadFile> publishes = new List<UploadFile>();
  46. string chargingProfilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SetChargingProfile.json");
  47. string dataTransferPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataTransfer.json");
  48. int selectedPublish = -1;
  49. bool isDestroyMode = false;
  50. public MainWindow()
  51. {
  52. InitializeComponent();
  53. Loaded += MainWindow_Loaded;
  54. }
  55. private void MainWindow_Loaded(object sender, RoutedEventArgs e)
  56. {
  57. uxChargeBoxIdTb.Text = Properties.Settings.Default.ChargeBoxId;
  58. }
  59. private void UxSubmitBtn_Click(object sender, RoutedEventArgs e)
  60. {
  61. if (isDestroyMode)
  62. {
  63. try
  64. {
  65. string actualAction = action.Split(new char[] { '_', '(' })[0];
  66. var uuid = Guid.NewGuid().ToString();
  67. WritetoDB(uuid, null, actualAction, GetDestroyVersionData(actualAction));
  68. uxMsgTb.Text = string.Format("Send Actions: {0} UUID:{1}", actualAction, uuid);
  69. }
  70. catch (Exception ex)
  71. {
  72. MessageBox.Show(ex.ToString());
  73. }
  74. }
  75. else
  76. {
  77. switch (action)
  78. {
  79. #region Core Profile
  80. case "ChangeAvailability_Inoperative":
  81. {
  82. SetChangeAvailability_Inoperative();
  83. }
  84. break;
  85. case "ChangeAvailability_Operative":
  86. {
  87. SetChangeAvailability_Operative();
  88. }
  89. break;
  90. case "DataTransfer":
  91. {
  92. var request = VerifyDataTransfer(dataTransferPath);
  93. SetDataTransfer(request);
  94. }
  95. break;
  96. case "GetConfiguration":
  97. {
  98. if (uxConfigKeyTb.Text == "")
  99. {
  100. SetGetConfiguration_ALL();
  101. }
  102. else
  103. {
  104. SetGetConfiguration();
  105. }
  106. }
  107. break;
  108. case "ChangeConfiguration":
  109. {
  110. SetChangeConfiguration();
  111. }
  112. break;
  113. case "ClearCache":
  114. {
  115. SetClearCache();
  116. }
  117. break;
  118. case "RemoteStartTransaction":
  119. {
  120. SetRemoteStartTransaction();
  121. }
  122. break;
  123. case "RemoteStartTransaction_ChargingProfile":
  124. {
  125. var chargingProfile = VerifyChargingProfile(chargingProfilePath);
  126. if (chargingProfile != null)
  127. {
  128. SetRemoteStartTransaction(chargingProfile);
  129. }
  130. else
  131. {
  132. uxMsgTb.Text = "Please check chargingProfile.json exist in " + AppDomain.CurrentDomain.BaseDirectory;
  133. }
  134. }
  135. break;
  136. case "RemoteStopTransaction":
  137. {
  138. SetRemoteStopTransaction();
  139. }
  140. break;
  141. case "Reset_HardReset":
  142. {
  143. SetHardReset();
  144. }
  145. break;
  146. case "Reset_SoftReset":
  147. {
  148. SetSoftReset();
  149. }
  150. break;
  151. case "UnlockConnector":
  152. {
  153. SetUnlockConnector();
  154. }
  155. break;
  156. #endregion
  157. #region Local Authorization
  158. case "GetLocalListVersion":
  159. {
  160. GetLocalListVersion();
  161. }
  162. break;
  163. case "SendLocalList_Full":
  164. {
  165. SendLocalAuthorizationList(true);
  166. }
  167. break;
  168. case "SendLocalList_Diff":
  169. {
  170. SendLocalAuthorizationList(false);
  171. }
  172. break;
  173. #endregion
  174. case "GetDiagnostics_FTP":
  175. {
  176. GetDiagnostics(true);
  177. }
  178. break;
  179. case "GetDiagnostics_HTTP":
  180. {
  181. GetDiagnostics(false);
  182. }
  183. break;
  184. case "ReserveNow":
  185. {
  186. ReserveNow();
  187. }
  188. break;
  189. case "CancelReservation":
  190. {
  191. CancelReservation();
  192. }
  193. break;
  194. case "ClearChargingProfile":
  195. {
  196. ClearChargingProfile();
  197. }
  198. break;
  199. case "GetCompositeSchedule":
  200. {
  201. GetCompositeSchedule();
  202. }
  203. break;
  204. case "SetChargingProfile":
  205. {
  206. var chargingProfile = VerifyChargingProfile(chargingProfilePath);
  207. if (chargingProfile != null)
  208. {
  209. SetChargingProfile(chargingProfile);
  210. }
  211. else
  212. {
  213. uxMsgTb.Text = "Please check chargingProfile.json exist in " + AppDomain.CurrentDomain.BaseDirectory;
  214. }
  215. //SetChargingProfile(new SetChargingProfileRequest()
  216. //{
  217. // connectorId = 0,
  218. // csChargingProfiles = new csChargingProfiles()
  219. // {
  220. // chargingProfileId = 1,
  221. // chargingProfileKind = ChargingProfileKindType.Recurring,
  222. // chargingProfilePurpose = ChargingProfilePurposeType.ChargePointMaxProfile,
  223. // chargingSchedule = new ChargingSchedule()
  224. // {
  225. // chargingRateUnit = ChargingRateUnitType.W,
  226. // chargingSchedulePeriod = new List<ChargingSchedulePeriod>()
  227. // {
  228. // new ChargingSchedulePeriod(){ startPeriod=0, limit=int.Parse(uxConfigValueTb.Text)}
  229. // },
  230. // },
  231. // recurrencyKind = RecurrencyKindType.Daily,
  232. // stackLevel = 1,
  233. // }
  234. //});
  235. }
  236. break;
  237. #region Trigger Profile
  238. case "TriggerMessage_BootNotification":
  239. case "TriggerMessage_DiagnosticsStatusNotification":
  240. case "TriggerMessage_FirmwareStatusNotification":
  241. case "TriggerMessage_Heartbeat":
  242. case "TriggerMessage_MeterValues":
  243. case "TriggerMessage_StatusNotification":
  244. {
  245. SetRemoteTrigger(action);
  246. }
  247. break;
  248. #endregion
  249. default:
  250. break;
  251. }
  252. }
  253. }
  254. private void SetDataTransfer(DataTransferRequest request)
  255. {
  256. try
  257. {
  258. var uuid = Guid.NewGuid().ToString();
  259. WritetoDB(uuid, request);
  260. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  261. }
  262. catch (Exception ex)
  263. {
  264. MessageBox.Show(ex.ToString());
  265. }
  266. }
  267. private DataTransferRequest VerifyDataTransfer(string path)
  268. {
  269. DataTransferRequest request = null;
  270. if (!File.Exists(path)) return request;
  271. try
  272. {
  273. request = JsonConvert.DeserializeObject<DataTransferRequest>(File.ReadAllText(path));
  274. }
  275. catch
  276. {
  277. }
  278. return request;
  279. }
  280. private SetChargingProfileRequest VerifyChargingProfile(string path)
  281. {
  282. SetChargingProfileRequest request = null;
  283. if (!File.Exists(path)) return request;
  284. try
  285. {
  286. request = JsonConvert.DeserializeObject<SetChargingProfileRequest>(File.ReadAllText(path));
  287. }
  288. catch
  289. {
  290. }
  291. return request;
  292. }
  293. private void SetChargingProfile(SetChargingProfileRequest csProfile)
  294. {
  295. try
  296. {
  297. var uuid = Guid.NewGuid().ToString();
  298. WritetoDB(uuid, csProfile);
  299. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  300. }
  301. catch (Exception ex)
  302. {
  303. MessageBox.Show(ex.ToString());
  304. }
  305. }
  306. private void GetCompositeSchedule()
  307. {
  308. try
  309. {
  310. var uuid = Guid.NewGuid().ToString();
  311. var request = new GetCompositeScheduleRequest()
  312. {
  313. connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
  314. duration = 10000
  315. };
  316. WritetoDB(uuid, request);
  317. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  318. }
  319. catch (Exception ex)
  320. {
  321. MessageBox.Show(ex.ToString());
  322. }
  323. }
  324. private void ClearChargingProfile()
  325. {
  326. try
  327. {
  328. var uuid = Guid.NewGuid().ToString();
  329. var request = new ClearChargingProfileRequest()
  330. {
  331. connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
  332. };
  333. WritetoDB(uuid, request);
  334. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  335. }
  336. catch (Exception ex)
  337. {
  338. MessageBox.Show(ex.ToString());
  339. }
  340. }
  341. private void CancelReservation()
  342. {
  343. try
  344. {
  345. var uuid = Guid.NewGuid().ToString();
  346. var request = new CancelReservationRequest()
  347. {
  348. reservationId = Convert.ToInt32(uxReservationTb.Text),
  349. };
  350. WritetoDB(uuid, request);
  351. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  352. }
  353. catch (Exception ex)
  354. {
  355. MessageBox.Show(ex.ToString());
  356. }
  357. }
  358. private void SetWrongAction()
  359. {
  360. bool isError = false;
  361. DateTime expiryTime = DateTime.Now;
  362. try
  363. {
  364. try
  365. {
  366. expiryTime = Convert.ToDateTime(uxExpiryTimeTb.Text);
  367. //if (expiryTime < DateTime.Now.AddSeconds(60))
  368. //{
  369. // isError = true;
  370. // uxMsgTb.Text = string.Format("ExpiryTime is too close or too early to the current time (60 seconds).");
  371. //}
  372. }
  373. catch (Exception ex)
  374. {
  375. if (ex is FormatException)
  376. {
  377. isError = true;
  378. uxMsgTb.Text = string.Format("ExpiryTime's Format is wrong Example:{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
  379. }
  380. }
  381. if (!isError)
  382. {
  383. var uuid = Guid.NewGuid().ToString();
  384. var request = new ReserveNowRequest()
  385. {
  386. connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
  387. expiryDate = expiryTime.ToUniversalTime(),
  388. idTag = uxIdTagTb.Text,
  389. parentIdTag = "PTAG",
  390. reservationId = Convert.ToInt32(expiryTime.ToUniversalTime().ToString("yyMMddHHmm")),
  391. };
  392. WritetoDB(uuid, request);
  393. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  394. }
  395. }
  396. catch (Exception ex)
  397. {
  398. MessageBox.Show(ex.ToString());
  399. }
  400. }
  401. private void ReserveNow()
  402. {
  403. bool isError = false;
  404. DateTime expiryTime = DateTime.Now;
  405. try
  406. {
  407. try
  408. {
  409. expiryTime = Convert.ToDateTime(uxExpiryTimeTb.Text);
  410. //if (expiryTime < DateTime.Now.AddSeconds(60))
  411. //{
  412. // isError = true;
  413. // uxMsgTb.Text = string.Format("ExpiryTime is too close or too early to the current time (60 seconds).");
  414. //}
  415. }
  416. catch (Exception ex)
  417. {
  418. if (ex is FormatException)
  419. {
  420. isError = true;
  421. uxMsgTb.Text = string.Format("ExpiryTime's Format is wrong Example:{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
  422. }
  423. }
  424. if (!isError)
  425. {
  426. var uuid = Guid.NewGuid().ToString();
  427. var request = new ReserveNowRequest()
  428. {
  429. connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
  430. expiryDate = expiryTime.ToUniversalTime(),
  431. idTag = uxIdTagTb.Text,
  432. parentIdTag = "PTAG",
  433. reservationId = Convert.ToInt32(expiryTime.ToUniversalTime().ToString("MMddHHmm")),
  434. };
  435. WritetoDB(uuid, request);
  436. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  437. }
  438. }
  439. catch (Exception ex)
  440. {
  441. MessageBox.Show(ex.ToString());
  442. }
  443. }
  444. private void GetDiagnostics(bool ftp)
  445. {
  446. try
  447. {
  448. var uuid = Guid.NewGuid().ToString();
  449. var request = new GetDiagnosticsRequest()
  450. {
  451. location = new Uri(ftp ? Properties.Settings.Default.FTPGetDiagnosticsPreUrl : Properties.Settings.Default.GetDiagnosticsPreUrl),
  452. retries = 1,
  453. retryInterval = 30,
  454. startTime = DateTime.Now.AddHours(-1).ToUniversalTime(),
  455. stopTime = DateTime.Now.ToUniversalTime()
  456. };
  457. WritetoDB(uuid, request);
  458. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  459. }
  460. catch (Exception ex)
  461. {
  462. MessageBox.Show(ex.ToString());
  463. }
  464. }
  465. #region Local Authorization
  466. private void GetLocalListVersion()
  467. {
  468. try
  469. {
  470. var uuid = Guid.NewGuid().ToString();
  471. var request = new GetLocalListVersionRequest()
  472. {
  473. };
  474. WritetoDB(uuid, request);
  475. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  476. }
  477. catch (Exception ex)
  478. {
  479. MessageBox.Show(ex.ToString());
  480. }
  481. }
  482. private void SendLocalAuthorizationList(bool isFull)
  483. {
  484. try
  485. {
  486. var size = Convert.ToInt32(uxLocalListSizeTb.Text);
  487. var uuid = Guid.NewGuid().ToString();
  488. var request = new SendLocalListRequest()
  489. {
  490. listVersion = Convert.ToInt32(DateTimeOffset.Now.AddDays(-50).ToUnixTimeSeconds()),
  491. updateType = isFull ? UpdateType.Full : UpdateType.Differential,
  492. localAuthorizationList = new List<AuthorizationData>()
  493. //localAuthorizationList = new List<AuthorizationData>()
  494. //{
  495. // new AuthorizationData()
  496. // {
  497. // idTagInfo=new IdTagInfo(){ expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status= AuthorizationStatus.Accepted},
  498. // idTag="F5902677"
  499. // }, new AuthorizationData()
  500. // {
  501. // idTagInfo=new IdTagInfo(){ expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status= AuthorizationStatus.Expired},
  502. // idTag="772690F5"
  503. // }
  504. //}
  505. };
  506. //request.localAuthorizationList.Add(new AuthorizationData()
  507. //{
  508. // idTag = "F5902677",
  509. // idTagInfo = new IdTagInfo()
  510. // {
  511. // parentIdTag = "0000000000000000001",
  512. // expiryDate = DateTime.UtcNow.AddMonths(1),
  513. // status = AuthorizationStatus.ConcurrentTx
  514. // }
  515. //});
  516. for (int i = 0; i < size; i++)
  517. {
  518. request.localAuthorizationList.Add(new AuthorizationData()
  519. {
  520. idTag = DateTime.Now.ToString("yyyyMMddHHmmss" + i.ToString("00000")),
  521. idTagInfo = new IdTagInfo()
  522. {
  523. parentIdTag = "0000000000000000001",
  524. expiryDate = DateTime.UtcNow.AddMonths(1),
  525. status = AuthorizationStatus.Accepted
  526. }
  527. });
  528. }
  529. WritetoDB(uuid, request);
  530. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  531. }
  532. catch (Exception ex)
  533. {
  534. MessageBox.Show(ex.ToString());
  535. }
  536. }
  537. #endregion
  538. private void SetRemoteTrigger(string action)
  539. {
  540. try
  541. {
  542. string type = action.Split('_').Last();
  543. var uuid = Guid.NewGuid().ToString();
  544. var request = new TriggerMessageRequest()
  545. {
  546. requestedMessage = (MessageTrigger)Enum.Parse(typeof(MessageTrigger), type, false)
  547. };
  548. WritetoDB(uuid, request);
  549. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  550. }
  551. catch (Exception ex)
  552. {
  553. MessageBox.Show(ex.ToString());
  554. }
  555. }
  556. private void SetGetConfiguration()
  557. {
  558. try
  559. {
  560. string uuid = Guid.NewGuid().ToString();
  561. var request = new GetConfigurationRequest()
  562. {
  563. key = uxConfigKeyTb.Text.Split('/').ToList()
  564. };
  565. WritetoDB(uuid, request);
  566. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  567. }
  568. catch (Exception ex)
  569. {
  570. MessageBox.Show(ex.ToString());
  571. }
  572. }
  573. private void UxCmdCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
  574. {
  575. var item = uxCmdCb.SelectedValue as ComboBoxItem;
  576. action = item.Content as string;
  577. }
  578. private void SetRemoteStartTransaction(SetChargingProfileRequest csProfile = null)
  579. {
  580. try
  581. {
  582. var uuid = Guid.NewGuid().ToString();
  583. var request = new RemoteStartTransactionRequest()
  584. {
  585. connectorId = int.Parse(uxConnectorIdTb.Text),
  586. idTag = uxIdTagTb.Text
  587. };
  588. if (csProfile != null)
  589. {
  590. request.chargingProfile = csProfile.csChargingProfiles;
  591. }
  592. WritetoDB(uuid, request);
  593. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  594. }
  595. catch (Exception ex)
  596. {
  597. MessageBox.Show(ex.ToString());
  598. }
  599. }
  600. private void SetUnlockConnector()
  601. {
  602. try
  603. {
  604. var uuid = Guid.NewGuid().ToString();
  605. var request = new UnlockConnectorRequest()
  606. {
  607. connectorId = int.Parse(uxConnectorIdTb.Text),
  608. };
  609. WritetoDB(uuid, request);
  610. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  611. }
  612. catch (Exception ex)
  613. {
  614. MessageBox.Show(ex.ToString());
  615. }
  616. }
  617. private void SetChangeAvailability_Inoperative()
  618. {
  619. try
  620. {
  621. var uuid = Guid.NewGuid().ToString();
  622. var request = new ChangeAvailabilityRequest()
  623. {
  624. connectorId = int.Parse(uxConnectorIdTb.Text),
  625. type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Inoperative
  626. };
  627. WritetoDB(uuid, request);
  628. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  629. }
  630. catch (Exception ex)
  631. {
  632. MessageBox.Show(ex.ToString());
  633. }
  634. }
  635. private void SetChangeAvailability_Operative()
  636. {
  637. try
  638. {
  639. var uuid = Guid.NewGuid().ToString();
  640. var request = new ChangeAvailabilityRequest()
  641. {
  642. connectorId = int.Parse(uxConnectorIdTb.Text),
  643. type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Operative
  644. };
  645. WritetoDB(uuid, request);
  646. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  647. }
  648. catch (Exception ex)
  649. {
  650. MessageBox.Show(ex.ToString());
  651. }
  652. }
  653. private void SetChangeConfiguration()
  654. {
  655. try
  656. {
  657. var uuid = Guid.NewGuid().ToString();
  658. var request = new ChangeConfigurationRequest()
  659. {
  660. key = uxConfigKeyTb.Text,
  661. value = uxConfigValueTb.Text,
  662. };
  663. WritetoDB(uuid, request);
  664. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  665. }
  666. catch (Exception ex)
  667. {
  668. MessageBox.Show(ex.ToString());
  669. }
  670. }
  671. private void SetClearCache()
  672. {
  673. try
  674. {
  675. var uuid = Guid.NewGuid().ToString();
  676. var request = new ClearCacheRequest()
  677. {
  678. };
  679. WritetoDB(uuid, request);
  680. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  681. }
  682. catch (Exception ex)
  683. {
  684. MessageBox.Show(ex.ToString());
  685. }
  686. }
  687. private void SetGetConfiguration_ALL()
  688. {
  689. try
  690. {
  691. var uuid = Guid.NewGuid().ToString();
  692. var request = new GetConfigurationRequest()
  693. {
  694. key = new List<string>() { }
  695. };
  696. WritetoDB(uuid, request);
  697. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  698. }
  699. catch (Exception ex)
  700. {
  701. MessageBox.Show(ex.ToString());
  702. }
  703. }
  704. private void SetHardReset()
  705. {
  706. try
  707. {
  708. var uuid = Guid.NewGuid().ToString();
  709. var request = new ResetRequest()
  710. {
  711. type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Hard
  712. };
  713. WritetoDB(uuid, request);
  714. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  715. }
  716. catch (Exception ex)
  717. {
  718. MessageBox.Show(ex.ToString());
  719. }
  720. }
  721. private void SetSoftReset()
  722. {
  723. try
  724. {
  725. var uuid = Guid.NewGuid().ToString();
  726. var request = new ResetRequest()
  727. {
  728. type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Soft
  729. };
  730. WritetoDB(uuid, request);
  731. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  732. }
  733. catch (Exception ex)
  734. {
  735. MessageBox.Show(ex.ToString());
  736. }
  737. }
  738. private void SetRemoteStopTransaction()
  739. {
  740. try
  741. {
  742. var uuid = Guid.NewGuid().ToString();
  743. var request = new RemoteStopTransactionRequest()
  744. {
  745. transactionId = int.Parse(uxTransactionIdTb.Text)
  746. };
  747. WritetoDB(uuid, request);
  748. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  749. }
  750. catch (Exception ex)
  751. {
  752. MessageBox.Show(ex.ToString());
  753. }
  754. }
  755. private void WritetoDB(string uuid, IRequest request, string action = "", string destroyData = "")
  756. {
  757. using (var db = new MainDBContext())
  758. {
  759. db.MachineOperateRecord.Add(new MachineOperateRecord()
  760. {
  761. CreatedOn = DateTime.Now.ToUniversalTime(),
  762. ChargeBoxId = uxChargeBoxIdTb.Text,
  763. SerialNo = uuid,
  764. RequestContent = !string.IsNullOrEmpty(destroyData) ? destroyData : JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  765. EVSE_Status = 0,
  766. Status = 0,
  767. RequestType = 1,
  768. Action = !string.IsNullOrEmpty(destroyData) ? action : request.Action.ToString()
  769. });
  770. db.ServerMessage.Add(new ServerMessage()
  771. {
  772. ChargeBoxId = uxChargeBoxIdTb.Text,
  773. CreatedBy = !string.IsNullOrEmpty(destroyData) ? "Destroyer" : "TestTool",
  774. CreatedOn = DateTime.Now.ToUniversalTime(),
  775. OutAction = !string.IsNullOrEmpty(destroyData) ? action : request.Action.ToString(),
  776. OutRequest = !string.IsNullOrEmpty(destroyData) ? destroyData : JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  777. SerialNo = uuid,
  778. InMessage = string.Empty
  779. });
  780. db.SaveChanges();
  781. }
  782. }
  783. private void uxFileSubmitBtn_Click(object sender, RoutedEventArgs e)
  784. {
  785. OpenFileDialog openFileDialog = new OpenFileDialog();
  786. openFileDialog.Title = "Select file";
  787. var result = openFileDialog.ShowDialog();
  788. if (result == true)
  789. {
  790. uxUploadFileTb.Text = openFileDialog.FileName;
  791. }
  792. }
  793. private void uxUploadBtn_Click(object sender, RoutedEventArgs e)
  794. {
  795. if (string.IsNullOrEmpty(uxUploadFileTb.Text))
  796. {
  797. uxMsgTb.Text = "Please select upload file!";
  798. return;
  799. }
  800. string filePath = uxUploadFileTb.Text;
  801. Task.Run(async () =>
  802. {
  803. await UploadTask(filePath, false);
  804. });
  805. }
  806. private async Task UploadTask(string filepath, bool isFTP)
  807. {
  808. try
  809. {
  810. await Dispatcher.BeginInvoke(new Action(() =>
  811. {
  812. uxMsgTb.Text = "Uploading........";
  813. }));
  814. FileInfo f = new FileInfo(filepath);
  815. int size = (int)f.Length;
  816. string fileMD5 = ""; //get file md5
  817. using (var md5 = MD5.Create())
  818. {
  819. using (var stream = File.OpenRead(filepath))
  820. {
  821. fileMD5 = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", String.Empty).ToLower();
  822. }
  823. }
  824. string filePreUrl = isFTP ? Properties.Settings.Default.FTPUpdateFWPreUrl : Properties.Settings.Default.UpdateFWPreUrl;
  825. UploadFile ufObj = new UploadFile();
  826. ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
  827. ufObj.FileExtensionName = System.IO.Path.GetExtension(filepath);
  828. ufObj.Id = Guid.NewGuid().ToString();
  829. ufObj.FileName = fileMD5 + System.IO.Path.GetExtension(filepath);
  830. ufObj.FilePath = isFTP ? "~/" + ufObj.FileName : "~/UploadFiles/FW/" + ufObj.FileName;
  831. ufObj.FileSize = size;
  832. ufObj.FileMD5 = fileMD5;
  833. ufObj.OriginName = System.IO.Path.GetFileName(filepath);
  834. ufObj.FileUrl = new Uri(filePreUrl + ufObj.FilePath.Replace("~/", "")).ToString();
  835. ufObj.VendorId = "TestTool";
  836. ufObj.ModelName = "TestTool";
  837. ufObj.ModuleId = 0;
  838. using (var db = new MainDBContext())
  839. {
  840. db.UploadFile.Add(ufObj);
  841. await db.SaveChangesAsync();
  842. }
  843. FluentFTPClient ftpClient = new FluentFTPClient("ocpp.phihong.com.tw", 5002, "testocpp", "testocpp", "/");
  844. //Properties.Settings.Default.UpdateFWPreUrl
  845. bool uploadResult = await ftpClient.UploadFileAsync(filepath, ufObj.FileName);
  846. await Dispatcher.BeginInvoke(new Action(() =>
  847. {
  848. if (uploadResult)
  849. {
  850. uxMsgTb.Text = "Current Progress :100 %";
  851. Thread.CurrentThread.Join(100);
  852. }
  853. uxMsgTb.Text = "Upload File Result :" + (uploadResult ? "Success" : "Fail");
  854. }));
  855. }
  856. catch (Exception ex)
  857. {
  858. }
  859. }
  860. private void uxFTPUploadBtn_Click(object sender, RoutedEventArgs e)
  861. {
  862. if (string.IsNullOrEmpty(uxUploadFileTb.Text))
  863. {
  864. uxMsgTb.Text = "Please select upload file!";
  865. return;
  866. }
  867. FileInfo f = new FileInfo(uxUploadFileTb.Text);
  868. int size = (int)f.Length;
  869. string md5 = "";
  870. using (WebClient client = new WebClient())
  871. {
  872. client.UseDefaultCredentials = false;
  873. client.Headers.Add("Content-Type", "application/octet-stream");
  874. using (Stream fileStream = File.OpenRead(uxUploadFileTb.Text))
  875. {
  876. var _md5 = MD5.Create();
  877. var hash = _md5.ComputeHash(fileStream);
  878. md5 = BitConverter.ToString(hash).Replace("-", String.Empty).ToLowerInvariant();
  879. }
  880. }
  881. UploadFile ufObj = new UploadFile();
  882. ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
  883. ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
  884. ufObj.Id = Guid.NewGuid().ToString();
  885. ufObj.FileName = md5 + ufObj.FileExtensionName;
  886. ufObj.FilePath = "~/UploadFiles/Fw/" + ufObj.FileName;
  887. ufObj.FileSize = size;
  888. ufObj.FileMD5 = md5;
  889. ufObj.OriginName = System.IO.Path.GetFileName(uxUploadFileTb.Text);
  890. ufObj.FileUrl = new Uri(Properties.Settings.Default.FTPUpdateFWPreUrl + ufObj.FileName).ToString();
  891. ufObj.VendorId = "TestTool";
  892. ufObj.ModelName = "TestTool";
  893. ufObj.ModuleId = 0;
  894. using (var db = new MainDBContext())
  895. {
  896. db.UploadFile.Add(ufObj);
  897. db.SaveChanges();
  898. }
  899. string filePath = uxUploadFileTb.Text;
  900. uxMsgTb.Text = "Uploading........";
  901. Task.Run(async () =>
  902. {
  903. await UploadTask(filePath, true);
  904. });
  905. }
  906. private void uxRefreshBtn_Click(object sender, RoutedEventArgs e)
  907. {
  908. using (var db = new MainDBContext())
  909. {
  910. publishes = db.UploadFile.OrderByDescending(c => c.CreatedOn).Take(20).ToList();
  911. StringBuilder sb = new StringBuilder();
  912. uxPublishCb.Items.Clear();
  913. foreach (var i in publishes)
  914. {
  915. string prefix = i.FileUrl.StartsWith("ftp") ? "FTP" : "HTTP";
  916. sb.Clear();
  917. sb.Append(string.Format("[{0}]", prefix));
  918. sb.Append("_上傳日期:");
  919. sb.Append(i.CreatedOn.ToString());
  920. sb.Append("_檔名:");
  921. sb.Append(i.OriginName);
  922. uxPublishCb.Items.Add(sb.ToString());
  923. uxPublishCb.SelectedIndex = 0;
  924. }
  925. }
  926. }
  927. private void uxPublishBtn_Click(object sender, RoutedEventArgs e)
  928. {
  929. if (selectedPublish < 0)
  930. {
  931. uxMsgTb.Text = "Please choose publish version!";
  932. return;
  933. }
  934. using (var db = new MainDBContext())
  935. {
  936. var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
  937. MachineVersionFile obj = new MachineVersionFile()
  938. {
  939. ChargeBoxId = uxChargeBoxIdTb.Text,
  940. UploadFileId = publishes[selectedPublish].Id,
  941. CreatedOn = DateTime.Now.ToUniversalTime()
  942. };
  943. db.MachineVersionFile.Add(obj);
  944. //將machine的軟體更新更新到這個值
  945. db.SaveChanges();
  946. machine.FW_AssignedVersion = obj.Id;
  947. db.SaveChanges();
  948. }
  949. uxMsgTb.Text = "Publish Complete";
  950. }
  951. private void uxPublishCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
  952. {
  953. selectedPublish = uxPublishCb.SelectedIndex;
  954. }
  955. private void uxClearPublishBtn_Click(object sender, RoutedEventArgs e)
  956. {
  957. using (var db = new MainDBContext())
  958. {
  959. var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
  960. machine.FW_AssignedVersion = null;
  961. db.SaveChanges();
  962. }
  963. uxMsgTb.Text = "Clear Publish";
  964. }
  965. private void uxChargeBoxIdTb_LostFocus(object sender, RoutedEventArgs e)
  966. {
  967. Properties.Settings.Default.ChargeBoxId = uxChargeBoxIdTb.Text;
  968. Properties.Settings.Default.Save();
  969. }
  970. private string GetDestroyVersionData(string action)
  971. {
  972. string result = "";
  973. try
  974. {
  975. string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, action + ".json");
  976. var request = JsonConvert.DeserializeObject(File.ReadAllText(path));
  977. result = JsonConvert.SerializeObject(request);
  978. }
  979. catch (Exception ex)
  980. {
  981. uxMsgTb.Text += "解析檔案發生問題 " + ex.ToString();
  982. }
  983. return result;
  984. }
  985. private void uxDestroyCb_Checked(object sender, RoutedEventArgs e)
  986. {
  987. isDestroyMode = true;
  988. uxConnectorIdTb.IsEnabled = false;
  989. uxReservationTb.IsEnabled = false;
  990. uxIdTagTb.IsEnabled = false;
  991. uxParentIdTagTb.IsEnabled = false;
  992. uxTransactionIdTb.IsEnabled = false;
  993. uxLocalListSizeTb.IsEnabled = false;
  994. uxConfigKeyTb.IsEnabled = false;
  995. uxConfigValueTb.IsEnabled = false;
  996. uxExpiryTimeTb.IsEnabled = false;
  997. }
  998. private void uxDestroyCb_Unchecked(object sender, RoutedEventArgs e)
  999. {
  1000. isDestroyMode = false;
  1001. uxConnectorIdTb.IsEnabled = true;
  1002. uxReservationTb.IsEnabled = true;
  1003. uxIdTagTb.IsEnabled = true;
  1004. uxParentIdTagTb.IsEnabled = true;
  1005. uxTransactionIdTb.IsEnabled = true;
  1006. uxLocalListSizeTb.IsEnabled = true;
  1007. uxConfigKeyTb.IsEnabled = true;
  1008. uxConfigValueTb.IsEnabled = true;
  1009. uxExpiryTimeTb.IsEnabled = true;
  1010. }
  1011. }
  1012. }