MainWindow.xaml.cs 33 KB

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