MainWindow.xaml.cs 40 KB

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