MainWindow.xaml.cs 34 KB

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