MainWindow.xaml.cs 35 KB

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