1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207 |
- using EVCB_OCPP.Domain;
- using EVCB_OCPP.Domain.Models.Database;
- using EVCB_OCPP.Packet.Features;
- using EVCB_OCPP.Packet.Messages;
- using EVCB_OCPP.Packet.Messages.Core;
- using Microsoft.Win32;
- using Newtonsoft.Json;
- using OCPPPackage.Profiles;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Security.Cryptography;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- using System.Data.Entity;
- using EVCB_OCPP.Packet.Messages.RemoteTrigger;
- using EVCB_OCPP.Packet.Messages.SubTypes;
- using EVCB_OCPP.Packet.Messages.LocalAuthListManagement;
- using EVCB_OCPP.Packet.Messages.FirmwareManagement;
- using EVCB_OCPP.Packet.Messages.Reservation;
- using EVCB_OCPP.Packet.Messages.SmartCharging;
- using System.Threading;
- using System.Net.Http;
- using Newtonsoft.Json.Converters;
- namespace TestTool.RemoteTriggerAPP
- {
- /// <summary>
- /// MainWindow.xaml 的互動邏輯
- /// </summary>
- public partial class MainWindow : Window
- {
- string action = "";
- List<UploadFile> publishes = new List<UploadFile>();
- string chargingProfilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SetChargingProfile.json");
- string dataTransferPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataTransfer.json");
- int selectedPublish = -1;
- bool isDestroyMode = false;
- public MainWindow()
- {
- InitializeComponent();
- Loaded += MainWindow_Loaded;
- }
- private void MainWindow_Loaded(object sender, RoutedEventArgs e)
- {
- uxChargeBoxIdTb.Text = Properties.Settings.Default.ChargeBoxId;
- }
- private void UxSubmitBtn_Click(object sender, RoutedEventArgs e)
- {
- if (isDestroyMode)
- {
- try
- {
- string actualAction = action.Split(new char[] { '_', '(' })[0];
- var uuid = Guid.NewGuid().ToString();
- WritetoDB(uuid, null, actualAction, GetDestroyVersionData(actualAction));
- uxMsgTb.Text = string.Format("Send Actions: {0} UUID:{1}", actualAction, uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- else
- {
- switch (action)
- {
- #region Core Profile
- case "ChangeAvailability_Inoperative":
- {
- SetChangeAvailability_Inoperative();
- }
- break;
- case "ChangeAvailability_Operative":
- {
- SetChangeAvailability_Operative();
- }
- break;
- case "DataTransfer":
- {
- var request = VerifyDataTransfer(dataTransferPath);
- SetDataTransfer(request);
- }
- break;
- case "GetConfiguration":
- {
- if (uxConfigKeyTb.Text == "")
- {
- SetGetConfiguration_ALL();
- }
- else
- {
- SetGetConfiguration();
- }
- }
- break;
- case "ChangeConfiguration":
- {
- SetChangeConfiguration();
- }
- break;
- case "ClearCache":
- {
- SetClearCache();
- }
- break;
- case "RemoteStartTransaction":
- {
- SetRemoteStartTransaction();
- }
- break;
- case "RemoteStartTransaction_ChargingProfile":
- {
- var chargingProfile = VerifyChargingProfile(chargingProfilePath);
- if (chargingProfile != null)
- {
- SetRemoteStartTransaction(chargingProfile);
- }
- else
- {
- uxMsgTb.Text = "Please check chargingProfile.json exist in " + AppDomain.CurrentDomain.BaseDirectory;
- }
- }
- break;
- case "RemoteStopTransaction":
- {
- SetRemoteStopTransaction();
- }
- break;
- case "Reset_HardReset":
- {
- SetHardReset();
- }
- break;
- case "Reset_SoftReset":
- {
- SetSoftReset();
- }
- break;
- case "UnlockConnector":
- {
- SetUnlockConnector();
- }
- break;
- #endregion
- #region Local Authorization
- case "GetLocalListVersion":
- {
- GetLocalListVersion();
- }
- break;
- case "SendLocalList_Full":
- {
- SendLocalAuthorizationList(true);
- }
- break;
- case "SendLocalList_Diff":
- {
- SendLocalAuthorizationList(false);
- }
- break;
- #endregion
- case "GetDiagnostics_FTP":
- {
- GetDiagnostics(true);
- }
- break;
- case "GetDiagnostics_HTTP":
- {
- GetDiagnostics(false);
- }
- break;
- case "ReserveNow":
- {
- ReserveNow();
- }
- break;
- case "CancelReservation":
- {
- CancelReservation();
- }
- break;
- case "ClearChargingProfile":
- {
- ClearChargingProfile();
- }
- break;
- case "GetCompositeSchedule":
- {
- GetCompositeSchedule();
- }
- break;
- case "SetChargingProfile":
- {
- var chargingProfile = VerifyChargingProfile(chargingProfilePath);
- if (chargingProfile != null)
- {
- SetChargingProfile(chargingProfile);
- }
- else
- {
- uxMsgTb.Text = "Please check chargingProfile.json exist in " + AppDomain.CurrentDomain.BaseDirectory;
- }
- //SetChargingProfile(new SetChargingProfileRequest()
- //{
- // connectorId = 0,
- // csChargingProfiles = new csChargingProfiles()
- // {
- // chargingProfileId = 1,
- // chargingProfileKind = ChargingProfileKindType.Recurring,
- // chargingProfilePurpose = ChargingProfilePurposeType.ChargePointMaxProfile,
- // chargingSchedule = new ChargingSchedule()
- // {
- // chargingRateUnit = ChargingRateUnitType.W,
- // chargingSchedulePeriod = new List<ChargingSchedulePeriod>()
- // {
- // new ChargingSchedulePeriod(){ startPeriod=0, limit=int.Parse(uxConfigValueTb.Text)}
- // },
- // },
- // recurrencyKind = RecurrencyKindType.Daily,
- // stackLevel = 1,
- // }
- //});
- }
- break;
- #region Trigger Profile
- case "TriggerMessage_BootNotification":
- case "TriggerMessage_DiagnosticsStatusNotification":
- case "TriggerMessage_FirmwareStatusNotification":
- case "TriggerMessage_Heartbeat":
- case "TriggerMessage_MeterValues":
- case "TriggerMessage_StatusNotification":
- {
- SetRemoteTrigger(action);
- }
- break;
- #endregion
- default:
- break;
- }
- }
- }
- private void SetDataTransfer(DataTransferRequest request)
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private DataTransferRequest VerifyDataTransfer(string path)
- {
- DataTransferRequest request = null;
- if (!File.Exists(path)) return request;
- try
- {
- request = JsonConvert.DeserializeObject<DataTransferRequest>(File.ReadAllText(path));
- }
- catch
- {
- }
- return request;
- }
- private SetChargingProfileRequest VerifyChargingProfile(string path)
- {
- SetChargingProfileRequest request = null;
- if (!File.Exists(path)) return request;
- try
- {
- request = JsonConvert.DeserializeObject<SetChargingProfileRequest>(File.ReadAllText(path));
- }
- catch
- {
- }
- return request;
- }
- private void SetChargingProfile(SetChargingProfileRequest csProfile)
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- WritetoDB(uuid, csProfile);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void GetCompositeSchedule()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new GetCompositeScheduleRequest()
- {
- connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
- duration = 10000
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void ClearChargingProfile()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new ClearChargingProfileRequest()
- {
- connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void CancelReservation()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new CancelReservationRequest()
- {
- reservationId = Convert.ToInt32(uxReservationTb.Text),
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SetWrongAction()
- {
- bool isError = false;
- DateTime expiryTime = DateTime.Now;
- try
- {
- try
- {
- expiryTime = Convert.ToDateTime(uxExpiryTimeTb.Text);
- //if (expiryTime < DateTime.Now.AddSeconds(60))
- //{
- // isError = true;
- // uxMsgTb.Text = string.Format("ExpiryTime is too close or too early to the current time (60 seconds).");
- //}
- }
- catch (Exception ex)
- {
- if (ex is FormatException)
- {
- isError = true;
- uxMsgTb.Text = string.Format("ExpiryTime's Format is wrong Example:{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
- }
- }
- if (!isError)
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new ReserveNowRequest()
- {
- connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
- expiryDate = expiryTime.ToUniversalTime(),
- idTag = uxIdTagTb.Text,
- parentIdTag = "PTAG",
- reservationId = Convert.ToInt32(expiryTime.ToUniversalTime().ToString("yyMMddHHmm")),
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void ReserveNow()
- {
- bool isError = false;
- DateTime expiryTime = DateTime.Now;
- try
- {
- try
- {
- expiryTime = Convert.ToDateTime(uxExpiryTimeTb.Text);
- //if (expiryTime < DateTime.Now.AddSeconds(60))
- //{
- // isError = true;
- // uxMsgTb.Text = string.Format("ExpiryTime is too close or too early to the current time (60 seconds).");
- //}
- }
- catch (Exception ex)
- {
- if (ex is FormatException)
- {
- isError = true;
- uxMsgTb.Text = string.Format("ExpiryTime's Format is wrong Example:{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
- }
- }
- if (!isError)
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new ReserveNowRequest()
- {
- connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
- expiryDate = expiryTime.ToUniversalTime(),
- idTag = uxIdTagTb.Text,
- parentIdTag = "PTAG",
- reservationId = Convert.ToInt32(expiryTime.ToUniversalTime().ToString("MMddHHmm")),
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void GetDiagnostics(bool ftp)
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new GetDiagnosticsRequest()
- {
- location = new Uri(ftp ? Properties.Settings.Default.FTPGetDiagnosticsPreUrl : Properties.Settings.Default.GetDiagnosticsPreUrl),
- retries = 1,
- retryInterval = 30,
- startTime = DateTime.Now.AddHours(-1).ToUniversalTime(),
- stopTime = DateTime.Now.ToUniversalTime()
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- #region Local Authorization
- private void GetLocalListVersion()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new GetLocalListVersionRequest()
- {
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SendLocalAuthorizationList(bool isFull)
- {
- try
- {
- var size = Convert.ToInt32(uxLocalListSizeTb.Text);
- var uuid = Guid.NewGuid().ToString();
- var request = new SendLocalListRequest()
- {
- listVersion = Convert.ToInt32(DateTimeOffset.Now.AddDays(-50).ToUnixTimeSeconds()),
- updateType = isFull ? UpdateType.Full : UpdateType.Differential,
- localAuthorizationList = new List<AuthorizationData>()
- //localAuthorizationList = new List<AuthorizationData>()
- //{
- // new AuthorizationData()
- // {
- // idTagInfo=new IdTagInfo(){ expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status= AuthorizationStatus.Accepted},
- // idTag="F5902677"
- // }, new AuthorizationData()
- // {
- // idTagInfo=new IdTagInfo(){ expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status= AuthorizationStatus.Expired},
- // idTag="772690F5"
- // }
- //}
- };
- //request.localAuthorizationList.Add(new AuthorizationData()
- //{
- // idTag = "F5902677",
- // idTagInfo = new IdTagInfo()
- // {
- // parentIdTag = "0000000000000000001",
- // expiryDate = DateTime.UtcNow.AddMonths(1),
- // status = AuthorizationStatus.ConcurrentTx
- // }
- //});
- for (int i = 0; i < size; i++)
- {
- request.localAuthorizationList.Add(new AuthorizationData()
- {
- idTag = DateTime.Now.ToString("yyyyMMddHHmmss" + i.ToString("00000")),
- idTagInfo = new IdTagInfo()
- {
- parentIdTag = "0000000000000000001",
- expiryDate = DateTime.UtcNow.AddMonths(1),
- status = AuthorizationStatus.Accepted
- }
- });
- }
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- #endregion
- private void SetRemoteTrigger(string action)
- {
- try
- {
- string type = action.Split('_').Last();
- var uuid = Guid.NewGuid().ToString();
- var request = new TriggerMessageRequest()
- {
- requestedMessage = (MessageTrigger)Enum.Parse(typeof(MessageTrigger), type, false)
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SetGetConfiguration()
- {
- try
- {
- string uuid = Guid.NewGuid().ToString();
- var request = new GetConfigurationRequest()
- {
- key = uxConfigKeyTb.Text.Split('/').ToList()
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void UxCmdCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- var item = uxCmdCb.SelectedValue as ComboBoxItem;
- action = item.Content as string;
- }
- private void SetRemoteStartTransaction(SetChargingProfileRequest csProfile = null)
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new RemoteStartTransactionRequest()
- {
- connectorId = int.Parse(uxConnectorIdTb.Text),
- idTag = uxIdTagTb.Text
- };
- if (csProfile != null)
- {
- request.chargingProfile = csProfile.csChargingProfiles;
- }
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SetUnlockConnector()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new UnlockConnectorRequest()
- {
- connectorId = int.Parse(uxConnectorIdTb.Text),
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SetChangeAvailability_Inoperative()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new ChangeAvailabilityRequest()
- {
- connectorId = int.Parse(uxConnectorIdTb.Text),
- type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Inoperative
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SetChangeAvailability_Operative()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new ChangeAvailabilityRequest()
- {
- connectorId = int.Parse(uxConnectorIdTb.Text),
- type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Operative
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SetChangeConfiguration()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new ChangeConfigurationRequest()
- {
- key = uxConfigKeyTb.Text,
- value = uxConfigValueTb.Text,
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SetClearCache()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new ClearCacheRequest()
- {
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SetGetConfiguration_ALL()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new GetConfigurationRequest()
- {
- key = new List<string>() { }
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SetHardReset()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new ResetRequest()
- {
- type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Hard
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SetSoftReset()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new ResetRequest()
- {
- type = EVCB_OCPP.Packet.Messages.SubTypes.ResetType.Soft
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void SetRemoteStopTransaction()
- {
- try
- {
- var uuid = Guid.NewGuid().ToString();
- var request = new RemoteStopTransactionRequest()
- {
- transactionId = int.Parse(uxTransactionIdTb.Text)
- };
- WritetoDB(uuid, request);
- uxMsgTb.Text = string.Format("UUID:{0}", uuid);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- private void WritetoDB(string uuid, IRequest request, string action = "", string destroyData = "")
- {
- using (var db = new MainDBContext())
- {
- db.MachineOperateRecord.Add(new MachineOperateRecord()
- {
- CreatedOn = DateTime.Now.ToUniversalTime(),
- ChargeBoxId = uxChargeBoxIdTb.Text,
- SerialNo = uuid,
- RequestContent = !string.IsNullOrEmpty(destroyData) ? destroyData : JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
- EVSE_Status = 0,
- Status = 0,
- RequestType = 1,
- Action = !string.IsNullOrEmpty(destroyData) ? action : request.Action.ToString()
- });
- db.ServerMessage.Add(new ServerMessage()
- {
- ChargeBoxId = uxChargeBoxIdTb.Text,
- CreatedBy = !string.IsNullOrEmpty(destroyData) ? "Destroyer" : "TestTool",
- CreatedOn = DateTime.Now.ToUniversalTime(),
- OutAction = !string.IsNullOrEmpty(destroyData) ? action : request.Action.ToString(),
- OutRequest = !string.IsNullOrEmpty(destroyData) ? destroyData : JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
- SerialNo = uuid,
- InMessage = string.Empty
- });
- db.SaveChanges();
- }
- }
- private void uxFileSubmitBtn_Click(object sender, RoutedEventArgs e)
- {
- OpenFileDialog openFileDialog = new OpenFileDialog();
- openFileDialog.Title = "Select file";
- var result = openFileDialog.ShowDialog();
- if (result == true)
- {
- uxUploadFileTb.Text = openFileDialog.FileName;
- }
- }
- private void uxUploadBtn_Click(object sender, RoutedEventArgs e)
- {
- if (string.IsNullOrEmpty(uxUploadFileTb.Text))
- {
- uxMsgTb.Text = "Please select upload file!";
- return;
- }
- string filePath = uxUploadFileTb.Text;
- Task.Run(async () =>
- {
- await UploadTask(filePath, false);
- });
- }
- private async Task UploadTask(string filepath, bool isFTP)
- {
- try
- {
- await Dispatcher.BeginInvoke(new Action(() =>
- {
- uxMsgTb.Text = "Uploading........";
- }));
- FileInfo f = new FileInfo(filepath);
- int size = (int)f.Length;
- string fileMD5 = ""; //get file md5
- using (var md5 = MD5.Create())
- {
- using (var stream = File.OpenRead(filepath))
- {
- fileMD5 = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", String.Empty).ToLower();
- }
- }
- string filePreUrl = isFTP ? Properties.Settings.Default.FTPUpdateFWPreUrl : Properties.Settings.Default.UpdateFWPreUrl;
- UploadFile ufObj = new UploadFile();
- ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
- ufObj.FileExtensionName = System.IO.Path.GetExtension(filepath);
- ufObj.Id = Guid.NewGuid().ToString();
- ufObj.FileName = fileMD5 + System.IO.Path.GetExtension(filepath);
- ufObj.FilePath = isFTP ? "~/" + ufObj.FileName : "~/UploadFiles/FW/" + ufObj.FileName;
- ufObj.FileSize = size;
- ufObj.FileMD5 = fileMD5;
- ufObj.OriginName = System.IO.Path.GetFileName(filepath);
- ufObj.FileUrl = new Uri(filePreUrl + ufObj.FilePath.Replace("~/", "")).ToString();
- ufObj.VendorId = "TestTool";
- ufObj.ModelName = "TestTool";
- ufObj.ModuleId = 0;
- using (var db = new MainDBContext())
- {
- db.UploadFile.Add(ufObj);
- await db.SaveChangesAsync();
- }
- FluentFTPClient ftpClient = new FluentFTPClient("ocpp.phihong.com.tw", 5002, "testocpp", "testocpp", "/");
- //Properties.Settings.Default.UpdateFWPreUrl
- bool uploadResult = await ftpClient.UploadFileAsync(filepath, ufObj.FileName);
- await Dispatcher.BeginInvoke(new Action(() =>
- {
- if (uploadResult)
- {
- uxMsgTb.Text = "Current Progress :100 %";
- Thread.CurrentThread.Join(100);
- }
- uxMsgTb.Text = "Upload File Result :" + (uploadResult ? "Success" : "Fail");
- }));
- }
- catch (Exception ex)
- {
- }
- }
- private void uxFTPUploadBtn_Click(object sender, RoutedEventArgs e)
- {
- if (string.IsNullOrEmpty(uxUploadFileTb.Text))
- {
- uxMsgTb.Text = "Please select upload file!";
- return;
- }
- FileInfo f = new FileInfo(uxUploadFileTb.Text);
- int size = (int)f.Length;
- string md5 = "";
- using (WebClient client = new WebClient())
- {
- client.UseDefaultCredentials = false;
- client.Headers.Add("Content-Type", "application/octet-stream");
- using (Stream fileStream = File.OpenRead(uxUploadFileTb.Text))
- {
- var _md5 = MD5.Create();
- var hash = _md5.ComputeHash(fileStream);
- md5 = BitConverter.ToString(hash).Replace("-", String.Empty).ToLowerInvariant();
- }
- }
- UploadFile ufObj = new UploadFile();
- ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
- ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
- ufObj.Id = Guid.NewGuid().ToString();
- ufObj.FileName = md5 + ufObj.FileExtensionName;
- ufObj.FilePath = "~/UploadFiles/Fw/" + ufObj.FileName;
- ufObj.FileSize = size;
- ufObj.FileMD5 = md5;
- ufObj.OriginName = System.IO.Path.GetFileName(uxUploadFileTb.Text);
- ufObj.FileUrl = new Uri(Properties.Settings.Default.FTPUpdateFWPreUrl + ufObj.FileName).ToString();
- ufObj.VendorId = "TestTool";
- ufObj.ModelName = "TestTool";
- ufObj.ModuleId = 0;
- using (var db = new MainDBContext())
- {
- db.UploadFile.Add(ufObj);
- db.SaveChanges();
- }
- string filePath = uxUploadFileTb.Text;
- uxMsgTb.Text = "Uploading........";
- Task.Run(async () =>
- {
- await UploadTask(filePath, true);
- });
- }
- private void uxRefreshBtn_Click(object sender, RoutedEventArgs e)
- {
- using (var db = new MainDBContext())
- {
- publishes = db.UploadFile.OrderByDescending(c => c.CreatedOn).Take(20).ToList();
- StringBuilder sb = new StringBuilder();
- uxPublishCb.Items.Clear();
- foreach (var i in publishes)
- {
- string prefix = i.FileUrl.StartsWith("ftp") ? "FTP" : "HTTP";
- sb.Clear();
- sb.Append(string.Format("[{0}]", prefix));
- sb.Append("_上傳日期:");
- sb.Append(i.CreatedOn.ToString());
- sb.Append("_檔名:");
- sb.Append(i.OriginName);
- uxPublishCb.Items.Add(sb.ToString());
- uxPublishCb.SelectedIndex = 0;
- }
- }
- }
- private void uxPublishBtn_Click(object sender, RoutedEventArgs e)
- {
- if (selectedPublish < 0)
- {
- uxMsgTb.Text = "Please choose publish version!";
- return;
- }
- using (var db = new MainDBContext())
- {
- var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
- MachineVersionFile obj = new MachineVersionFile()
- {
- ChargeBoxId = uxChargeBoxIdTb.Text,
- UploadFileId = publishes[selectedPublish].Id,
- CreatedOn = DateTime.Now.ToUniversalTime()
- };
- db.MachineVersionFile.Add(obj);
- //將machine的軟體更新更新到這個值
- db.SaveChanges();
- machine.FW_AssignedVersion = obj.Id;
- db.SaveChanges();
- }
- uxMsgTb.Text = "Publish Complete";
- }
- private void uxPublishCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- selectedPublish = uxPublishCb.SelectedIndex;
- }
- private void uxClearPublishBtn_Click(object sender, RoutedEventArgs e)
- {
- using (var db = new MainDBContext())
- {
- var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
- machine.FW_AssignedVersion = null;
- db.SaveChanges();
- }
- uxMsgTb.Text = "Clear Publish";
- }
- private void uxChargeBoxIdTb_LostFocus(object sender, RoutedEventArgs e)
- {
- Properties.Settings.Default.ChargeBoxId = uxChargeBoxIdTb.Text;
- Properties.Settings.Default.Save();
- }
- private string GetDestroyVersionData(string action)
- {
- string result = "";
- try
- {
- string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, action + ".json");
- var request = JsonConvert.DeserializeObject(File.ReadAllText(path));
- result = JsonConvert.SerializeObject(request);
- }
- catch (Exception ex)
- {
- uxMsgTb.Text += "解析檔案發生問題 " + ex.ToString();
- }
- return result;
- }
- private void uxDestroyCb_Checked(object sender, RoutedEventArgs e)
- {
- isDestroyMode = true;
- uxConnectorIdTb.IsEnabled = false;
- uxReservationTb.IsEnabled = false;
- uxIdTagTb.IsEnabled = false;
- uxParentIdTagTb.IsEnabled = false;
- uxTransactionIdTb.IsEnabled = false;
- uxLocalListSizeTb.IsEnabled = false;
- uxConfigKeyTb.IsEnabled = false;
- uxConfigValueTb.IsEnabled = false;
- uxExpiryTimeTb.IsEnabled = false;
- }
- private void uxDestroyCb_Unchecked(object sender, RoutedEventArgs e)
- {
- isDestroyMode = false;
- uxConnectorIdTb.IsEnabled = true;
- uxReservationTb.IsEnabled = true;
- uxIdTagTb.IsEnabled = true;
- uxParentIdTagTb.IsEnabled = true;
- uxTransactionIdTb.IsEnabled = true;
- uxLocalListSizeTb.IsEnabled = true;
- uxConfigKeyTb.IsEnabled = true;
- uxConfigValueTb.IsEnabled = true;
- uxExpiryTimeTb.IsEnabled = true;
- }
- }
- }
|