MainWindow.xaml.cs 40 KB

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