Przeglądaj źródła

2020/07/16 Jessica
Actions:
1.調整一次要完電樁的設定值
2.韌體更新回覆狀態
3.計時心跳包處理時間

Jessica.Tseng 4 lat temu
rodzic
commit
2e5cfe8538

+ 23 - 21
EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs

@@ -21,6 +21,7 @@ using System.Transactions;
 using System.Data.Entity.Core;
 using System.Data.Entity.Validation;
 using NLog;
+using System.Diagnostics;
 
 namespace EVCB_OCPP.WSServer.Message
 {
@@ -32,6 +33,11 @@ namespace EVCB_OCPP.WSServer.Message
 
         async internal Task<MessageResult> ExecuteCoreRequest(Actions action, ClientData session, IRequest request)
         {
+            Stopwatch watch = new Stopwatch();
+            if (action == Actions.Heartbeat)
+            {
+                watch.Start();
+            }
             MessageResult result = new MessageResult() { Success = false };
 
             try
@@ -256,21 +262,13 @@ namespace EVCB_OCPP.WSServer.Message
                         {
 
                             StartTransactionRequest _request = request as StartTransactionRequest;
-                            IdTagInfo _idTagInfo = new IdTagInfo()
-                            {
-                                expiryDate = DateTime.UtcNow.AddDays(1),
-                                parentIdTag = "Supervisor",
-                                status = AuthorizationStatus.Accepted
 
-                            };
 
                             int _transactionId = -1;
-                            if (DateTime.Compare(DateTime.UtcNow.AddSeconds(-10), _request.timestamp.ToUniversalTime()) >= 0)
-                            {
-                                var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
-                                _idTagInfo = await businessService.Authorize(session.ChargeBoxId, _request.idTag);
 
-                            }
+                            var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
+                            var _idTagInfo = _request.idTag == "Backend" ? new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted } : await businessService.Authorize(session.ChargeBoxId, _request.idTag);
+
 
                             using (var db = new MainDBContext())
                             {
@@ -332,16 +330,9 @@ namespace EVCB_OCPP.WSServer.Message
                             List<TransactionDataRecord> _TransactionDatas = new List<TransactionDataRecord>();
                             int _ConnectorId = 0;
 
-                            //  var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
-                            // var _idTagInfo = businessService.Authorize(session.ChargeBoxId, _request.idTag);
-
-                            var _idTagInfo = new IdTagInfo()
-                            {
-                                expiryDate = DateTime.UtcNow.AddDays(1),
-                                parentIdTag = "Supervisor",
-                                status = AuthorizationStatus.Accepted
+                            var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
+                            var _idTagInfo = _request.idTag == "Backend" ? new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted } : await businessService.Authorize(session.ChargeBoxId, _request.idTag);
 
-                            };
 
                             using (var db = new MainDBContext())
                             {
@@ -423,10 +414,12 @@ namespace EVCB_OCPP.WSServer.Message
                     case Actions.Authorize:
                         {
                             AuthorizeRequest _request = request as AuthorizeRequest;
+
+
                             var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
                             var confirm = new AuthorizeConfirmation()
                             {
-                                idTagInfo = await businessService.Authorize(session.ChargeBoxId, _request.idTag)
+                                idTagInfo = _request.idTag == "Backend" ? new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted } : await businessService.Authorize(session.ChargeBoxId, _request.idTag)
                             };
                             result.Message = confirm;
                             result.Success = true;
@@ -447,6 +440,15 @@ namespace EVCB_OCPP.WSServer.Message
                 result.Exception = ex;
             }
 
+
+            if (action == Actions.Heartbeat)
+            {
+                watch.Stop();
+                if (watch.ElapsedMilliseconds / 1000 > 3)
+                {
+                    logger.Error("Processing Hearbeat costs " + watch.ElapsedMilliseconds/1000+" seconds");
+                }
+            }
             return result;
         }
 

+ 7 - 0
EVCB_OCPP.WSServer/Message/FirmwareManagementProfileHandler.cs

@@ -148,6 +148,12 @@ namespace EVCB_OCPP.WSServer.Message
                 case Actions.UpdateFirmware:
                 case Actions.GetDiagnostics:
                     {
+                        string evse_rep = string.Empty;
+                        if(confirm is GetDiagnosticsConfirmation)
+                        {
+                            var confirmation = confirm as GetDiagnosticsConfirmation;
+                            evse_rep = confirmation.fileName;
+                        }
                         using (var db = new MainDBContext())
                         {
                             var operation = db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
@@ -157,6 +163,7 @@ namespace EVCB_OCPP.WSServer.Message
                                 operation.FinishedOn = DateTime.Now;
                                 operation.Status = 1;//電樁有回覆
                                 operation.EVSE_Status = (int)1;//OK
+                                operation.EVSE_Value = evse_rep;
                                 db.SaveChanges();
                             }
 

+ 90 - 70
EVCB_OCPP.WSServer/ProtalServer.cs

@@ -264,57 +264,76 @@ namespace EVCB_OCPP.WSServer
             int takeCount = 8;
             using (var db = new MainDBContext())
             {
-
-                string maxKeys = StandardConfiguration.AllConfigs.Skip(skipCount).Take(1).FirstOrDefault();
-                if (maxKeys == StandardConfiguration.GetConfigurationMaxKeys)
-                {
-                    var _Configure = db.MachineConfiguration.Where(x => x.ChargeBoxId == chargeBoxId && x.ConfigureName == maxKeys).Select(x => new { ConfigureSetting = x.ConfigureSetting, ConfigureName = x.ConfigureName }).FirstOrDefault();
-                    if (_Configure != null)
-                    {
-                        int cp_ConfiureCount = 0;
-                        int.TryParse(_Configure.ConfigureSetting, out cp_ConfiureCount);
-                        takeCount = takeCount > cp_ConfiureCount ? cp_ConfiureCount : takeCount;
-                        skipCount = 1;
-                        if (string.IsNullOrEmpty(_Configure.ConfigureSetting)) return;
-                    }
-
-                }
-
-                while (StandardConfiguration.AllConfigs.Count > skipCount)
+                db.ServerMessage.Add(new ServerMessage()
                 {
-                    string _key = StandardConfiguration.AllConfigs.Skip(skipCount).Take(1).FirstOrDefault();
-                    var _Configure = db.MachineConfiguration.Where(x => x.ChargeBoxId == chargeBoxId && x.ConfigureName == _key).Select(x => new { ConfigureSetting = x.ConfigureSetting, ConfigureName = x.ConfigureName }).FirstOrDefault();
-                    takeCount = StandardConfiguration.AllConfigs.Count - skipCount > takeCount ? takeCount : StandardConfiguration.AllConfigs.Count - skipCount;
-
-                    var _keys = StandardConfiguration.AllConfigs.Skip(skipCount).Take(takeCount).ToList();
-                    //   Console.WriteLine("===============Skip:" + skipCount);
-                    if (_Configure == null)
-                    {
-                        // Console.WriteLine("_Configure == null===============Skip:" + skipCount);
-                        db.ServerMessage.Add(new ServerMessage()
-                        {
-                            ChargeBoxId = chargeBoxId,
-                            CreatedBy = "Server",
-                            CreatedOn = DateTime.Now,
-                            OutAction = Actions.GetConfiguration.ToString(),
-                            OutRequest = JsonConvert.SerializeObject(
+                    ChargeBoxId = chargeBoxId,
+                    CreatedBy = "Server",
+                    CreatedOn = DateTime.Now,
+                    OutAction = Actions.GetConfiguration.ToString(),
+                    OutRequest = JsonConvert.SerializeObject(
                             new GetConfigurationRequest()
                             {
-                                key = _keys
+                                key = new List<string>()
 
                             },
                             new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
-                            SerialNo = Guid.NewGuid().ToString(),
-                            InMessage = string.Empty
+                    SerialNo = Guid.NewGuid().ToString(),
+                    InMessage = string.Empty
 
-                        });
+                }); ;
 
-                        db.SaveChanges();
-                    }
-
-                    skipCount = skipCount + takeCount;
+                db.SaveChanges();
 
-                }
+                //string maxKeys = StandardConfiguration.AllConfigs.Skip(skipCount).Take(1).FirstOrDefault();
+                //if (maxKeys == StandardConfiguration.GetConfigurationMaxKeys)
+                //{
+                //    var _Configure = db.MachineConfiguration.Where(x => x.ChargeBoxId == chargeBoxId && x.ConfigureName == maxKeys).Select(x => new { ConfigureSetting = x.ConfigureSetting, ConfigureName = x.ConfigureName }).FirstOrDefault();
+                //    if (_Configure != null)
+                //    {
+                //        int cp_ConfiureCount = 0;
+                //        int.TryParse(_Configure.ConfigureSetting, out cp_ConfiureCount);
+                //        takeCount = takeCount > cp_ConfiureCount ? cp_ConfiureCount : takeCount;
+                //        skipCount = 1;
+                //        if (string.IsNullOrEmpty(_Configure.ConfigureSetting)) return;
+                //    }
+
+                //}
+
+                //while (StandardConfiguration.AllConfigs.Count > skipCount)
+                //{
+                //    string _key = StandardConfiguration.AllConfigs.Skip(skipCount).Take(1).FirstOrDefault();
+                //    var _Configure = db.MachineConfiguration.Where(x => x.ChargeBoxId == chargeBoxId && x.ConfigureName == _key).Select(x => new { ConfigureSetting = x.ConfigureSetting, ConfigureName = x.ConfigureName }).FirstOrDefault();
+                //    takeCount = StandardConfiguration.AllConfigs.Count - skipCount > takeCount ? takeCount : StandardConfiguration.AllConfigs.Count - skipCount;
+
+                //    var _keys = StandardConfiguration.AllConfigs.Skip(skipCount).Take(takeCount).ToList();
+                //    //   Console.WriteLine("===============Skip:" + skipCount);
+                //    if (_Configure == null)
+                //    {
+                //        // Console.WriteLine("_Configure == null===============Skip:" + skipCount);
+                //        db.ServerMessage.Add(new ServerMessage()
+                //        {
+                //            ChargeBoxId = chargeBoxId,
+                //            CreatedBy = "Server",
+                //            CreatedOn = DateTime.Now,
+                //            OutAction = Actions.GetConfiguration.ToString(),
+                //            OutRequest = JsonConvert.SerializeObject(
+                //            new GetConfigurationRequest()
+                //            {
+                //                key = _keys
+
+                //            },
+                //            new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
+                //            SerialNo = Guid.NewGuid().ToString(),
+                //            InMessage = string.Empty
+
+                //        });
+
+                //        db.SaveChanges();
+                //    }
+
+                //    skipCount = skipCount + takeCount;
+
+                //}
 
             }
         }
@@ -345,9 +364,9 @@ namespace EVCB_OCPP.WSServer
                 //Security = serverSecurity,
                 Certificate = Certificate,
                 Listeners = listeners,
-                LogAllSocketException = true,
+              //  LogAllSocketException = true,
                 KeepAliveTime = 10,
-                LogBasicSessionActivity = true
+               // LogBasicSessionActivity = true
 
 
             };
@@ -422,8 +441,8 @@ namespace EVCB_OCPP.WSServer
                         }
                     }
 
