Эх сурвалжийг харах

1. fix IsCheckIn
2. add messageService
3. remove ConnectorStatus cache

Robert 1 жил өмнө
parent
commit
4fd39d53f0

+ 1 - 0
EVCB_OCPP.WSServer/HostedProtalServer.cs

@@ -31,6 +31,7 @@ namespace EVCB_OCPP.WSServer
             services.AddTransient<OCPPWSServer>();
             services.AddTransient<IOCPPWSServerFactory, OCPPWSServerFactory>();
 
+            services.AddSingleton<ServerMessageService>();
             services.AddSingleton<MeterValueDbService>();
             services.AddSingleton<WebDbService>();
             services.AddSingleton<IMainDbService, MainDbService>();

+ 10 - 25
EVCB_OCPP.WSServer/Jobs/ServerSetFeeJob.cs

@@ -27,6 +27,7 @@ public class ServerSetFeeJob : IJob
 {
     private readonly ProtalServer protalServer;
     private readonly SqlConnectionFactory<WebDBConetext> webDbConnectionFactory;
+    private readonly ServerMessageService messageService;
     private readonly IMainDbService mainDbService;
     private readonly ILogger<ServerSetFeeJob> logger;
     //private readonly string webConnectionString;
@@ -35,11 +36,13 @@ public class ServerSetFeeJob : IJob
         ProtalServer protalServer,
         //IConfiguration configuration,
         SqlConnectionFactory<WebDBConetext> sqlConnectionFactory,
+        ServerMessageService messageService,
         IMainDbService mainDbService,
         ILogger<ServerSetFeeJob> logger)
     {
         this.protalServer = protalServer;
         this.webDbConnectionFactory = sqlConnectionFactory;
+        this.messageService = messageService;
         this.mainDbService = mainDbService;
         this.logger = logger;
         //this.webConnectionString = configuration.GetConnectionString("WebDBContext");
@@ -69,34 +72,16 @@ public class ServerSetFeeJob : IJob
 
                 protalServer.UpdateClientDisplayPrice(item.Key, displayPriceText);
 
-                await mainDbService.AddServerMessage(
-                        ChargeBoxId: session.ChargeBoxId,
-                        OutAction: Actions.ChangeConfiguration.ToString(),
-                        OutRequest: new ChangeConfigurationRequest()
-                        {
-                            key = "DefaultPrice",
-                            value = displayPriceText
-                        });
+                await messageService.SendChangeConfigurationRequest(
+                    session.ChargeBoxId, key: "DefaultPrice", value: displayPriceText);
 
                 if (session.CustomerId == new Guid("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
                 {
-                    await mainDbService.AddServerMessage(
-                            ChargeBoxId: session.ChargeBoxId,
-                            OutAction: Actions.ChangeConfiguration.ToString(),
-                            OutRequest: new ChangeConfigurationRequest()
-                            {
-                                key = "ConnectionTimeOut",
-                                value = "120"
-                            });
-
-                    await mainDbService.AddServerMessage(
-                            ChargeBoxId: session.ChargeBoxId,
-                            OutAction: Actions.ChangeConfiguration.ToString(),
-                            OutRequest:  new ChangeConfigurationRequest()
-                            {
-                                key = "MeterValueSampleInterval",
-                                value = "3"
-                            });
+                    await messageService.SendChangeConfigurationRequest(
+                        session.ChargeBoxId, key: "ConnectionTimeOut", value: "120");
+
+                    await messageService.SendChangeConfigurationRequest(
+                        session.ChargeBoxId, key: "MeterValueSampleInterval", value: "3");
                 }
             }
             catch (Exception ex)

+ 51 - 71
EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs

@@ -19,7 +19,6 @@ using System.Data;
 using System.Diagnostics;
 using System.Globalization;
 using SuperSocket.SocketBase;
-using Microsoft.AspNetCore.Http;
 
 namespace EVCB_OCPP.WSServer.Message;
 
@@ -66,6 +65,7 @@ internal partial class ProfileHandler
     private readonly ILogger logger;
     private readonly BlockingTreePrintService blockingTreePrintService;
     private readonly GoogleGetTimePrintService googleGetTimePrintService;
+    private readonly ServerMessageService messageService;
 
     //private readonly string webConnectionString;// = ConfigurationManager.ConnectionStrings[].ConnectionString;
     private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
@@ -88,6 +88,7 @@ internal partial class ProfileHandler
         ILogger<ProfileHandler> logger,
         BlockingTreePrintService blockingTreePrintService,
         GoogleGetTimePrintService googleGetTimePrintService,
+        ServerMessageService messageService,
         OuterHttpClient httpClient)
     {
         //webConnectionString = configuration.GetConnectionString("WebDBContext");
@@ -95,6 +96,7 @@ internal partial class ProfileHandler
         this.logger = logger;
         this.blockingTreePrintService = blockingTreePrintService;
         this.googleGetTimePrintService = googleGetTimePrintService;
+        this.messageService = messageService;
         this.maindbContextFactory = maindbContextFactory;
         this.webDbConnectionFactory = webDbConnectionFactory;
         this.meterValueDbService = meterValueDbService;
@@ -455,17 +457,12 @@ internal partial class ProfileHandler
                             {
                                 if (session.IsBilling)
                                 {
-                                    await mainDbService.AddServerMessage(
-                                            ChargeBoxId: session.ChargeBoxId,
-                                            OutAction: Actions.DataTransfer.ToString(),
-                                            OutRequest:
-                                                new DataTransferRequest()
-                                                {
-                                                    messageId = "ID_TxEnergy",
-                                                    vendorId = "Phihong Technology",
-                                                    data = JsonConvert.SerializeObject(new { txId = _request.transactionId, ConnectorId = _request.connectorId })
-                                                }
-                                            );
+                                    await messageService.SendDataTransferRequest(
+                                        session.ChargeBoxId,
+                                        messageId: "ID_TxEnergy",
+                                        vendorId: "Phihong Technology",
+                                        data: JsonConvert.SerializeObject(new { txId = _request.transactionId, ConnectorId = _request.connectorId })
+                                        );
                                 }
                             }
                             catch (Exception ex)
@@ -776,16 +773,11 @@ internal partial class ProfileHandler
 
                                 if (session.IsBilling)
                                 {
-                                    await mainDbService.AddServerMessage(
-                                        ChargeBoxId: session.ChargeBoxId,
-                                        OutAction: Actions.DataTransfer.ToString(),
-                                        OutRequest:
-                                            new DataTransferRequest()
-                                            {
-                                                messageId = "ID_TxEnergy",
-                                                vendorId = "Phihong Technology",
-                                                data = JsonConvert.SerializeObject(new { txId = _request.transactionId, ConnectorId = transaction.ConnectorId })
-                                            }
+                                    await messageService.SendDataTransferRequest(
+                                        session.ChargeBoxId,
+                                        messageId: "ID_TxEnergy",
+                                        vendorId: "Phihong Technology",
+                                        data: JsonConvert.SerializeObject(new { txId = _request.transactionId, ConnectorId = transaction.ConnectorId })
                                         );
                                 }
 
@@ -1223,32 +1215,26 @@ internal partial class ProfileHandler
 
                                         await db.SaveChangesAsync();
 
-                                        await mainDbService.AddServerMessage(
-                                            ChargeBoxId: session.ChargeBoxId,
-                                            OutAction: Actions.DataTransfer.ToString(),
-                                            OutRequest:
-                                                new DataTransferRequest()
+                                        await messageService.SendDataTransferRequest(
+                                            session.ChargeBoxId,
+                                            messageId: "FinalCost",
+                                            vendorId: "Phihong Technology",
+                                            data: JsonConvert.SerializeObject(new
+                                            {
+                                                txId = txEnergy.TxId,
+                                                description = JsonConvert.SerializeObject(new
                                                 {
-                                                    messageId = "FinalCost",
-                                                    vendorId = "Phihong Technology",
-                                                    data = JsonConvert.SerializeObject(new
-                                                    {
-                                                        txId = txEnergy.TxId,
-                                                        description = JsonConvert.SerializeObject(new
-                                                        {
-                                                            chargedEnergy = chargedEnergy,
-                                                            chargingFee = chargingCost,
-                                                            parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
-                                                            parkingFee = parkingCost,
-                                                            currency = currency,
-                                                            couponPoint = couponPoint,
-                                                            accountBalance = accountBalance - tx.Cost,
-                                                            farewellMessage = farewellMessage
-                                                        })
-                                                    })
-
-                                                }
-                                                );
+                                                    chargedEnergy = chargedEnergy,
+                                                    chargingFee = chargingCost,
+                                                    parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
+                                                    parkingFee = parkingCost,
+                                                    currency = currency,
+                                                    couponPoint = couponPoint,
+                                                    accountBalance = accountBalance - tx.Cost,
+                                                    farewellMessage = farewellMessage
+                                                })
+                                            })
+                                            );
 
                                         await meterValueDbService.InsertAsync(
                                             chargeBoxId: session.ChargeBoxId,
@@ -1291,30 +1277,24 @@ internal partial class ProfileHandler
                                     }
                                     else
                                     {
-                                        await mainDbService.AddServerMessage(
-                                            ChargeBoxId: session.ChargeBoxId,
-                                            OutAction: Actions.DataTransfer.ToString(),
-                                            OutRequest:
-                                             new DataTransferRequest()
-                                             {
-                                                 messageId = "RunningCost",
-                                                 vendorId = "Phihong Technology",
-                                                 data = JsonConvert.SerializeObject(new
-                                                 {
-                                                     txId = txEnergy.TxId,
-                                                     description = JsonConvert.SerializeObject(new
-                                                     {
-                                                         chargedEnergy = chargedEnergy,
-                                                         chargingFee = chargingCost,
-                                                         parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
-                                                         parkingFee = parkingCost,
-                                                         currency = currency
-                                                     })
-
-                                                 })
-
-                                             }
-                                        );
+                                        await messageService.SendDataTransferRequest(
+                                            session.ChargeBoxId,
+                                            messageId: "RunningCost",
+                                            vendorId: "Phihong Technology",
+                                            data: JsonConvert.SerializeObject(new
+                                            {
+                                                txId = txEnergy.TxId,
+                                                description = JsonConvert.SerializeObject(new
+                                                {
+                                                    chargedEnergy = chargedEnergy,
+                                                    chargingFee = chargingCost,
+                                                    parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
+                                                    parkingFee = parkingCost,
+                                                    currency = currency
+                                                })
+
+                                            })
+                                            );
 
                                         await meterValueDbService.InsertAsync(
                                             chargeBoxId: session.ChargeBoxId,

+ 25 - 43
EVCB_OCPP.WSServer/ProtalServer.cs

@@ -1,43 +1,31 @@
 using Dapper;
 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.Basic;
 using EVCB_OCPP.Packet.Messages.Core;
-using EVCB_OCPP.Packet.Messages.RemoteTrigger;
 using EVCB_OCPP.WSServer.Dto;
 using EVCB_OCPP.WSServer.Helper;
 using EVCB_OCPP.WSServer.Message;
 using EVCB_OCPP.WSServer.Service;
 using Microsoft.Extensions.Hosting;
 using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
 
 using OCPPServer.Protocol;
 using OCPPServer.SubProtocol;
 using SuperSocket.SocketBase;
 using SuperSocket.SocketBase.Config;
-using System;
-using System.Collections.Generic;
-using System.Configuration;
 using System.Data;
 using System.Diagnostics;
-using System.Linq;
 using System.Security.Authentication;
-using System.Threading;
-using System.Threading.Tasks;
 using System.Xml.Linq;
 using NLog;
 using Microsoft.Extensions.Configuration;
 using Microsoft.EntityFrameworkCore;
 using Microsoft.Extensions.DependencyInjection;
-using ProtoBuf.Serializers;
-using System.Net;
 using Microsoft.AspNetCore.Builder;
 using NLog.Extensions.Logging;
 using Microsoft.Data.SqlClient;
-using System.Collections.ObjectModel;
 using System.Collections.Concurrent;
 using EVCB_OCPP.WSServer.SuperSocket;
 using Microsoft.Extensions.Logging;
@@ -75,6 +63,7 @@ namespace EVCB_OCPP.WSServer
             , IOCPPWSServerFactory ocppWSServerFactory
             , IConnectionLogdbService connectionLogdbService
             , WebDbService webDbService
+            , ServerMessageService serverMessageService
             , IServiceProvider serviceProvider,
             OuterHttpClient httpClient)
         {
@@ -88,6 +77,7 @@ namespace EVCB_OCPP.WSServer
             this.ocppWSServerFactory = ocppWSServerFactory;
             this.connectionLogdbService = connectionLogdbService;
             this.webDbService = webDbService;
+            this.messageService = serverMessageService;
             this.httpClient = httpClient;
             isInDocker = !string.IsNullOrEmpty(configuration["DOTNET_RUNNING_IN_CONTAINER"]);
 
@@ -115,6 +105,7 @@ namespace EVCB_OCPP.WSServer
         private readonly IOCPPWSServerFactory ocppWSServerFactory;
         private readonly IConnectionLogdbService connectionLogdbService;
         private readonly WebDbService webDbService;
+        private readonly ServerMessageService messageService;
         private readonly ProfileHandler profileHandler;//= new ProfileHandler();
         //private readonly string webConnectionString;// = ConfigurationManager.ConnectionStrings["WebDBContext"].ConnectionString;
         private readonly bool isInDocker;
@@ -500,16 +491,6 @@ namespace EVCB_OCPP.WSServer
             _cts?.Cancel();
         }
 
-        private async void CheckEVSEConfigure(string chargeBoxId)
-        {
-            if (string.IsNullOrEmpty(chargeBoxId)) return;
-            await mainDbService.AddServerMessage(
-                ChargeBoxId: chargeBoxId,
-                OutAction: Actions.GetConfiguration.ToString(),
-                OutRequest: new GetConfigurationRequest() { key = new List<string>() }
-                );
-        }
-
         private void OpenNetwork()
         {
 
@@ -922,21 +903,23 @@ 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)
                                     {
-                                        CheckEVSEConfigure(session.ChargeBoxId);
+                                        session.IsCheckIn = true;
+
+                                        await messageService.SendGetEVSEConfigureRequest(session.ChargeBoxId);
+
                                         if (session.CustomerId == new Guid("298918C0-6BB5-421A-88CC-4922F918E85E") || session.CustomerId == new Guid("9E6BFDCC-09FB-4DAB-A428-43FE507600A3"))
                                         {
-                                            await mainDbService.AddServerMessage(
-                                                ChargeBoxId: session.ChargeBoxId,
-                                                OutAction: Actions.ChangeConfiguration.ToString(),
-                                                OutRequest: new ChangeConfigurationRequest()
-                                                {
-                                                    key = "TimeOffset",
-                                                    value = "+08:00"
-                                                });
+                                            await messageService.SendChangeConfigurationRequest(
+                                                session.ChargeBoxId, key: "TimeOffset", value: "+08:00");
                                         }
+
+                                        await messageService.SendDataTransferRequest(
+                                            session.ChargeBoxId,
+                                            messageId: "ID_FirmwareVersion",
+                                            vendorId: "Phihong Technology",
+                                            data: string.Empty);
                                     }
                                     else
                                     {
@@ -963,17 +946,16 @@ namespace EVCB_OCPP.WSServer
                                     var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
                                     if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
                                     {
-                                        await mainDbService.AddServerMessage(
-                                            ChargeBoxId: session.ChargeBoxId,
-                                            OutAction: Actions.DataTransfer.ToString(),
-                                            OutRequest: new DataTransferRequest() { 
-                                                messageId = "SetUserPrice", 
-                                                vendorId = "Phihong Technology",
-                                                data = JsonConvert.SerializeObject(
-                                                    new {
-                                                        idToken = authorizeRequest.idTag, 
-                                                        price = session.UserDisplayPrices[authorizeRequest.idTag] 
-                                                    }) }
+                                        await messageService.SendDataTransferRequest(
+                                            session.ChargeBoxId,
+                                            messageId: "SetUserPrice",
+                                            vendorId: "Phihong Technology",
+                                            data: JsonConvert.SerializeObject(
+                                                new
+                                                {
+                                                    idToken = authorizeRequest.idTag,
+                                                    price = session.UserDisplayPrices[authorizeRequest.idTag]
+                                                })
                                             );
                                     }
                                 }

+ 12 - 12
EVCB_OCPP.WSServer/Service/MainDbService.cs

@@ -69,7 +69,7 @@ public class MainDbService : IMainDbService
     }
 
     private const string CustomerMemCacheKeyFromat = "Customer_{0}";
-    private const string ChargeBoxConnectorIdMemCacheKeyFromat = "Connector_{0}{1}";
+    //private const string ChargeBoxConnectorIdMemCacheKeyFromat = "Connector_{0}{1}";
 
     private readonly IDbContextFactory<MainDBContext> contextFactory;
     private readonly SqlConnectionFactory<MainDBContext> sqlConnectionFactory;
@@ -158,24 +158,24 @@ public class MainDbService : IMainDbService
 
         await db.SaveChangesAsync();
 
-        memoryCache.Set(
-            string.Format(ChargeBoxConnectorIdMemCacheKeyFromat, ChargeBoxId, ConnectorId)
-            , _currentStatus, TimeSpan.FromHours(12));
+        //memoryCache.Set(
+        //    string.Format(ChargeBoxConnectorIdMemCacheKeyFromat, ChargeBoxId, ConnectorId)
+        //    , _currentStatus, TimeSpan.FromHours(12));
     }
 
     public async ValueTask<ConnectorStatus> GetConnectorStatus(string ChargeBoxId, int ConnectorId)
     {
-        var key = string.Format(ChargeBoxConnectorIdMemCacheKeyFromat, ChargeBoxId, ConnectorId);
-        if (memoryCache.TryGetValue<ConnectorStatus>(key, out var status))
-        {
-            return status;
-        }
+        //var key = string.Format(ChargeBoxConnectorIdMemCacheKeyFromat, ChargeBoxId, ConnectorId);
+        //if (memoryCache.TryGetValue<ConnectorStatus>(key, out var status))
+        //{
+        //    return status;
+        //}
 
         using var db = await contextFactory.CreateDbContextAsync();
         var statusFromDb = await db.ConnectorStatus.Where(x => x.ChargeBoxId == ChargeBoxId
                             && x.ConnectorId == ConnectorId).AsNoTracking().FirstOrDefaultAsync();
 
-        memoryCache.Set(key, statusFromDb, TimeSpan.FromHours(12));
+        //memoryCache.Set(key, statusFromDb, TimeSpan.FromHours(12));
         return statusFromDb;
     }
 
@@ -185,8 +185,8 @@ public class MainDbService : IMainDbService
         //await UpdateConnectorStatusEF(Id, Status);
         await UpdateConnectorStatusDapper(Id, Status);
 
-        var key = string.Format(ChargeBoxConnectorIdMemCacheKeyFromat, Status.ChargeBoxId, Status.ConnectorId);
-        memoryCache.Set(key, Status, TimeSpan.FromHours(12));
+        //var key = string.Format(ChargeBoxConnectorIdMemCacheKeyFromat, Status.ChargeBoxId, Status.ConnectorId);
+        //memoryCache.Set(key, Status, TimeSpan.FromHours(12));
         return;
     }
 

+ 55 - 0
EVCB_OCPP.WSServer/Service/ServerMessageService.cs

@@ -0,0 +1,55 @@
+using EVCB_OCPP.Packet.Features;
+using EVCB_OCPP.Packet.Messages.Core;
+using Microsoft.Extensions.Logging;
+
+namespace EVCB_OCPP.WSServer.Service;
+
+public class ServerMessageService
+{
+    public ServerMessageService(
+        IMainDbService mainDbService
+        , ILogger<ServerMessageService> logger)
+    {
+        this.mainDbService = mainDbService;
+        this.logger = logger;
+    }
+
+    private readonly IMainDbService mainDbService;
+    private readonly ILogger<ServerMessageService> logger;
+
+    internal async Task SendGetEVSEConfigureRequest(string chargeBoxId)
+    {
+        if (string.IsNullOrEmpty(chargeBoxId)) return;
+        await mainDbService.AddServerMessage(
+            ChargeBoxId: chargeBoxId,
+            OutAction: Actions.GetConfiguration.ToString(),
+            OutRequest: new GetConfigurationRequest() { key = new List<string>() }
+            );
+    }
+
+    internal Task SendChangeConfigurationRequest(string chargeBoxId, string key, string value)
+    {
+        return mainDbService.AddServerMessage(
+            ChargeBoxId: chargeBoxId,
+            OutAction: Actions.ChangeConfiguration.ToString(),
+            OutRequest: new ChangeConfigurationRequest()
+            {
+                key = key,
+                value = value
+            });
+    }
+
+    internal Task SendDataTransferRequest(string chargeBoxId, string messageId, string vendorId, string data)
+    {
+        return mainDbService.AddServerMessage(
+            ChargeBoxId: chargeBoxId,
+            OutAction: Actions.DataTransfer.ToString(),
+            OutRequest: new DataTransferRequest()
+            {
+                messageId = messageId,
+                vendorId = vendorId,
+                data = data
+            }
+            );
+    }
+}