MainWindow.xaml.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  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. FTPClient UploadClient = new FTPClient(@"ftp://test.evsocket.phihong.com.cn", "testocpp", "testocpp");
  47. string chargingProfilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SetChargingProfile.json");
  48. string dataTransferPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataTransfer.json");
  49. int selectedPublish = -1;
  50. bool isDestroyMode = false;
  51. public MainWindow()
  52. {
  53. InitializeComponent();
  54. Loaded += MainWindow_Loaded;
  55. UploadClient.OnUploadProgress += UploadClient_OnUploadProgress;
  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 ReserveNow()
  361. {
  362. bool isError = false;
  363. DateTime expiryTime = DateTime.Now;
  364. try
  365. {
  366. try
  367. {
  368. expiryTime = Convert.ToDateTime(uxExpiryTimeTb.Text);
  369. if (expiryTime < DateTime.Now.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.Now.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 GetDiagnostics(bool ftp)
  404. {
  405. try
  406. {
  407. var uuid = Guid.NewGuid().ToString();
  408. var request = new GetDiagnosticsRequest()
  409. {
  410. location = new Uri(ftp ? Properties.Settings.Default.FTPGetDiagnosticsPreUrl : Properties.Settings.Default.GetDiagnosticsPreUrl),
  411. retries = 1,
  412. retryInterval = 30,
  413. startTime = DateTime.Now.AddHours(-1).ToUniversalTime(),
  414. stopTime = DateTime.Now.ToUniversalTime()
  415. };
  416. WritetoDB(uuid, request);
  417. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  418. }
  419. catch (Exception ex)
  420. {
  421. MessageBox.Show(ex.ToString());
  422. }
  423. }
  424. #region Local Authorization
  425. private void GetLocalListVersion()
  426. {
  427. try
  428. {
  429. var uuid = Guid.NewGuid().ToString();
  430. var request = new GetLocalListVersionRequest()
  431. {
  432. };
  433. WritetoDB(uuid, request);
  434. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  435. }
  436. catch (Exception ex)
  437. {
  438. MessageBox.Show(ex.ToString());
  439. }
  440. }
  441. private void SendLocalAuthorizationList(bool isFull)
  442. {
  443. try
  444. {
  445. var size = Convert.ToInt32(uxLocalListSizeTb.Text);
  446. var uuid = Guid.NewGuid().ToString();
  447. var request = new SendLocalListRequest()
  448. {
  449. listVersion = Convert.ToInt32(DateTimeOffset.Now.AddDays(-50).ToUnixTimeSeconds()),
  450. updateType = isFull ? UpdateType.Full : UpdateType.Differential,
  451. localAuthorizationList = new List<AuthorizationData>()
  452. //localAuthorizationList = new List<AuthorizationData>()
  453. //{
  454. // new AuthorizationData()
  455. // {
  456. // idTagInfo=new IdTagInfo(){ expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status= AuthorizationStatus.Accepted},
  457. // idTag="F5902677"
  458. // }, new AuthorizationData()
  459. // {
  460. // idTagInfo=new IdTagInfo(){ expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status= AuthorizationStatus.Expired},
  461. // idTag="772690F5"
  462. // }
  463. //}
  464. };
  465. //request.localAuthorizationList.Add(new AuthorizationData()
  466. //{
  467. // idTag = "F5902677",
  468. // idTagInfo = new IdTagInfo()
  469. // {
  470. // parentIdTag = "0000000000000000001",
  471. // expiryDate = DateTime.UtcNow.AddMonths(1),
  472. // status = AuthorizationStatus.ConcurrentTx
  473. // }
  474. //});
  475. request.localAuthorizationList.Add(new AuthorizationData()
  476. {
  477. idTag = "AA",
  478. idTagInfo = new IdTagInfo()
  479. {
  480. parentIdTag = "SuperVisor",
  481. expiryDate = DateTime.UtcNow.AddMinutes(5),
  482. status = AuthorizationStatus.Accepted
  483. }
  484. });
  485. request.localAuthorizationList.Add(new AuthorizationData()
  486. {
  487. idTag = "BB",
  488. idTagInfo = new IdTagInfo()
  489. {
  490. parentIdTag = "SuperVisor",
  491. expiryDate = DateTime.UtcNow.AddMinutes(5),
  492. status = AuthorizationStatus.Accepted
  493. }
  494. });
  495. request.localAuthorizationList.Add(new AuthorizationData()
  496. {
  497. idTag = "CC",
  498. idTagInfo = new IdTagInfo()
  499. {
  500. parentIdTag = "SuperVisor",
  501. expiryDate = DateTime.UtcNow.AddMinutes(5),
  502. status = AuthorizationStatus.Accepted
  503. }
  504. });
  505. request.localAuthorizationList.Add(new AuthorizationData()
  506. {
  507. idTag = "DD",
  508. idTagInfo = new IdTagInfo()
  509. {
  510. parentIdTag = "SuperVisor",
  511. expiryDate = DateTime.UtcNow.AddMonths(-1),
  512. status = AuthorizationStatus.Invalid
  513. }
  514. });
  515. request.localAuthorizationList.Add(new AuthorizationData()
  516. {
  517. idTag = "EE",
  518. idTagInfo = new IdTagInfo()
  519. {
  520. parentIdTag = "SuperVisor",
  521. expiryDate = DateTime.UtcNow.AddMonths(-1),
  522. status = AuthorizationStatus.Invalid
  523. }
  524. });
  525. for (int i = 0; i < size - request.localAuthorizationList.Count(); i++)
  526. {
  527. request.localAuthorizationList.Add(new AuthorizationData()
  528. {
  529. idTag = DateTime.Now.ToString("yyyyMMddHHmmss" + i.ToString("00000")),
  530. idTagInfo = new IdTagInfo()
  531. {
  532. parentIdTag = "0000000000000000001",
  533. expiryDate = DateTime.UtcNow.AddMonths(1),
  534. status = AuthorizationStatus.Accepted
  535. }
  536. });
  537. }
  538. WritetoDB(uuid, request);
  539. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  540. }
  541. catch (Exception ex)
  542. {
  543. MessageBox.Show(ex.ToString());
  544. }
  545. }
  546. #endregion
  547. private void SetRemoteTrigger(string action)
  548. {
  549. try
  550. {
  551. string type = action.Split('_').Last();
  552. var uuid = Guid.NewGuid().ToString();
  553. var request = new TriggerMessageRequest()
  554. {
  555. requestedMessage = (MessageTrigger)Enum.Parse(typeof(MessageTrigger), type, false)
  556. };
  557. WritetoDB(uuid, request);
  558. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  559. }
  560. catch (Exception ex)
  561. {
  562. MessageBox.Show(ex.ToString());
  563. }
  564. }
  565. private void SetGetConfiguration()
  566. {
  567. try
  568. {
  569. string uuid = Guid.NewGuid().ToString();
  570. var request = new GetConfigurationRequest()
  571. {
  572. key = uxConfigKeyTb.Text.Split('/').ToList()
  573. };
  574. WritetoDB(uuid, request);
  575. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  576. }
  577. catch (Exception ex)
  578. {
  579. MessageBox.Show(ex.ToString());
  580. }
  581. }
  582. private void UxCmdCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
  583. {
  584. var item = uxCmdCb.SelectedValue as ComboBoxItem;
  585. action = item.Content as string;
  586. }
  587. private void SetRemoteStartTransaction(SetChargingProfileRequest csProfile = null)
  588. {
  589. try
  590. {
  591. var uuid = Guid.NewGuid().ToString();
  592. var request = new RemoteStartTransactionRequest()
  593. {
  594. connectorId = int.Parse(uxConnectorIdTb.Text),
  595. idTag = uxIdTagTb.Text
  596. };
  597. if (csProfile != null)
  598. {
  599. request.chargingProfile = csProfile.csChargingProfiles;
  600. }
  601. WritetoDB(uuid, request);
  602. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  603. }
  604. catch (Exception ex)
  605. {
  606. MessageBox.Show(ex.ToString());
  607. }
  608. }
  609. private void SetUnlockConnector()
  610. {
  611. try
  612. {
  613. var uuid = Guid.NewGuid().ToString();
  614. var request = new UnlockConnectorRequest()
  615. {
  616. connectorId = int.Parse(uxConnectorIdTb.Text),
  617. };
  618. WritetoDB(uuid, request);
  619. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  620. }
  621. catch (Exception ex)
  622. {
  623. MessageBox.Show(ex.ToString());
  624. }
  625. }
  626. private void SetChangeAvailability_Inoperative()
  627. {
  628. try
  629. {
  630. var uuid = Guid.NewGuid().ToString();
  631. var request = new ChangeAvailabilityRequest()
  632. {
  633. connectorId = int.Parse(uxConnectorIdTb.Text),
  634. type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Inoperative
  635. };
  636. WritetoDB(uuid, request);
  637. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  638. }
  639. catch (Exception ex)
  640. {
  641. MessageBox.Show(ex.ToString());
  642. }
  643. }
  644. private void SetChangeAvailability_Operative()
  645. {
  646. try
  647. {
  648. var uuid = Guid.NewGuid().ToString();
  649. var request = new ChangeAvailabilityRequest()
  650. {
  651. connectorId = int.Parse(uxConnectorIdTb.Text),
  652. type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Operative
  653. };
  654. WritetoDB(uuid, request);
  655. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  656. }
  657. catch (Exception ex)
  658. {
  659. MessageBox.Show(ex.ToString());
  660. }
  661. }
  662. private void SetChangeConfiguration()
  663. {
  664. try
  665. {
  666. var uuid = Guid.NewGuid().ToString();
  667. var request = new ChangeConfigurationRequest()
  668. {
  669. key = uxConfigKeyTb.Text,
  670. value = uxConfigValueTb.Text,
  671. };
  672. WritetoDB(uuid, request);
  673. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  674. }
  675. catch (Exception ex)
  676. {
  677. MessageBox.Show(ex.ToString());
  678. }
  679. }
  680. private void SetClearCache()
  681. {
  682. try
  683. {
  684. var uuid = Guid.NewGuid().ToString();
  685. var request = new ClearCacheRequest()
  686. {
  687. };
  688. WritetoDB(uuid, request);
  689. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  690. }
  691. catch (Exception ex)
  692. {
  693. MessageBox.Show(ex.ToString());
  694. }
  695. }
  696. private void SetGetConfiguration_ALL()
  697. {
  698. try
  699. {
  700. var uuid = Guid.NewGuid().ToString();
  701. var request = new GetConfigurationRequest()
  702. {
  703. key = new List<string>() { }
  704. };
  705. WritetoDB(uuid, request);
  706. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  707. }
  708. catch (Exception ex)
  709. {
  710. MessageBox.Show(ex.ToString());
  711. }
  712. }
  713. private void SetHardReset()
  714. {
  715. try
  716. {
  717. var uuid = Guid.NewGuid().ToString();
  718. var request = new ResetRequest()
  719. {
  720. type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Hard
  721. };
  722. WritetoDB(uuid, request);
  723. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  724. }
  725. catch (Exception ex)
  726. {
  727. MessageBox.Show(ex.ToString());
  728. }
  729. }
  730. private void SetSoftReset()
  731. {
  732. try
  733. {
  734. var uuid = Guid.NewGuid().ToString();
  735. var request = new ResetRequest()
  736. {
  737. type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Soft
  738. };
  739. WritetoDB(uuid, request);
  740. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  741. }
  742. catch (Exception ex)
  743. {
  744. MessageBox.Show(ex.ToString());
  745. }
  746. }
  747. private void SetRemoteStopTransaction()
  748. {
  749. try
  750. {
  751. var uuid = Guid.NewGuid().ToString();
  752. var request = new RemoteStopTransactionRequest()
  753. {
  754. transactionId = int.Parse(uxTransactionIdTb.Text)
  755. };
  756. WritetoDB(uuid, request);
  757. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  758. }
  759. catch (Exception ex)
  760. {
  761. MessageBox.Show(ex.ToString());
  762. }
  763. }
  764. private void WritetoDB(string uuid, IRequest request, string action = "", string destroyData = "")
  765. {
  766. using (var db = new MainDBContext())
  767. {
  768. db.MachineOperateRecord.Add(new MachineOperateRecord()
  769. {
  770. CreatedOn = DateTime.Now.ToUniversalTime(),
  771. ChargeBoxId = uxChargeBoxIdTb.Text,
  772. SerialNo = uuid,
  773. RequestContent = !string.IsNullOrEmpty(destroyData) ? destroyData : JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  774. EVSE_Status = 0,
  775. Status = 0,
  776. RequestType = 1,
  777. Action = !string.IsNullOrEmpty(destroyData) ? action : request.Action.ToString()
  778. });
  779. db.ServerMessage.Add(new ServerMessage()
  780. {
  781. ChargeBoxId = uxChargeBoxIdTb.Text,
  782. CreatedBy = !string.IsNullOrEmpty(destroyData) ? "Destroyer" : "TestTool",
  783. CreatedOn = DateTime.Now.ToUniversalTime(),
  784. OutAction = !string.IsNullOrEmpty(destroyData) ? action : request.Action.ToString(),
  785. OutRequest = !string.IsNullOrEmpty(destroyData) ? destroyData : JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  786. SerialNo = uuid,
  787. InMessage = string.Empty
  788. });
  789. db.SaveChanges();
  790. }
  791. }
  792. private void uxFileSubmitBtn_Click(object sender, RoutedEventArgs e)
  793. {
  794. OpenFileDialog openFileDialog = new OpenFileDialog();
  795. openFileDialog.Title = "Select file";
  796. var result = openFileDialog.ShowDialog();
  797. if (result == true)
  798. {
  799. uxUploadFileTb.Text = openFileDialog.FileName;
  800. }
  801. }
  802. private void uxUploadBtn_Click(object sender, RoutedEventArgs e)
  803. {
  804. if (string.IsNullOrEmpty(uxUploadFileTb.Text))
  805. {
  806. uxMsgTb.Text = "Please select upload file!";
  807. return;
  808. }
  809. FileInfo f = new FileInfo(uxUploadFileTb.Text);
  810. int size = (int)f.Length;
  811. string md5 = "";
  812. string filePreUrl = ConfigurationManager.AppSettings["UpdateFWPreUrl"];
  813. using (WebClient client = new WebClient())
  814. {
  815. client.UseDefaultCredentials = false;
  816. client.Headers.Add("Content-Type", "application/octet-stream");
  817. using (Stream fileStream = File.OpenRead(uxUploadFileTb.Text))
  818. {
  819. var _md5 = MD5.Create();
  820. var hash = _md5.ComputeHash(fileStream);
  821. md5 = BitConverter.ToString(hash).Replace("-", String.Empty).ToLowerInvariant();
  822. }
  823. }
  824. UploadFile ufObj = new UploadFile();
  825. ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
  826. ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
  827. ufObj.Id = Guid.NewGuid().ToString();
  828. ufObj.FileName = md5 + ufObj.FileExtensionName;
  829. ufObj.FilePath = "~/UploadFiles/Fw/" + ufObj.FileName;
  830. ufObj.FileSize = size;
  831. ufObj.FileMD5 = md5;
  832. ufObj.OriginName = System.IO.Path.GetFileName(uxUploadFileTb.Text);
  833. ufObj.FileUrl = new Uri(Properties.Settings.Default.UpdateFWPreUrl + ufObj.FilePath.Replace("~/", "")).ToString();
  834. ufObj.VendorId = "TestTool";
  835. ufObj.ModelName = "TestTool";
  836. ufObj.ModuleId = 0;
  837. using (var db = new MainDBContext())
  838. {
  839. db.UploadFile.Add(ufObj);
  840. db.SaveChanges();
  841. }
  842. string filePath = uxUploadFileTb.Text;
  843. uxMsgTb.Text = "Uploading........";
  844. Task.Run(async () =>
  845. {
  846. await UploadTask(filePath, ufObj.FileName);
  847. });
  848. }
  849. private async Task UploadTask(string filePath, string fileName)
  850. {
  851. bool uploadResult = UploadClient.FtpUploadBroken(filePath, @"ftp://ocpp.phihong.com.tw/" + fileName);
  852. await Dispatcher.BeginInvoke(new Action(() =>
  853. {
  854. if (uploadResult)
  855. {
  856. uxMsgTb.Text = "Current Progress :100 %";
  857. Thread.CurrentThread.Join(100);
  858. }
  859. uxMsgTb.Text = "Upload File Result :" + (uploadResult ? "Success" : "Fail");
  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.Now.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, ufObj.FileName);
  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.Now.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. }