Browse Source

1. add back GetConfiguration value null handling
2. SetDefaultFee using QueryFirstOrDefaultAsync instead QueryAsync then First()
3. clarify ValidateHandshake failed msg log
4. add back try catch in TryConfirmMessage
5. add back send get configure and move to InitializeEVSE

Robert 10 months ago
parent
commit
d20e3c7ac7

+ 6 - 72
EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs

@@ -1576,12 +1576,13 @@ internal partial class ProfileHandler
                                     {
                                         logger.LogTrace("*********************");
                                     }
-                                    var foundConfig = configure.Find(x => x.ConfigureName == item.key);
 
+                                    var foundConfig = configure.Find(x => x.ConfigureName == item.key);
+                                    var updateValue = string.IsNullOrEmpty(item.value) ? string.Empty : item.value;
 
                                     if (foundConfig == null)
                                     {
-                                        await mainDbService.AddMachineConfiguration(session.ChargeBoxId, item.key, item.value, item.IsReadOnly);
+                                        await mainDbService.AddMachineConfiguration(session.ChargeBoxId, item.key, updateValue, item.IsReadOnly);
                                     }
                                     else if (item.value != foundConfig.ConfigureSetting)
                                     {
@@ -1595,7 +1596,7 @@ internal partial class ProfileHandler
                                             oldValue = foundConfig.ConfigureSetting;
                                         }
 
-                                        await mainDbService.UpdateMachineConfiguration(session.ChargeBoxId, item.key, item.value, item.IsReadOnly);
+                                        await mainDbService.UpdateMachineConfiguration(session.ChargeBoxId, item.key, updateValue, item.IsReadOnly);
                                     }
                                 }
                             }
@@ -1607,82 +1608,15 @@ internal partial class ProfileHandler
                                     var foundConfig = configure.Find(x => x.ConfigureName == item);
                                     if (foundConfig != null)
                                     {
-                                        await mainDbService.UpdateMachineConfiguration(session.ChargeBoxId, item, string.Empty, true, isExists: false);
+                                        await mainDbService.UpdateMachineConfiguration(session.ChargeBoxId, item, string.Empty, isReadOnly: true, isExists: false);
                                     }
                                     else
                                     {
-                                        await mainDbService.AddMachineConfiguration(session.ChargeBoxId, item, string.Empty, true, isExist: false);
+                                        await mainDbService.AddMachineConfiguration(session.ChargeBoxId, item, string.Empty, isReadOnly: true, isExist: false);
                                     }
                                 }
                             }
 
