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 = 300
  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 uuid = Guid.NewGuid().ToString();
  427. var request = new SendLocalListRequest()
  428. {
  429. listVersion = Convert.ToInt32(DateTimeOffset.Now.AddDays(-50).ToUnixTimeSeconds()),
  430. updateType = isFull ? UpdateType.Full : UpdateType.Differential,
  431. localAuthorizationList = new List<AuthorizationData>()
  432. //localAuthorizationList = new List<AuthorizationData>()
  433. //{
  434. // new AuthorizationData()
  435. // {
  436. // idTagInfo=new IdTagInfo(){ expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status= AuthorizationStatus.Accepted},
  437. // idTag="F5902677"
  438. // }, new AuthorizationData()
  439. // {
  440. // idTagInfo=new IdTagInfo(){ expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status= AuthorizationStatus.Expired},
  441. // idTag="772690F5"
  442. // }
  443. //}
  444. };
  445. //request.localAuthorizationList.Add(new AuthorizationData()
  446. //{
  447. // idTag = "F5902677",
  448. // idTagInfo = new IdTagInfo()
  449. // {
  450. // parentIdTag = "0000000000000000001",
  451. // expiryDate = DateTime.UtcNow.AddMonths(1),
  452. // status = AuthorizationStatus.ConcurrentTx
  453. // }
  454. //});
  455. //request.localAuthorizationList.Add(new AuthorizationData()
  456. //{
  457. // idTag = "772690F5",
  458. // idTagInfo = new IdTagInfo()
  459. // {
  460. // parentIdTag = "0000000000000000001",
  461. // expiryDate = DateTime.UtcNow.AddMonths(1),
  462. // status = AuthorizationStatus.Accepted
  463. // }
  464. //});
  465. for (int i = 0; i < 50; i++)
  466. {
  467. request.localAuthorizationList.Add(new AuthorizationData()
  468. {
  469. idTag = DateTime.Now.ToString("yyyyMMddHHmmss" + i.ToString("00000")),
  470. idTagInfo = new IdTagInfo()
  471. {
  472. parentIdTag = "0000000000000000001",
  473. expiryDate = DateTime.UtcNow.AddMonths(1),
  474. status = AuthorizationStatus.Accepted
  475. }
  476. });
  477. }
  478. WritetoDB(uuid, request);
  479. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  480. }
  481. catch (Exception ex)
  482. {
  483. MessageBox.Show(ex.ToString());
  484. }
  485. }
  486. #endregion
  487. private void SetRemoteTrigger(string action)
  488. {
  489. try
  490. {
  491. string type = action.Split('_').Last();
  492. var uuid = Guid.NewGuid().ToString();
  493. var request = new TriggerMessageRequest()
  494. {
  495. requestedMessage = (MessageTrigger)Enum.Parse(typeof(MessageTrigger), type, false)
  496. };
  497. WritetoDB(uuid, request);
  498. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  499. }
  500. catch (Exception ex)
  501. {
  502. MessageBox.Show(ex.ToString());
  503. }
  504. }
  505. private void SetGetConfiguration()
  506. {
  507. try
  508. {
  509. string uuid = Guid.NewGuid().ToString();
  510. var request = new GetConfigurationRequest()
  511. {
  512. key = uxConfigKeyTb.Text.Split('/').ToList()
  513. };
  514. WritetoDB(uuid, request);
  515. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  516. }
  517. catch (Exception ex)
  518. {
  519. MessageBox.Show(ex.ToString());
  520. }
  521. }
  522. private void UxCmdCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
  523. {
  524. var item = uxCmdCb.SelectedValue as ComboBoxItem;
  525. action = item.Content as string;
  526. }
  527. private void SetRemoteStartTransaction(SetChargingProfileRequest csProfile = null)
  528. {
  529. try
  530. {
  531. var uuid = Guid.NewGuid().ToString();
  532. var request = new RemoteStartTransactionRequest()
  533. {
  534. connectorId = byte.Parse(uxConnectorIdTb.Text),
  535. idTag = uxIdTagTb.Text
  536. };
  537. if (csProfile != null)
  538. {
  539. request.chargingProfile = csProfile.csChargingProfiles;
  540. }
  541. WritetoDB(uuid, request);
  542. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  543. }
  544. catch (Exception ex)
  545. {
  546. MessageBox.Show(ex.ToString());
  547. }
  548. }
  549. private void SetUnlockConnector()
  550. {
  551. try
  552. {
  553. var uuid = Guid.NewGuid().ToString();
  554. var request = new UnlockConnectorRequest()
  555. {
  556. connectorId = byte.Parse(uxConnectorIdTb.Text),
  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 SetChangeAvailability_Inoperative()
  567. {
  568. try
  569. {
  570. var uuid = Guid.NewGuid().ToString();
  571. var request = new ChangeAvailabilityRequest()
  572. {
  573. connectorId = byte.Parse(uxConnectorIdTb.Text),
  574. type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Inoperative
  575. };
  576. WritetoDB(uuid, request);
  577. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  578. }
  579. catch (Exception ex)
  580. {
  581. MessageBox.Show(ex.ToString());
  582. }
  583. }
  584. private void SetChangeAvailability_Operative()
  585. {
  586. try
  587. {
  588. var uuid = Guid.NewGuid().ToString();
  589. var request = new ChangeAvailabilityRequest()
  590. {
  591. connectorId = byte.Parse(uxConnectorIdTb.Text),
  592. type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Operative
  593. };
  594. WritetoDB(uuid, request);
  595. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  596. }
  597. catch (Exception ex)
  598. {
  599. MessageBox.Show(ex.ToString());
  600. }
  601. }
  602. private void SetChangeConfiguration()
  603. {
  604. try
  605. {
  606. var uuid = Guid.NewGuid().ToString();
  607. var request = new ChangeConfigurationRequest()
  608. {
  609. key = uxConfigKeyTb.Text,
  610. value = uxConfigValueTb.Text,
  611. };
  612. WritetoDB(uuid, request);
  613. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  614. }
  615. catch (Exception ex)
  616. {
  617. MessageBox.Show(ex.ToString());
  618. }
  619. }
  620. private void SetClearCache()
  621. {
  622. try
  623. {
  624. var uuid = Guid.NewGuid().ToString();
  625. var request = new ClearCacheRequest()
  626. {
  627. };
  628. WritetoDB(uuid, request);
  629. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  630. }
  631. catch (Exception ex)
  632. {
  633. MessageBox.Show(ex.ToString());
  634. }
  635. }
  636. private void SetGetConfiguration_ALL()
  637. {
  638. try
  639. {
  640. var uuid = Guid.NewGuid().ToString();
  641. var request = new GetConfigurationRequest()
  642. {
  643. key = new List<string>() { }
  644. };
  645. WritetoDB(uuid, request);
  646. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  647. }
  648. catch (Exception ex)
  649. {
  650. MessageBox.Show(ex.ToString());
  651. }
  652. }
  653. private void SetHardReset()
  654. {
  655. try
  656. {
  657. var uuid = Guid.NewGuid().ToString();
  658. var request = new ResetRequest()
  659. {
  660. type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Hard
  661. };
  662. WritetoDB(uuid, request);
  663. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  664. }
  665. catch (Exception ex)
  666. {
  667. MessageBox.Show(ex.ToString());
  668. }
  669. }
  670. private void SetSoftReset()
  671. {
  672. try
  673. {
  674. var uuid = Guid.NewGuid().ToString();
  675. var request = new ResetRequest()
  676. {
  677. type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Soft
  678. };
  679. WritetoDB(uuid, request);
  680. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  681. }
  682. catch (Exception ex)
  683. {
  684. MessageBox.Show(ex.ToString());
  685. }
  686. }
  687. private void SetRemoteStopTransaction()
  688. {
  689. try
  690. {
  691. var uuid = Guid.NewGuid().ToString();
  692. var request = new RemoteStopTransactionRequest()
  693. {
  694. transactionId = int.Parse(uxTransactionIdTb.Text)
  695. };
  696. WritetoDB(uuid, request);
  697. uxMsgTb.Text = string.Format("UUID:{0}", uuid);
  698. }
  699. catch (Exception ex)
  700. {
  701. MessageBox.Show(ex.ToString());
  702. }
  703. }
  704. private void WritetoDB(string uuid, IRequest request)
  705. {
  706. using (var db = new MainDBContext())
  707. {
  708. db.MachineOperateRecord.Add(new MachineOperateRecord()
  709. {
  710. CreatedOn = DateTime.Now.ToUniversalTime(),
  711. ChargeBoxId = uxChargeBoxIdTb.Text,
  712. SerialNo = uuid,
  713. RequestContent = JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  714. EVSE_Status = 0,
  715. Status = 0,
  716. RequestType = 1,
  717. Action = request.Action.ToString()
  718. });
  719. db.ServerMessage.Add(new ServerMessage()
  720. {
  721. ChargeBoxId = uxChargeBoxIdTb.Text,
  722. CreatedBy = "TestTool",
  723. CreatedOn = DateTime.Now.ToUniversalTime(),
  724. OutAction = request.Action.ToString(),
  725. OutRequest = JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  726. SerialNo = uuid,
  727. InMessage = string.Empty
  728. });
  729. db.SaveChanges();
  730. }
  731. }
  732. private void uxFileSubmitBtn_Click(object sender, RoutedEventArgs e)
  733. {
  734. OpenFileDialog openFileDialog = new OpenFileDialog();
  735. openFileDialog.Title = "Select file";
  736. var result = openFileDialog.ShowDialog();
  737. if (result == true)
  738. {
  739. uxUploadFileTb.Text = openFileDialog.FileName;
  740. }
  741. }
  742. private void uxUploadBtn_Click(object sender, RoutedEventArgs e)
  743. {
  744. if (string.IsNullOrEmpty(uxUploadFileTb.Text))
  745. {
  746. uxMsgTb.Text = "Please select upload file!";
  747. return;
  748. }
  749. FileInfo f = new FileInfo(uxUploadFileTb.Text);
  750. int size = (int)f.Length;
  751. string md5 = "";
  752. string filePreUrl = ConfigurationManager.AppSettings["FilePreUrl"];
  753. using (WebClient client = new WebClient())
  754. {
  755. client.UseDefaultCredentials = false;
  756. client.Headers.Add("Content-Type", "application/octet-stream");
  757. using (Stream fileStream = File.OpenRead(uxUploadFileTb.Text))
  758. {
  759. var _md5 = MD5.Create();
  760. var hash = _md5.ComputeHash(fileStream);
  761. md5 = BitConverter.ToString(hash).Replace("-", String.Empty).ToLowerInvariant();
  762. }
  763. }
  764. UploadFile ufObj = new UploadFile();
  765. ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
  766. ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
  767. ufObj.Id = Guid.NewGuid().ToString();
  768. ufObj.FileName = md5 + ufObj.FileExtensionName;
  769. ufObj.FilePath = "~/UploadFiles/Fw/" + ufObj.FileName;
  770. ufObj.FileSize = size;
  771. ufObj.FileMD5 = md5;
  772. ufObj.OriginName = System.IO.Path.GetFileName(uxUploadFileTb.Text);
  773. ufObj.FileUrl = new Uri(Properties.Settings.Default.FilePreUrl + ufObj.FilePath.Replace("~/", "")).ToString();
  774. ufObj.VendorId = "TestTool";
  775. ufObj.ModelName= "TestTool";
  776. ufObj.ModuleId = 0;
  777. using (var db = new MainDBContext())
  778. {
  779. db.UploadFile.Add(ufObj);
  780. db.SaveChanges();
  781. }
  782. string filePath = uxUploadFileTb.Text;
  783. uxMsgTb.Text = "Uploading........";
  784. Task.Run(async () =>
  785. {
  786. await UploadTask(filePath, ufObj.FileName);
  787. });
  788. }
  789. private async Task UploadTask(string filePath, string fileName)
  790. {
  791. bool uploadResult = UploadClient.FtpUploadBroken(filePath, @"ftp://test.evsocket.phihong.com.cn/" + fileName);
  792. await Dispatcher.BeginInvoke(new Action(() =>
  793. {
  794. if (uploadResult)
  795. {
  796. uxMsgTb.Text = "Current Progress :100 %";
  797. Thread.CurrentThread.Join(100);
  798. }
  799. uxMsgTb.Text = "Upload File Result :" + (uploadResult ? "Success" : "Fail");
  800. }));
  801. }
  802. private void UploadClient_OnUploadProgress(double percent)
  803. {
  804. Dispatcher.BeginInvoke(new Action(() =>
  805. {
  806. uxMsgTb.Text = "Current Progress :" + (int)percent + " %";
  807. }));
  808. }
  809. private void uxFTPUploadBtn_Click(object sender, RoutedEventArgs e)
  810. {
  811. if (string.IsNullOrEmpty(uxUploadFileTb.Text))
  812. {
  813. uxMsgTb.Text = "Please select upload file!";
  814. return;
  815. }
  816. FileInfo f = new FileInfo(uxUploadFileTb.Text);
  817. int size = (int)f.Length;
  818. string md5 = "";
  819. using (WebClient client = new WebClient())
  820. {
  821. client.UseDefaultCredentials = false;
  822. client.Headers.Add("Content-Type", "application/octet-stream");
  823. using (Stream fileStream = File.OpenRead(uxUploadFileTb.Text))
  824. {
  825. var _md5 = MD5.Create();
  826. var hash = _md5.ComputeHash(fileStream);
  827. md5 = BitConverter.ToString(hash).Replace("-", String.Empty).ToLowerInvariant();
  828. }
  829. }
  830. UploadFile ufObj = new UploadFile();
  831. ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
  832. ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
  833. ufObj.Id = Guid.NewGuid().ToString();
  834. ufObj.FileName = md5 + ufObj.FileExtensionName;
  835. ufObj.FilePath = "~/UploadFiles/Fw/" + ufObj.FileName;
  836. ufObj.FileSize = size;
  837. ufObj.FileMD5 = md5;
  838. ufObj.OriginName = System.IO.Path.GetFileName(uxUploadFileTb.Text);
  839. ufObj.FileUrl = new Uri(Properties.Settings.Default.FTPFilePreUrl + ufObj.FileName).ToString();
  840. ufObj.VendorId = "TestTool";
  841. ufObj.ModelName = "TestTool";
  842. ufObj.ModuleId = 0;
  843. using (var db = new MainDBContext())
  844. {
  845. db.UploadFile.Add(ufObj);
  846. db.SaveChanges();
  847. }
  848. string filePath = uxUploadFileTb.Text;
  849. uxMsgTb.Text = "Uploading........";
  850. Task.Run(async () =>
  851. {
  852. await UploadTask(filePath, ufObj.FileName);
  853. });
  854. }
  855. private void uxRefreshBtn_Click(object sender, RoutedEventArgs e)
  856. {
  857. using (var db = new MainDBContext())
  858. {
  859. publishes = db.UploadFile.OrderByDescending(c => c.CreatedOn).Take(20).ToList();
  860. StringBuilder sb = new StringBuilder();
  861. uxPublishCb.Items.Clear();
  862. foreach (var i in publishes)
  863. {
  864. string prefix = i.FileUrl.StartsWith("ftp") ? "FTP" : "HTTP";
  865. sb.Clear();
  866. sb.Append(string.Format("[{0}]", prefix));
  867. sb.Append("_上傳日期:");
  868. sb.Append(i.CreatedOn.ToString());
  869. sb.Append("_檔名:");
  870. sb.Append(i.OriginName);
  871. uxPublishCb.Items.Add(sb.ToString());
  872. uxPublishCb.SelectedIndex = 0;
  873. }
  874. }
  875. }
  876. private void uxPublishBtn_Click(object sender, RoutedEventArgs e)
  877. {
  878. if (selectedPublish < 0)
  879. {
  880. uxMsgTb.Text = "Please choose publish version!";
  881. return;
  882. }
  883. using (var db = new MainDBContext())
  884. {
  885. var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
  886. MachineVersionFile obj = new MachineVersionFile()
  887. {
  888. ChargeBoxId = uxChargeBoxIdTb.Text,
  889. UploadFileId = publishes[selectedPublish].Id,
  890. CreatedOn = DateTime.Now.ToUniversalTime()
  891. };
  892. db.MachineVersionFile.Add(obj);
  893. //將machine的軟體更新更新到這個值
  894. db.SaveChanges();
  895. machine.FW_AssignedVersion = obj.Id;
  896. db.SaveChanges();
  897. }
  898. uxMsgTb.Text = "Publish Complete";
  899. }
  900. private void uxPublishCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
  901. {
  902. selectedPublish = uxPublishCb.SelectedIndex;
  903. }
  904. private void uxClearPublishBtn_Click(object sender, RoutedEventArgs e)
  905. {
  906. using (var db = new MainDBContext())
  907. {
  908. var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
  909. machine.FW_AssignedVersion = null;
  910. db.SaveChanges();
  911. }
  912. uxMsgTb.Text = "Clear Publish";
  913. }
  914. private void uxChargeBoxIdTb_LostFocus(object sender, RoutedEventArgs e)
  915. {
  916. Properties.Settings.Default.ChargeBoxId = uxChargeBoxIdTb.Text;
  917. Properties.Settings.Default.Save();
  918. }
  919. }
  920. }