MainWindow.xaml.cs 42 KB

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