-								//var configure = await db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId).ToListAsync();
-
-								//if (_confirm.configurationKey != null)
-								//{
-								//	foreach (var item in _confirm.configurationKey)
-								//	{
-								//		string oldValue = string.Empty;
-								//		if (item.key == null)
-								//		{
-								//			logger.LogTrace("*********************");
-								//		}
-								//		var foundConfig = configure.Find(x => x.ConfigureName == item.key);
-
-
-								//		if (foundConfig != null)
-								//		{
-								//			if (foundConfig.ConfigureName == null)
-								//			{
-								//				logger.LogTrace("*********************");
-								//			}
-
-								//			if (foundConfig.ConfigureName == "SecurityProfile")
-								//			{
-								//				oldValue = foundConfig.ConfigureSetting;
-								//			}
-
-								//			foundConfig.ReadOnly = item.IsReadOnly;
-								//			foundConfig.ConfigureSetting = string.IsNullOrEmpty(item.value) ? string.Empty : item.value;
-								//		}
-								//		else
-								//		{
-								//			await db.MachineConfigurations.AddAsync(new MachineConfigurations()
-								//			{
-								//				ChargeBoxId = session.ChargeBoxId,
-								//				ConfigureName = item.key,
-								//				ReadOnly = item.IsReadOnly,
-								//				ConfigureSetting = string.IsNullOrEmpty(item.value) ? string.Empty : item.value,
-								//				Exists = true
-								//			});
-								//		}
-
-
-								//	}
-								//}
-								//if (_confirm.unknownKey != null)
-								//{
-
-								//	foreach (var item in _confirm.unknownKey)
-								//	{
-								//		var foundConfig = configure.Find(x => x.ConfigureName == item);
-								//		if (foundConfig != null)
-								//		{
-								//			foundConfig.ReadOnly = true;
-								//			foundConfig.ConfigureSetting = string.Empty;
-								//			foundConfig.Exists = false;
-								//		}
-								//		else
-								//		{
-								//			await db.MachineConfigurations.AddAsync(new MachineConfigurations()
-								//			{
-								//				ChargeBoxId = session.ChargeBoxId,
-								//				ConfigureName = item
-								//			});
-								//		}
-								//	}
-								//}
-
                             using (var db = await maindbContextFactory.CreateDbContextAsync())
                             {
                                 var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&

+ 6 - 5
EVCB_OCPP.WSServer/ProtalServer.cs

@@ -1045,18 +1045,19 @@ namespace EVCB_OCPP.WSServer
             await mainDbService.SetMachineConnectionType(session.ChargeBoxId, session.UriScheme.Contains("wss") ? 2 : 1, session.DisconnetCancellationToken);
 
             string requestId = string.Empty;
-            MessageResult response = null;
-            Func<Task<string>> sendTask = null;
-            Func<string, Task> sendTask2 = null;
 
             var displayPriceText = await webDbService.SetDefaultFee(session);
             UpdateClientDisplayPrice(session.ChargeBoxId, displayPriceText);
 
+            Func<string, Task<string>> sendTask;
+            sendTask = async (string serialNo) => await messageService.SendGetEVSEConfigureRequest(session.ChargeBoxId, serialNo: serialNo);
+            var response = await confirmWaitingMessageSerevice.SendAndWaitUntilResultAsync(sendTask, session.DisconnetCancellationToken);
+
             if (!string.IsNullOrEmpty(displayPriceText))
             {
-                sendTask2 = async (string serialNo) => await messageService.SendChangeConfigurationRequest(
+                sendTask = async (string serialNo) => await messageService.SendChangeConfigurationRequest(
                     session.ChargeBoxId, key: "DefaultPrice", value: displayPriceText, serialNo: serialNo);
-                await confirmWaitingMessageSerevice.SendAndWaitUntilResultAsync(sendTask2, session.DisconnetCancellationToken);
+                await confirmWaitingMessageSerevice.SendAndWaitUntilResultAsync(sendTask, session.DisconnetCancellationToken);
             }
 
             if (session.CustomerId == new Guid("298918C0-6BB5-421A-88CC-4922F918E85E") || session.CustomerId == new Guid("9E6BFDCC-09FB-4DAB-A428-43FE507600A3"))

+ 15 - 7
EVCB_OCPP.WSServer/Service/ConfirmWaitingMessageSerevice.cs

@@ -154,14 +154,22 @@ namespace EVCB_OCPP.WSServer.Service
                 foundRequest.SentInterval = 0;
                 analysisResult.RequestId = foundRequest.RequestId;
 
-                using (var db = await maindbContextFactory.CreateDbContextAsync())
+                try
                 {
-                    var sc = await db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefaultAsync();
-                    sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
-                    sc.ReceivedOn = DateTime.UtcNow;
-                    await db.SaveChangesAsync();
-                    //  Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
-
+                    using (var db = await maindbContextFactory.CreateDbContextAsync())
+                    {
+                        var sc = await db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefaultAsync();
+                        sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
+                        sc.ReceivedOn = DateTime.UtcNow;
+                        await db.SaveChangesAsync();
+                        //  Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
+
+                    }
+                }
+                catch (Exception ex)
+                {
+                    logger.LogWarning(string.Format("TryConfirmMessage:{0}", JsonConvert.SerializeObject(analysisResult)));
+                    logger.LogWarning(ex.ToString());
                 }
                 confirmed = true;
 

+ 1 - 1
EVCB_OCPP.WSServer/Service/DbService/MainDbService.cs

@@ -55,7 +55,7 @@ public interface IMainDbService
     Task SetMachineConnectionType(string chargeBoxId, int connectionType, CancellationToken token = default);
     Task UpdateServerMessageUpdateTime(int table_id);
     Task AddMachineConfiguration(string chargeBoxId, string key, string value, bool isReadOnly, bool isExist = true);
-    Task UpdateMachineConfiguration(string chargeBoxId, string item, string empty, bool v, bool isExists = true);
+    Task UpdateMachineConfiguration(string chargeBoxId, string item, string empty, bool isReadOnly, bool isExists = true);
     Task<List<MachineConfigurations>> GetMachineConfiguration(string chargeBoxId);
     Task<object> TryGetResponseFromDb(string msgId, CancellationToken token = default);
 }

+ 3 - 3
EVCB_OCPP.WSServer/Service/DbService/WebDbService.cs

@@ -95,12 +95,12 @@ public class WebDbService
                     """;
 
                 }
-                var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
-                if (result.Count() == 0)
+                var result = await conn.QueryFirstOrDefaultAsync<StationFee>(displayPricestrSql, parameters);
+                if (result == default)
                 {
                     return string.Empty;
                 }
-                var stationPrice = result.First();
+                var stationPrice = result;//.First();
 
                 if (stationPrice.BillingMethod == 1)
                 {

+ 0 - 1
EVCB_OCPP.WSServer/Service/StationConfigService.cs

@@ -59,7 +59,6 @@ public class StationConfigService
     public async Task CheckAndUpdateEvseConfig(WsClientData session, CancellationToken token = default)
     {
         var chargeBoxId = session.ChargeBoxId;
-        await GetEvseCurrentConfig(chargeBoxId);
         var stationId = await webDbService.GetEvseStation(chargeBoxId, token);
         if (stationId is null)
         {

+ 23 - 20
EVCB_OCPP.WSServer/Service/WsService/OcppWebsocketService.cs

@@ -100,8 +100,6 @@ public class OcppWebsocketService : WebsocketService<WsClientData>
     {
         if (context.RequestAborted.IsCancellationRequested) return false;
 
-        string authHeader = context?.Request?.Headers?.Authorization;
-
         session.ISOCPP20 = context.WebSockets.WebSocketRequestedProtocols.Any(x => x.ToLower() == "ocpp2.0");
 
         int securityProfile = 0;
@@ -192,24 +190,26 @@ public class OcppWebsocketService : WebsocketService<WsClientData>
 
         if (securityProfile == 3 && session.UriScheme == "ws")
         {
-            logger.LogInformation("{id} {func} {securityProfile} auth failed", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
+            logger.LogInformation("{id} {func} {securityProfile} connection unsecured", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
+            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
+            return false;
+        }
+
+        if (securityProfile == 2 && session.UriScheme == "ws")
+        {
+            logger.LogInformation("{id} {func} {securityProfile} connection unsecured", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
             context.Response.StatusCode = StatusCodes.Status401Unauthorized;
             return false;
         }
 
         if (securityProfile == 1 || securityProfile == 2)
         {
-            if (securityProfile == 2 && session.UriScheme == "ws")
-            {
-                logger.LogInformation("{id} {func} {securityProfile} connection unsecured", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
-                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
-                return false;
-            }
+            string authHeader = context?.Request?.Headers?.Authorization;
 
             //if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
             if (string.IsNullOrEmpty(authHeader))
             {
-                logger.LogInformation("{id} {func} {securityProfile} auth failed", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
+                logger.LogInformation("{id} {func} {securityProfile} missing auth header", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
                 context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                 return false;
             }
@@ -226,19 +226,22 @@ public class OcppWebsocketService : WebsocketService<WsClientData>
 
             logger.LogInformation("{id} ***********Authorization   ", context.TraceIdentifier);
 
-            if (!string.IsNullOrEmpty(authorizationKey))
+            if (string.IsNullOrEmpty(authorizationKey))
             {
-                //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
-                string base64Encoded = authHeader.Replace("Basic ", "");
-                byte[] data = Convert.FromBase64String(base64Encoded);
-                string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
-                logger.LogInformation("{id} ***********Authorization   " + Encoding.ASCII.GetString(data), context.TraceIdentifier);
-                if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
-                {
-                    authorizated = true;
-                }
+                logger.LogInformation("{id} {func} {securityProfile} auth key not defined in server", context.TraceIdentifier, nameof(ValidateHandshake), securityProfile);
+                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
+                return false;
             }
 
+            //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
+            string base64Encoded = authHeader.Replace("Basic ", "");
+            byte[] data = Convert.FromBase64String(base64Encoded);
+            string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
+            logger.LogInformation("{id} ***********Authorization   " + Encoding.ASCII.GetString(data), context.TraceIdentifier);
+            if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
+            {
+                authorizated = true;
+            }
 
             if (!authorizated)
             {

+ 1 - 1
version.txt

@@ -1 +1 @@
-Docker_v1.1.30
+Docker_v1.1.31