MainWindow.xaml.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  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 SetWrongAction()
  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 ReserveNow()
  404. {
  405. bool isError = false;
  406. DateTime expiryTime = DateTime.Now;
  407. try
  408. {
  409. try
  410. {
  411. expiryTime = Convert.ToDateTime(uxExpiryTimeTb.Text);
  412. //if (expiryTime < DateTime.Now.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.Now.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("yyMMddHHmm")),
  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.Now.AddHours(-1).ToUniversalTime(),
  457. stopTime = DateTime.Now.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.Now.ToUniversalTime().AddDays(3), status= AuthorizationStatus.Accepted},
  500. // idTag="F5902677"
  501. // }, new AuthorizationData()
  502. // {
  503. // idTagInfo=new IdTagInfo(){ expiryDate=DateTime.Now.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. request.localAuthorizationList.Add(new AuthorizationData()
  519. {
  520. idTag = "AA",
  521. idTagInfo = new IdTagInfo()
  522. {
  523. parentIdTag = "SuperVisor",
  524. expiryDate = DateTime.UtcNow.AddMinutes(5),
  525. status = AuthorizationStatus.Accepted
  526. }
  527. });
  528. request.localAuthorizationList.Add(new AuthorizationData()
  529. {
  530. idTag = "BB",
  531. idTagInfo = new IdTagInfo()
  532. {
  533. parentIdTag = "SuperVisor",
  534. expiryDate = DateTime.UtcNow.AddMinutes(5),
  535. status = AuthorizationStatus.Accepted
  536. }
  537. });
  538. request.localAuthorizationList.Add(new AuthorizationData()
  539. {
  540. idTag = "CC",
  541. idTagInfo = new IdTagInfo()
  542. {
  543. parentIdTag = "SuperVisor",
  544. expiryDate = DateTime.UtcNow.AddMinutes(5),
  545. status = AuthorizationStatus.Accepted
  546. }
  547. });
  548. request.localAuthorizationList.Add(new AuthorizationData()
  549. {
  550. idTag = "DD",
  551. idTagInfo = new IdTagInfo()
  552. {
  553. parentIdTag = "SuperVisor",
  554. expiryDate = DateTime.UtcNow.AddMonths(-1),
  555. status = AuthorizationStatus.Invalid
  556. }
  557. });
  558. request.localAuthorizationList.Add(new AuthorizationData()
  559. {
  560. idTag = "EE",
  561. idTagInfo = new IdTagInfo()
  562. {
  563. parentIdTag = "SuperVisor",
  564. expiryDate = DateTime.UtcNow.AddMonths(-1),
  565. status = AuthorizationStatus.Invalid
  566. }
  567. });
  568. for (int i = 0; i < size - request.localAuthorizationList.Count(); i++)
  569. {
  570. request.localAuthorizationList.Add(new AuthorizationData()
  571. {
  572. idTag = DateTime.Now.ToString("yyyyMMddHHmmss" + i.ToString("00000")),
  573. idTagInfo = new IdTagInfo()
  574. {
  575. parentIdTag = "0000000000000000001",
  576. expiryDate = DateTime.UtcNow.AddMonths(1),
  577. status = AuthorizationStatus.Accepted
  578. }
  579. });
  580. }
  581. WritetoDB(uuid, request);
  582. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  583. }
  584. catch (Exception ex)
  585. {
  586. MessageBox.Show(ex.ToString());
  587. }
  588. }
  589. #endregion
  590. private void SetRemoteTrigger(string action)
  591. {
  592. try
  593. {
  594. string type = action.Split('_').Last();
  595. var uuid = Guid.NewGuid().ToString();
  596. var request = new TriggerMessageRequest()
  597. {
  598. requestedMessage = (MessageTrigger)Enum.Parse(typeof(MessageTrigger), type, false)
  599. };
  600. WritetoDB(uuid, request);
  601. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  602. }
  603. catch (Exception ex)
  604. {
  605. MessageBox.Show(ex.ToString());
  606. }
  607. }
  608. private void SetGetConfiguration()
  609. {
  610. try
  611. {
  612. string uuid = Guid.NewGuid().ToString();
  613. var request = new GetConfigurationRequest()
  614. {
  615. key = uxConfigKeyTb.Text.Split('/').ToList()
  616. };
  617. WritetoDB(uuid, request);
  618. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  619. }
  620. catch (Exception ex)
  621. {
  622. MessageBox.Show(ex.ToString());
  623. }
  624. }
  625. private void UxCmdCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
  626. {
  627. var item = uxCmdCb.SelectedValue as ComboBoxItem;
  628. action = item.Content as string;
  629. }
  630. private void SetRemoteStartTransaction(SetChargingProfileRequest csProfile = null)
  631. {
  632. try
  633. {
  634. var uuid = Guid.NewGuid().ToString();
  635. var request = new RemoteStartTransactionRequest()
  636. {
  637. connectorId = int.Parse(uxConnectorIdTb.Text),
  638. idTag = uxIdTagTb.Text
  639. };
  640. if (csProfile != null)
  641. {
  642. request.chargingProfile = csProfile.csChargingProfiles;
  643. }
  644. WritetoDB(uuid, request);
  645. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  646. }
  647. catch (Exception ex)
  648. {
  649. MessageBox.Show(ex.ToString());
  650. }
  651. }
  652. private void SetUnlockConnector()
  653. {
  654. try
  655. {
  656. var uuid = Guid.NewGuid().ToString();
  657. var request = new UnlockConnectorRequest()
  658. {
  659. connectorId = int.Parse(uxConnectorIdTb.Text),
  660. };
  661. WritetoDB(uuid, request);
  662. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  663. }
  664. catch (Exception ex)
  665. {
  666. MessageBox.Show(ex.ToString());
  667. }
  668. }
  669. private void SetChangeAvailability_Inoperative()
  670. {
  671. try
  672. {
  673. var uuid = Guid.NewGuid().ToString();
  674. var request = new ChangeAvailabilityRequest()
  675. {
  676. connectorId = int.Parse(uxConnectorIdTb.Text),
  677. type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Inoperative
  678. };
  679. WritetoDB(uuid, request);
  680. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  681. }
  682. catch (Exception ex)
  683. {
  684. MessageBox.Show(ex.ToString());
  685. }
  686. }
  687. private void SetChangeAvailability_Operative()
  688. {
  689. try
  690. {
  691. var uuid = Guid.NewGuid().ToString();
  692. var request = new ChangeAvailabilityRequest()
  693. {
  694. connectorId = int.Parse(uxConnectorIdTb.Text),
  695. type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Operative
  696. };
  697. WritetoDB(uuid, request);
  698. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  699. }
  700. catch (Exception ex)
  701. {
  702. MessageBox.Show(ex.ToString());
  703. }
  704. }
  705. private void SetChangeConfiguration()
  706. {
  707. try
  708. {
  709. var uuid = Guid.NewGuid().ToString();
  710. var request = new ChangeConfigurationRequest()
  711. {
  712. key = uxConfigKeyTb.Text,
  713. value = uxConfigValueTb.Text,
  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 SetClearCache()
  724. {
  725. try
  726. {
  727. var uuid = Guid.NewGuid().ToString();
  728. var request = new ClearCacheRequest()
  729. {
  730. };
  731. WritetoDB(uuid, request);
  732. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  733. }
  734. catch (Exception ex)
  735. {
  736. MessageBox.Show(ex.ToString());
  737. }
  738. }
  739. private void SetGetConfiguration_ALL()
  740. {
  741. try
  742. {
  743. var uuid = Guid.NewGuid().ToString();
  744. var request = new GetConfigurationRequest()
  745. {
  746. key = new List<string>() { }
  747. };
  748. WritetoDB(uuid, request);
  749. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  750. }
  751. catch (Exception ex)
  752. {
  753. MessageBox.Show(ex.ToString());
  754. }
  755. }
  756. private void SetHardReset()
  757. {
  758. try
  759. {
  760. var uuid = Guid.NewGuid().ToString();
  761. var request = new ResetRequest()
  762. {
  763. type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Hard
  764. };
  765. WritetoDB(uuid, request);
  766. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  767. }
  768. catch (Exception ex)
  769. {
  770. MessageBox.Show(ex.ToString());
  771. }
  772. }
  773. private void SetSoftReset()
  774. {
  775. try
  776. {
  777. var uuid = Guid.NewGuid().ToString();
  778. var request = new ResetRequest()
  779. {
  780. type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Soft
  781. };
  782. WritetoDB(uuid, request);
  783. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  784. }
  785. catch (Exception ex)
  786. {
  787. MessageBox.Show(ex.ToString());
  788. }
  789. }
  790. private void SetRemoteStopTransaction()
  791. {
  792. try
  793. {
  794. var uuid = Guid.NewGuid().ToString();
  795. var request = new RemoteStopTransactionRequest()
  796. {
  797. transactionId = int.Parse(uxTransactionIdTb.Text)
  798. };
  799. WritetoDB(uuid, request);
  800. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  801. }
  802. catch (Exception ex)
  803. {
  804. MessageBox.Show(ex.ToString());
  805. }
  806. }
  807. private void WritetoDB(string uuid, IRequest request, string action = "", string destroyData = "")
  808. {
  809. using (var db = new MainDBContext())
  810. {
  811. db.MachineOperateRecord.Add(new MachineOperateRecord()
  812. {
  813. CreatedOn = DateTime.Now.ToUniversalTime(),
  814. ChargeBoxId = uxChargeBoxIdTb.Text,
  815. SerialNo = uuid,
  816. RequestContent = !string.IsNullOrEmpty(destroyData) ? destroyData : JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  817. EVSE_Status = 0,
  818. Status = 0,
  819. RequestType = 1,
  820. Action = !string.IsNullOrEmpty(destroyData) ? action : request.Action.ToString()
  821. });
  822. db.ServerMessage.Add(new ServerMessage()
  823. {
  824. ChargeBoxId = uxChargeBoxIdTb.Text,
  825. CreatedBy = !string.IsNullOrEmpty(destroyData) ? "Destroyer" : "TestTool",
  826. CreatedOn = DateTime.Now.ToUniversalTime(),
  827. OutAction = !string.IsNullOrEmpty(destroyData) ? action : request.Action.ToString(),
  828. OutRequest = !string.IsNullOrEmpty(destroyData) ? destroyData : JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  829. SerialNo = uuid,
  830. InMessage = string.Empty
  831. });
  832. db.SaveChanges();
  833. }
  834. }
  835. private void uxFileSubmitBtn_Click(object sender, RoutedEventArgs e)
  836. {
  837. OpenFileDialog openFileDialog = new OpenFileDialog();
  838. openFileDialog.Title = "Select file";
  839. var result = openFileDialog.ShowDialog();
  840. if (result == true)
  841. {
  842. uxUploadFileTb.Text = openFileDialog.FileName;
  843. }
  844. }
  845. private void uxUploadBtn_Click(object sender, RoutedEventArgs e)
  846. {
  847. if (string.IsNullOrEmpty(uxUploadFileTb.Text))
  848. {
  849. uxMsgTb.Text = "Please select upload file!";
  850. return;
  851. }
  852. FileInfo f = new FileInfo(uxUploadFileTb.Text);
  853. int size = (int)f.Length;
  854. string md5 = "";
  855. string filePreUrl = ConfigurationManager.AppSettings["UpdateFWPreUrl"];
  856. using (WebClient client = new WebClient())
  857. {
  858. client.UseDefaultCredentials = false;
  859. client.Headers.Add("Content-Type", "application/octet-stream");
  860. using (Stream fileStream = File.OpenRead(uxUploadFileTb.Text))
  861. {
  862. var _md5 = MD5.Create();
  863. var hash = _md5.ComputeHash(fileStream);
  864. md5 = BitConverter.ToString(hash).Replace("-", String.Empty).ToLowerInvariant();
  865. }
  866. }
  867. UploadFile ufObj = new UploadFile();
  868. ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
  869. ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
  870. ufObj.Id = Guid.NewGuid().ToString();
  871. ufObj.FileName = md5 + ufObj.FileExtensionName;
  872. ufObj.FilePath = "~/UploadFiles/Fw/" + ufObj.FileName;
  873. ufObj.FileSize = size;
  874. ufObj.FileMD5 = md5;
  875. ufObj.OriginName = System.IO.Path.GetFileName(uxUploadFileTb.Text);
  876. ufObj.FileUrl = new Uri(Properties.Settings.Default.UpdateFWPreUrl + ufObj.FilePath.Replace("~/", "")).ToString();
  877. ufObj.VendorId = "TestTool";
  878. ufObj.ModelName = "TestTool";
  879. ufObj.ModuleId = 0;
  880. using (var db = new MainDBContext())
  881. {
  882. db.UploadFile.Add(ufObj);
  883. db.SaveChanges();
  884. }
  885. string filePath = uxUploadFileTb.Text;
  886. uxMsgTb.Text = "Uploading........";
  887. Task.Run(async () =>
  888. {
  889. await UploadTask(filePath, ufObj.FileName);
  890. });
  891. }
  892. private async Task UploadTask(string filePath, string fileName)
  893. {
  894. bool uploadResult = UploadClient.FtpUploadBroken(filePath, @"ftp://ocpp.phihong.com.tw/" + fileName);
  895. await Dispatcher.BeginInvoke(new Action(() =>
  896. {
  897. if (uploadResult)
  898. {
  899. uxMsgTb.Text = "Current Progress :100 %";
  900. Thread.CurrentThread.Join(100);
  901. }
  902. uxMsgTb.Text = "Upload File Result :" + (uploadResult ? "Success" : "Fail");
  903. }));
  904. }
  905. private void UploadClient_OnUploadProgress(double percent)
  906. {
  907. Dispatcher.BeginInvoke(new Action(() =>
  908. {
  909. uxMsgTb.Text = "Current Progress :" + (int)percent + " %";
  910. }));
  911. }
  912. private void uxFTPUploadBtn_Click(object sender, RoutedEventArgs e)
  913. {
  914. if (string.IsNullOrEmpty(uxUploadFileTb.Text))
  915. {
  916. uxMsgTb.Text = "Please select upload file!";
  917. return;
  918. }
  919. FileInfo f = new FileInfo(uxUploadFileTb.Text);
  920. int size = (int)f.Length;
  921. string md5 = "";
  922. using (WebClient client = new WebClient())
  923. {
  924. client.UseDefaultCredentials = false;
  925. client.Headers.Add("Content-Type", "application/octet-stream");
  926. using (Stream fileStream = File.OpenRead(uxUploadFileTb.Text))
  927. {
  928. var _md5 = MD5.Create();
  929. var hash = _md5.ComputeHash(fileStream);
  930. md5 = BitConverter.ToString(hash).Replace("-", String.Empty).ToLowerInvariant();
  931. }
  932. }
  933. UploadFile ufObj = new UploadFile();
  934. ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
  935. ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
  936. ufObj.Id = Guid.NewGuid().ToString();
  937. ufObj.FileName = md5 + ufObj.FileExtensionName;
  938. ufObj.FilePath = "~/UploadFiles/Fw/" + ufObj.FileName;
  939. ufObj.FileSize = size;
  940. ufObj.FileMD5 = md5;
  941. ufObj.OriginName = System.IO.Path.GetFileName(uxUploadFileTb.Text);
  942. ufObj.FileUrl = new Uri(Properties.Settings.Default.FTPUpdateFWPreUrl + ufObj.FileName).ToString();
  943. ufObj.VendorId = "TestTool";
  944. ufObj.ModelName = "TestTool";
  945. ufObj.ModuleId = 0;
  946. using (var db = new MainDBContext())
  947. {
  948. db.UploadFile.Add(ufObj);
  949. db.SaveChanges();
  950. }
  951. string filePath = uxUploadFileTb.Text;
  952. uxMsgTb.Text = "Uploading........";
  953. Task.Run(async () =>
  954. {
  955. await UploadTask(filePath, ufObj.FileName);
  956. });
  957. }
  958. private void uxRefreshBtn_Click(object sender, RoutedEventArgs e)
  959. {
  960. using (var db = new MainDBContext())
  961. {
  962. publishes = db.UploadFile.OrderByDescending(c => c.CreatedOn).Take(20).ToList();
  963. StringBuilder sb = new StringBuilder();
  964. uxPublishCb.Items.Clear();
  965. foreach (var i in publishes)
  966. {
  967. string prefix = i.FileUrl.StartsWith("ftp") ? "FTP" : "HTTP";
  968. sb.Clear();
  969. sb.Append(string.Format("[{0}]", prefix));
  970. sb.Append("_上傳日期:");
  971. sb.Append(i.CreatedOn.ToString());
  972. sb.Append("_檔名:");
  973. sb.Append(i.OriginName);
  974. uxPublishCb.Items.Add(sb.ToString());
  975. uxPublishCb.SelectedIndex = 0;
  976. }
  977. }
  978. }
  979. private void uxPublishBtn_Click(object sender, RoutedEventArgs e)
  980. {
  981. if (selectedPublish < 0)
  982. {
  983. uxMsgTb.Text = "Please choose publish version!";
  984. return;
  985. }
  986. using (var db = new MainDBContext())
  987. {
  988. var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
  989. MachineVersionFile obj = new MachineVersionFile()
  990. {
  991. ChargeBoxId = uxChargeBoxIdTb.Text,
  992. UploadFileId = publishes[selectedPublish].Id,
  993. CreatedOn = DateTime.Now.ToUniversalTime()
  994. };
  995. db.MachineVersionFile.Add(obj);
  996. //將machine的軟體更新更新到這個值
  997. db.SaveChanges();
  998. machine.FW_AssignedVersion = obj.Id;
  999. db.SaveChanges();
  1000. }
  1001. uxMsgTb.Text = "Publish Complete";
  1002. }
  1003. private void uxPublishCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
  1004. {
  1005. selectedPublish = uxPublishCb.SelectedIndex;
  1006. }
  1007. private void uxClearPublishBtn_Click(object sender, RoutedEventArgs e)
  1008. {
  1009. using (var db = new MainDBContext())
  1010. {
  1011. var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
  1012. machine.FW_AssignedVersion = null;
  1013. db.SaveChanges();
  1014. }
  1015. uxMsgTb.Text = "Clear Publish";
  1016. }
  1017. private void uxChargeBoxIdTb_LostFocus(object sender, RoutedEventArgs e)
  1018. {
  1019. Properties.Settings.Default.ChargeBoxId = uxChargeBoxIdTb.Text;
  1020. Properties.Settings.Default.Save();
  1021. }
  1022. private string GetDestroyVersionData(string action)
  1023. {
  1024. string result = "";
  1025. try
  1026. {
  1027. string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, action + ".json");
  1028. var request = JsonConvert.DeserializeObject(File.ReadAllText(path));
  1029. result = JsonConvert.SerializeObject(request);
  1030. }
  1031. catch (Exception ex)
  1032. {
  1033. uxMsgTb.Text += "解析檔案發生問題 " + ex.ToString();
  1034. }
  1035. return result;
  1036. }
  1037. private void uxDestroyCb_Checked(object sender, RoutedEventArgs e)
  1038. {
  1039. isDestroyMode = true;
  1040. uxConnectorIdTb.IsEnabled = false;
  1041. uxReservationTb.IsEnabled = false;
  1042. uxIdTagTb.IsEnabled = false;
  1043. uxParentIdTagTb.IsEnabled = false;
  1044. uxTransactionIdTb.IsEnabled = false;
  1045. uxLocalListSizeTb.IsEnabled = false;
  1046. uxConfigKeyTb.IsEnabled = false;
  1047. uxConfigValueTb.IsEnabled = false;
  1048. uxExpiryTimeTb.IsEnabled = false;
  1049. }
  1050. private void uxDestroyCb_Unchecked(object sender, RoutedEventArgs e)
  1051. {
  1052. isDestroyMode = false;
  1053. uxConnectorIdTb.IsEnabled = true;
  1054. uxReservationTb.IsEnabled = true;
  1055. uxIdTagTb.IsEnabled = true;
  1056. uxParentIdTagTb.IsEnabled = true;
  1057. uxTransactionIdTb.IsEnabled = true;
  1058. uxLocalListSizeTb.IsEnabled = true;
  1059. uxConfigKeyTb.IsEnabled = true;
  1060. uxConfigValueTb.IsEnabled = true;
  1061. uxExpiryTimeTb.IsEnabled = true;
  1062. }
  1063. }
  1064. }