MainWindow.xaml.cs 40 KB

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