-                    CheckVersion(session.ChargeBoxId);
-                    CheckEVSEConfigure(session.ChargeBoxId);
+                  
+                   // CheckEVSEConfigure(session.ChargeBoxId);
                 }
             }
             catch (Exception ex)
@@ -537,7 +556,7 @@ namespace EVCB_OCPP.WSServer
 
         }
 
-
+     
 
         async private void ProcessRequestMessage(MessageResult analysisResult, ClientData session, Actions action)
         {
@@ -556,32 +575,32 @@ namespace EVCB_OCPP.WSServer
                         {
 
 
-                            bool oldstatus = session.IsCheckIn;
+                            
                             var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
                             if (replyResult.Success)
                             {
                                 string response = msgAnalyser.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
+
+
                                 Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString());
+
+
                                 if (action == Actions.BootNotification && replyResult.Message is BootNotificationConfirmation)
                                 {
                                     if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
                                     {
-                                        session.IsCheckIn = true;
-                                        if (!oldstatus)
+                                        using (var db = new MainDBContext())
                                         {
-                                            using (var db = new MainDBContext())
+                                            var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
+                                            if (machine != null)
                                             {
-                                                var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
-                                                if (machine != null)
-                                                {
-                                                    machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
-                                                    db.SaveChanges();
-                                                }
+                                                machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
+                                                db.SaveChanges();
                                             }
-
-
-                                            // CheckEVSEConfigure(session.ChargeBoxId);
                                         }
+
+                                        CheckVersion(session.ChargeBoxId);
+                                        CheckEVSEConfigure(session.ChargeBoxId);
                                     }
                                 }
 
@@ -992,7 +1011,7 @@ namespace EVCB_OCPP.WSServer
                         var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
                         if (commandList.Count > 0)
                         {
-                            Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
+                           // Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
                         }
 
                         foreach (var charger_SN in cmdMachineList)
@@ -1002,6 +1021,7 @@ namespace EVCB_OCPP.WSServer
                             if (clientDic.TryGetValue(charger_SN, out session))
                             {
                                 Console.WriteLine(string.Format("charger_SN:{0} startDt:{1} CreatedOn:{2}", charger_SN, startDt.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
+
                                 if (session.IsCheckIn)
                                 {
                                     var cmdList = commandList.Where(c => c.ChargeBoxId == charger_SN).ToList();
@@ -1053,7 +1073,7 @@ namespace EVCB_OCPP.WSServer
                                 }
                             }
                         }
-                        db.ChangeTracker.DetectChanges();
+                       
                     }
 
                     await Task.Delay(1000);
@@ -1077,9 +1097,9 @@ namespace EVCB_OCPP.WSServer
                 }
 
                 try
-                {          
+                {
 
-                    if (DateTime.Now.Subtract(lastcheckdt).TotalSeconds > 20)
+                    if (DateTime.Now.Subtract(lastcheckdt).TotalSeconds > 10)
                     {
                         Stopwatch watch = new Stopwatch();
                         Dictionary<string, ClientData> _copyClientDic = null;
@@ -1088,12 +1108,12 @@ namespace EVCB_OCPP.WSServer
                             _copyClientDic = new Dictionary<string, ClientData>(clientDic);
                         }
 
-                        var clients = _copyClientDic.Where(x => x.Value.LastActiveTime > DateTime.Now.AddSeconds(-60)).Select(x => x.Value).ToList();
-
+                        var cdt = DateTime.Now;
+                        var clients = _copyClientDic.Where(x => x.Value.LastActiveTime > cdt.AddSeconds(-30)).Select(x => x.Value).ToList();
+                      
                         watch.Start();
                         foreach (var session in clients)
                         {
-
                             using (var db = new MainDBContext())
                             {
                                 var machine = new Machine() { Id = session.MachineId };
@@ -1112,14 +1132,14 @@ namespace EVCB_OCPP.WSServer
                             }
                         }
                         watch.Stop();
-                        if (watch.ElapsedMilliseconds/1000 > 5)
+                        if (watch.ElapsedMilliseconds / 1000 > 5)
                         {
                             logger.Fatal("Update HeartBeatCheckTrigger cost " + watch.ElapsedMilliseconds / 1000 + " seconds.");
                         }
                     }
                     lastcheckdt = DateTime.Now;
 
-                    await Task.Delay(60000);
+                    await Task.Delay(10000);
                 }
                 catch (Exception ex)
                 {
@@ -1233,7 +1253,7 @@ namespace EVCB_OCPP.WSServer
                         sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
                         sc.ReceivedOn = DateTime.Now;
                         db.SaveChanges();
-                        Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
+                      //  Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
 
                     }
                     confirmed = true;

+ 6 - 1
EVCB_OCPP.WSServer/SuperSocket.Protocol/OCPPWSServer.cs

@@ -61,7 +61,12 @@ namespace OCPPServer.Protocol
 
         protected override bool ValidateHandshake(ClientData session, string origin)
         {
-
+            if(string.IsNullOrEmpty(session.Path))
+            {
+                Console.WriteLine("===========================================");
+                Console.WriteLine("session.Path EMPTY");
+                Console.WriteLine("===========================================");
+            }
 
             string[] words = session.Path.Split('/');
             session.ChargeBoxId = words.Last();

+ 1 - 1
TestTool.RemoteTriggerAPP/MainWindow.xaml

@@ -5,7 +5,7 @@
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:local="clr-namespace:TestTool.RemoteTriggerAPP"      
         mc:Ignorable="d"
-        Title="下發測試用工具(公司內網) V1.1.21 (20200618)" Height="481" Width="639">
+        Title="下發測試用工具(公司內網) V1.1.22 (20200709)" Height="481" Width="639">
     <Viewbox>
         <Grid Margin="0,2,2,0">
             <Grid.ColumnDefinitions>

+ 5 - 5
TestTool.RemoteTriggerAPP/MainWindow.xaml.cs

@@ -327,7 +327,7 @@ namespace TestTool.RemoteTriggerAPP
                 var request = new GetCompositeScheduleRequest()
                 {
                     connectorId = Convert.ToInt32(uxConnectorIdTb.Text),
-                    duration = 300
+                    duration = 10000
                 };
 
                 WritetoDB(uuid, request);
@@ -610,7 +610,7 @@ namespace TestTool.RemoteTriggerAPP
                 var uuid = Guid.NewGuid().ToString();
                 var request = new RemoteStartTransactionRequest()
                 {
-                    connectorId = byte.Parse(uxConnectorIdTb.Text),
+                    connectorId = int.Parse(uxConnectorIdTb.Text),
                     idTag = uxIdTagTb.Text
 
                 };
@@ -635,7 +635,7 @@ namespace TestTool.RemoteTriggerAPP
                 var uuid = Guid.NewGuid().ToString();
                 var request = new UnlockConnectorRequest()
                 {
-                    connectorId = byte.Parse(uxConnectorIdTb.Text),
+                    connectorId = int.Parse(uxConnectorIdTb.Text),
 
                 };
 
@@ -655,7 +655,7 @@ namespace TestTool.RemoteTriggerAPP
                 var uuid = Guid.NewGuid().ToString();
                 var request = new ChangeAvailabilityRequest()
                 {
-                    connectorId = byte.Parse(uxConnectorIdTb.Text),
+                    connectorId = int.Parse(uxConnectorIdTb.Text),
                     type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Inoperative
                 };
 
@@ -675,7 +675,7 @@ namespace TestTool.RemoteTriggerAPP
                 var uuid = Guid.NewGuid().ToString();
                 var request = new ChangeAvailabilityRequest()
                 {
-                    connectorId = byte.Parse(uxConnectorIdTb.Text),
+                    connectorId = int.Parse(uxConnectorIdTb.Text),
                     type = EVCB_OCPP.Packet.Messages.SubTypes.AvailabilityType.Operative
                 };