瀏覽代碼

1. 取消 handshake 讀取資料庫,已緩解大量Connection 進入塞車問題

Jessica Tseng 2 年之前
父節點
當前提交
f4abcade48

+ 30 - 39
EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs

@@ -70,13 +70,7 @@ namespace EVCB_OCPP.WSServer.Message
         private OuterHttpClient httpClient = new OuterHttpClient();
         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
             {
                 switch (action)
@@ -172,38 +166,44 @@ namespace EVCB_OCPP.WSServer.Message
                         break;
                     case Actions.BootNotification:
                         {
-                            BootNotificationRequest _request = request as BootNotificationRequest;
-                            int heartbeat_interval = GlobalConfig.GetHEARTBEAT_INTERVAL();
-                            using (var db = new MainDBContext())
+                            if (session.CustomerId == Guid.Empty)
+                            {
+                                result.Message = new BootNotificationConfirmation() { currentTime = DateTime.UtcNow, interval = 5, status = RegistrationStatus.Pending };
+                            }
+                            else
                             {
-                                var _machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
-                                _machine.ChargeBoxSerialNumber = string.IsNullOrEmpty(_request.chargeBoxSerialNumber) ? string.Empty : _request.chargeBoxSerialNumber;
-                                _machine.ChargePointSerialNumber = string.IsNullOrEmpty(_request.chargePointSerialNumber) ? string.Empty : _request.chargePointSerialNumber;
-                                _machine.ChargePointModel = string.IsNullOrEmpty(_request.chargePointModel) ? string.Empty : _request.chargePointModel;
-                                _machine.ChargePointVendor = string.IsNullOrEmpty(_request.chargePointVendor) ? string.Empty : _request.chargePointVendor;
-                                _machine.FW_CurrentVersion = string.IsNullOrEmpty(_request.firmwareVersion) ? string.Empty : _request.firmwareVersion;
-                                //_machine.Iccid = string.IsNullOrEmpty(_request.iccid) ? string.Empty : _request.iccid;
-                                _machine.Iccid = DateTime.UtcNow.ToString("yy-MM-dd HH:mm");
-                                _machine.Imsi = string.IsNullOrEmpty(_request.imsi) ? string.Empty : _request.imsi;
-                                _machine.MeterSerialNumber = string.IsNullOrEmpty(_request.meterSerialNumber) ? string.Empty : _request.meterSerialNumber;
-                                _machine.MeterType = string.IsNullOrEmpty(_request.meterType) ? string.Empty : _request.meterType;
+                                BootNotificationRequest _request = request as BootNotificationRequest;
+                                int heartbeat_interval = GlobalConfig.GetHEARTBEAT_INTERVAL();
+                                using (var db = new MainDBContext())
+                                {
+                                    var _machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
+                                    _machine.ChargeBoxSerialNumber = string.IsNullOrEmpty(_request.chargeBoxSerialNumber) ? string.Empty : _request.chargeBoxSerialNumber;
+                                    _machine.ChargePointSerialNumber = string.IsNullOrEmpty(_request.chargePointSerialNumber) ? string.Empty : _request.chargePointSerialNumber;
+                                    _machine.ChargePointModel = string.IsNullOrEmpty(_request.chargePointModel) ? string.Empty : _request.chargePointModel;
+                                    _machine.ChargePointVendor = string.IsNullOrEmpty(_request.chargePointVendor) ? string.Empty : _request.chargePointVendor;
+                                    _machine.FW_CurrentVersion = string.IsNullOrEmpty(_request.firmwareVersion) ? string.Empty : _request.firmwareVersion;
+                                    //_machine.Iccid = string.IsNullOrEmpty(_request.iccid) ? string.Empty : _request.iccid;
+                                    _machine.Iccid = DateTime.UtcNow.ToString("yy-MM-dd HH:mm");
+                                    _machine.Imsi = string.IsNullOrEmpty(_request.imsi) ? string.Empty : _request.imsi;
+                                    _machine.MeterSerialNumber = string.IsNullOrEmpty(_request.meterSerialNumber) ? string.Empty : _request.meterSerialNumber;
+                                    _machine.MeterType = string.IsNullOrEmpty(_request.meterType) ? string.Empty : _request.meterType;
 
-                                db.SaveChanges();
+                                    db.SaveChanges();
 
 
 
-                                var configVaule = db.MachineConfiguration.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.HeartbeatInterval)
-                                    .Select(x => x.ConfigureSetting).FirstOrDefault();
+                                    //    var configVaule = db.MachineConfiguration.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.HeartbeatInterval)
+                                    //        .Select(x => x.ConfigureSetting).FirstOrDefault();
 
-                                if (configVaule != null)
-                                {
-                                    int.TryParse(configVaule, out heartbeat_interval);
-                                }
+                                    //    if (configVaule != null)
+                                    //    {
+                                    //        int.TryParse(configVaule, out heartbeat_interval);
+                                    //    }
+                                    }
+                                    var confirm = new BootNotificationConfirmation() { currentTime = DateTime.UtcNow, interval = heartbeat_interval, status = Packet.Messages.SubTypes.RegistrationStatus.Accepted };                            
+                                result.Message = confirm;
                             }
-                            var confirm = new BootNotificationConfirmation() { currentTime = DateTime.UtcNow, interval = session.IsPending ? heartbeat_interval : 5, status = session.IsPending ? Packet.Messages.SubTypes.RegistrationStatus.Accepted : RegistrationStatus.Pending };
 
-                            session.IsPending = !session.IsPending;
-                            result.Message = confirm;
                             result.Success = true;
                         }
                         break;
@@ -793,15 +793,6 @@ 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;
         }
 

+ 1 - 1
EVCB_OCPP.WSServer/Properties/AssemblyInfo.cs

@@ -35,4 +35,4 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyVersion("1.0.6.0")]
 [assembly: AssemblyFileVersion("1.0.6.0")]
 
-[assembly: AssemblyInformationalVersion("6c4fbb3")]
+[assembly: AssemblyInformationalVersion("d6fe7ae")]

+ 149 - 94
EVCB_OCPP.WSServer/ProtalServer.cs

@@ -122,6 +122,10 @@ namespace EVCB_OCPP.WSServer
             //ReadTCCSetting();
             OpenNetwork();
 
+            Task fillinChargerDataTask = new Task(FillinChargerData, _ct);
+            fillinChargerDataTask.Start();
+
+
             Task serverCommandTask = new Task(ServerMessageTrigger, _ct);
             serverCommandTask.Start();
 
@@ -435,15 +439,15 @@ namespace EVCB_OCPP.WSServer
                     // logger.Debug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
                     WriteMachineLog(session, "NewSessionConnected", "Connection", "");
 
-                    using (var db = new MainDBContext())
-                    {
-                        var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
-                        if (machine != null)
-                        {
-                            machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
-                            db.SaveChanges();
-                        }
-                    }
+                    //using (var db = new MainDBContext())
+                    //{
+                    //    var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
+                    //    if (machine != null)
+                    //    {
+                    //        machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
+                    //        db.SaveChanges();
+                    //    }
+                    //}
                 }
             }
             catch (Exception ex)
@@ -717,10 +721,12 @@ namespace EVCB_OCPP.WSServer
 
                                 if (action == Actions.BootNotification && replyResult.Message is BootNotificationConfirmation)
                                 {
-                                    session.IsCheckIn = true;
                                     if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
                                     {
+                                        session.IsCheckIn = true;
+                                       
 
+                                        await SetDefaultFee(session);
                                         CheckVersion(session.ChargeBoxId);
                                         CheckEVSEConfigure(session.ChargeBoxId);
                                         if (session.CustomerId == new Guid("298918C0-6BB5-421A-88CC-4922F918E85E") || session.CustomerId == new Guid("9E6BFDCC-09FB-4DAB-A428-43FE507600A3"))
@@ -847,21 +853,7 @@ namespace EVCB_OCPP.WSServer
                                     }
                                     else
                                     {
-                                        using (var db = new MainDBContext())
-                                        {
-                                            var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
-                                            if (machine != null)
-                                            {
-                                                if (machine.ConnectorType.Contains("6") || machine.ConnectorType.Contains("7") || machine.ConnectorType.Contains("8") || machine.ConnectorType.Contains("9"))
-                                                {
-                                                    session.IsAC = false;
-                                                }
-                                                machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
-                                                db.SaveChanges();
-                                            }
-                                        }
 
-                                        await SetDefaultFee(session);
                                     }
                                 }
 
@@ -943,75 +935,75 @@ namespace EVCB_OCPP.WSServer
                                 Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
                             }
 
-                            if (action == Actions.StartTransaction)
-                            {
-                                var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
-                                var _powerDic = _loadingBalanceService.GetSettingPower(stationId, session.MachineId);
-                                if (_powerDic != null)
-                                {
-                                    foreach (var kv in _powerDic)
-                                    {
-                                        try
-                                        {
-                                            string chargeBoxId = string.Empty;
-                                            //set profile
-                                            lock (_lockClientDic)
-                                            {
-                                                chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
-                                            }
-
-                                            if (chargeBoxId != null && kv.Value.HasValue)
-                                            {
-                                                profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
-                                            }
-                                        }
-                                        catch (Exception ex)
-                                        {
-                                            logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
-                                        }
-
-                                    }
-                                }
-                            }
-
-                            if (action == Actions.StopTransaction)
-                            {
-                                var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
-                                if (_loadingBalanceService.IsNeedtoCancelSetting(stationId, session.MachineId, session.ChargeBoxId))
-                                {
-                                    //Clear  current profile    
-                                    profileHandler.ClearChargingProfile(session.ChargeBoxId);
-
-                                    var _powerDic = _loadingBalanceService.GetRerangeSettingPower(stationId);
-                                    if (_powerDic != null)
-                                    {
-                                        foreach (var kv in _powerDic)
-                                        {
-                                            try
-                                            {
-                                                string chargeBoxId = string.Empty;
-                                                //set profile
-                                                lock (_lockClientDic)
-                                                {
-                                                    chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
-                                                }
-
-                                                if (chargeBoxId != null && kv.Value.HasValue)
-                                                {
-                                                    profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
-                                                }
-                                            }
-                                            catch (Exception ex)
-                                            {
-                                                logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
-                                            }
-
-                                        }
-                                    }
-
-                                }
-
-                            }
+                            //if (action == Actions.StartTransaction)
+                            //{
+                            //    var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
+                            //    var _powerDic = _loadingBalanceService.GetSettingPower(stationId, session.MachineId);
+                            //    if (_powerDic != null)
+                            //    {
+                            //        foreach (var kv in _powerDic)
+                            //        {
+                            //            try
+                            //            {
+                            //                string chargeBoxId = string.Empty;
+                            //                //set profile
+                            //                lock (_lockClientDic)
+                            //                {
+                            //                    chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
+                            //                }
+
+                            //                if (chargeBoxId != null && kv.Value.HasValue)
+                            //                {
+                            //                    profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
+                            //                }
+                            //            }
+                            //            catch (Exception ex)
+                            //            {
+                            //                logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
+                            //            }
+
+                            //        }
+                            //    }
+                            //}
+
+                            //if (action == Actions.StopTransaction)
+                            //{
+                            //    var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
+                            //    if (_loadingBalanceService.IsNeedtoCancelSetting(stationId, session.MachineId, session.ChargeBoxId))
+                            //    {
+                            //        //Clear  current profile    
+                            //        profileHandler.ClearChargingProfile(session.ChargeBoxId);
+
+                            //        var _powerDic = _loadingBalanceService.GetRerangeSettingPower(stationId);
+                            //        if (_powerDic != null)
+                            //        {
+                            //            foreach (var kv in _powerDic)
+                            //            {
+                            //                try
+                            //                {
+                            //                    string chargeBoxId = string.Empty;
+                            //                    //set profile
+                            //                    lock (_lockClientDic)
+                            //                    {
+                            //                        chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
+                            //                    }
+
+                            //                    if (chargeBoxId != null && kv.Value.HasValue)
+                            //                    {
+                            //                        profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
+                            //                    }
+                            //                }
+                            //                catch (Exception ex)
+                            //                {
+                            //                    logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
+                            //                }
+
+                            //            }
+                            //        }
+
+                            //    }
+
+                            //}
 
                         }
                         break;
@@ -1211,6 +1203,61 @@ namespace EVCB_OCPP.WSServer
 
 
         }
+        DateTime fillinDt = DateTime.UtcNow.AddMinutes(-1);
+        async private void FillinChargerData()
+        {
+            for (; ; )
+            {
+                if (_ct.IsCancellationRequested)
+                {
+                    break;
+                }
+
+                var min_Interval = (DateTime.UtcNow - fillinDt).TotalSeconds;
+                if (min_Interval > 3)
+                {
+                    BasicMessageHandler msgAnalyser = new BasicMessageHandler();
+                    Dictionary<string, ClientData> _copyClientDic = null;
+                    lock (_lockClientDic)
+                    {
+                        _copyClientDic = new Dictionary<string, ClientData>(clientDic);
+
+                    }
+                    var chargers = _copyClientDic.Values.Where(x => x.CustomerId == Guid.Empty).Take(100).ToList();
+                    fillinDt = DateTime.UtcNow;
+                    using (var db = new MainDBContext())
+                    {
+
+                        foreach (var charger in chargers)
+                        {
+                            try
+                            {
+
+                                var machine = db.Machine.Where(x => x.ChargeBoxId == charger.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id ,x.ConnectorType }).FirstOrDefault();
+                                if (machine == null)
+                                {
+                                    charger.LastActiveTime = DateTime.UtcNow.AddDays(-1);
+                                }
+                                if (machine.ConnectorType.Contains("6") || machine.ConnectorType.Contains("7") || machine.ConnectorType.Contains("8") || machine.ConnectorType.Contains("9"))
+                                {
+                                    charger.IsAC = false;
+                                }
+                                charger.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
+                                charger.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
+                                charger.MachineId = machine == null ? String.Empty : machine.Id;
+
+                            }
+                            catch (Exception ex)
+                            {
+                                logger.Error(string.Format("FillinChargerData ChargeBoxId:{0}  Ex:{1}", charger.ChargeBoxId, ex.ToString()));
+                            }
+                        }
+                    }
+                    await Task.Delay(10000);
+
+                }
+            }
+        }
 
         async private void ServerUpdateTrigger()
         {
@@ -1510,6 +1557,9 @@ namespace EVCB_OCPP.WSServer
                         watch.Start();
                         foreach (var session in clients)
                         {
+                            if (string.IsNullOrEmpty(session.MachineId))
+                                continue;
+
                             using (var db = new MainDBContext())
                             {
                                 var machine = new Machine() { Id = session.MachineId };
@@ -2065,7 +2115,7 @@ namespace EVCB_OCPP.WSServer
                 try
                 {
                     session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
-                    // session.Close(CloseReason.ServerShutdown);
+                    session.Close(CloseReason.ServerShutdown);
 
                 }
                 catch (Exception ex)
@@ -2109,6 +2159,11 @@ namespace EVCB_OCPP.WSServer
         {
             try
             {
+                //using (var maindb = new MainDBContext())
+                //{
+                //    GlobalConfig.Machines = maindb.Machine.ToList();
+                //}
+
                 using (var log = new ConnectionLogDBContext())
                 {
                     log.MachineConnectionLog.ToList();

+ 8 - 74
EVCB_OCPP.WSServer/SuperSocket.Protocol/OCPPWSServer.cs

@@ -87,13 +87,12 @@ namespace OCPPServer.Protocol
             logger.Info(string.Format("ValidateHandshake: {0}", session.Path));
             bool isExistedSN = false;
             bool authorizated = false;
-            using (var db = new MainDBContext())
+          //  using (var db = new MainDBContext())
             {
-                var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).FirstOrDefault();
-                session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
-                session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
-                session.MachineId = machine == null ? String.Empty : machine.Id;
-                isExistedSN = machine == null ? false : true;
+
+                session.CustomerId = Guid.Empty;
+                session.MachineId = String.Empty;
+                isExistedSN  =true;
 
                 if (!isExistedSN)
                 {
@@ -111,9 +110,7 @@ namespace OCPPServer.Protocol
                     return false;
                 }
 
-                var configVaule = db.MachineConfiguration.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
-                                  .Select(x => x.ConfigureSetting).FirstOrDefault();
-                int.TryParse(configVaule, out securityProfile);
+              
 
                 if (session.ISOCPP20)
                 {
@@ -142,73 +139,10 @@ namespace OCPPServer.Protocol
                 if (securityProfile == 2 && session.UriScheme == "ws")
                 {
                     authorizated = false;
-                }
-
-                if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
-                {
-
-                    using (var db = new MainDBContext())
-                    {
-
-                        authorizationKey = db.MachineConfiguration.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
-                                          .Select(x => x.ConfigureSetting).FirstOrDefault();
-
-
-                        if (session.ISOCPP20)
-                        {
-                            // 1.6 server only support change server  function
-                            securityProfile = 0;
-                        }
-                    }
-                    logger.Info("***********Authorization   ");
-
-                    if (!string.IsNullOrEmpty(authorizationKey))
-                    {
-                        string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
-                        byte[] data = Convert.FromBase64String(base64Encoded);
-                        string[] base64Decoded = System.Text.ASCIIEncoding.ASCII.GetString(data).Split(':');
-                        logger.Info("***********Authorization   " + System.Text.ASCIIEncoding.ASCII.GetString(data));
-                        if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
-                        {
-                            authorizated = true;
-                        }
-                    }
-
-
-
-
-
-                }
-                else
-                {
-                    authorizated = true;
-
-                }
-
+                }               
 
-
-                if (!authorizated)
-                {
-                    StringBuilder responseBuilder = new StringBuilder();
-
-                    responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
-                    (int)HttpStatusCode.Unauthorized, @"Unauthorized");
-
-                    responseBuilder.AppendWithCrCf();
-                    string sb = responseBuilder.ToString();
-                    byte[] data = Encoding.UTF8.GetBytes(sb);
-
-                    ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
-                    logger.Info(sb);
-                    return false;
-                }
             }
-
-
-         
-
-
-
+            
             return true;
         }
     }

二進制
SuperWebSocket/bin/Debug/SuperWebSocket.dll


二進制
SuperWebSocket/bin/Debug/SuperWebSocket.pdb


二進制
TestTool.RemoteTriggerAPP/DLL/EVCB_OCPP.Domain.dll


+ 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.38 (20220622)" Height="481" Width="652">
+        Title="下發測試用工具(公司內網) V1.1.39 (20220810)" Height="481" Width="652">
     <Viewbox>
         <Grid Margin="0,2,2,0">
             <Grid.ColumnDefinitions>