Robert 1 年之前
父節點
當前提交
5aacbcd9bc
共有 34 個文件被更改,包括 372 次插入261 次删除
  1. 14 26
      Dockerfile
  2. 18 4
      Dockerfile2
  3. 34 0
      Dockerfile_dev
  4. 1 1
      EVCB_OCPP.WSServer/EVCB_OCPP.WSServer.csproj
  5. 0 1
      EVCB_OCPP.WSServer/GlobalConfig.cs
  6. 3 4
      EVCB_OCPP.WSServer/Helper/AddPortalDbContext.cs
  7. 9 0
      EVCB_OCPP.WSServer/HostedProtalServer.cs
  8. 1 1
      EVCB_OCPP.WSServer/Jobs/DenyModelCheckJob.cs
  9. 37 0
      EVCB_OCPP.WSServer/Jobs/GoogleCheckJob.cs
  10. 4 3
      EVCB_OCPP.WSServer/Jobs/HealthCheckTriggerJob.cs
  11. 2 2
      EVCB_OCPP.WSServer/Jobs/HeartBeatCheckJob.cs
  12. 2 1
      EVCB_OCPP.WSServer/Jobs/ServerMessageJob.cs
  13. 2 2
      EVCB_OCPP.WSServer/Jobs/ServerSetFeeJob.cs
  14. 83 82
      EVCB_OCPP.WSServer/Jobs/ServerUpdateJob.cs
  15. 1 1
      EVCB_OCPP.WSServer/Jobs/SmartChargingJob.cs
  16. 26 22
      EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs
  17. 4 4
      EVCB_OCPP.WSServer/Message/FirmwareManagementProfileHandler.cs
  18. 3 3
      EVCB_OCPP.WSServer/Message/LocalAuthListManagementProfileHandler.cs
  19. 2 2
      EVCB_OCPP.WSServer/Message/RemoteTriggerHandler.cs
  20. 4 4
      EVCB_OCPP.WSServer/Message/ReservationProfileHandler.cs
  21. 4 4
      EVCB_OCPP.WSServer/Message/SmartChargingProfileHandler.cs
  22. 4 0
      EVCB_OCPP.WSServer/Program.cs
  23. 13 11
      EVCB_OCPP.WSServer/ProtalServer.cs
  24. 7 4
      EVCB_OCPP.WSServer/Service/BusinessServiceFactory.cs
  25. 4 4
      EVCB_OCPP.WSServer/Service/ConnectionLogdbService.cs
  26. 5 1
      EVCB_OCPP.WSServer/Service/HttpClientService.cs
  27. 7 3
      EVCB_OCPP.WSServer/Service/LocalBusinessService.cs
  28. 14 34
      EVCB_OCPP.WSServer/Service/MainDbService.cs
  29. 4 3
      EVCB_OCPP.WSServer/Service/MeterValueDbService.cs
  30. 22 14
      EVCB_OCPP.WSServer/Service/OuterBusinessService.cs
  31. 6 1
      EVCB_OCPP.WSServer/Service/OuterHttpClient.cs
  32. 18 0
      EVCB_OCPP.WSServer/appsettings.json
  33. 9 14
      SocketEngine/SocketSession.cs
  34. 5 5
      TestTool.RemoteTriggerAPP/MainWindow.xaml.cs

+ 14 - 26
Dockerfile

@@ -1,8 +1,12 @@
 #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
 #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
 
 
-FROM mcr.microsoft.com/dotnet/sdk:7.0 AS base
-#RUN sed -i 's/TLSv1.2/TLSv1/g' /etc/ssl/openssl.cnf
-#RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf
+FROM mcr.microsoft.com/dotnet/sdk:7.0 AS final
+EXPOSE 80
+EXPOSE 443
+EXPOSE 2222 
+
+RUN sed -i 's/TLSv1.2/TLSv1/g' /etc/ssl/openssl.cnf
+RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf
 
 
 RUN apt-get update \
 RUN apt-get update \
     && apt-get install -y --no-install-recommends dialog \
     && apt-get install -y --no-install-recommends dialog \
@@ -17,28 +21,12 @@ RUN dotnet tool install --tool-path /tools dotnet-trace \
  && dotnet tool install --tool-path /tools dotnet-counters \
  && dotnet tool install --tool-path /tools dotnet-counters \
  && dotnet tool install --tool-path /tools dotnet-dump \
  && dotnet tool install --tool-path /tools dotnet-dump \
  && dotnet tool install --tool-path /tools dotnet-gcdump
  && dotnet tool install --tool-path /tools dotnet-gcdump
-
-EXPOSE 80
-EXPOSE 443
-EXPOSE 2222 
-WORKDIR /app
-
-FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
+ 
+RUN apt update
+RUN apt install -y linux-perf
+#RUN echo 0 > /proc/sys/kernel/kptr_restrict
 WORKDIR /src
 WORKDIR /src
-COPY ["EVCB_OCPP.WSServer/EVCB_OCPP.WSServer.csproj", "EVCB_OCPP.WSServer/"]
-COPY ["SuperWebSocket/SuperWebSocket.csproj", "SuperWebSocket/"]
-COPY ["SocketBase/SuperSocket.SocketBase.csproj", "SocketBase/"]
-COPY ["SocketCommon/SuperSocket.Common.csproj", "SocketCommon/"]
-COPY ["SocketEngine/SuperSocket.SocketEngine.csproj", "SocketEngine/"]
-RUN dotnet restore "EVCB_OCPP.WSServer/EVCB_OCPP.WSServer.csproj"
 COPY . .
 COPY . .
-WORKDIR "/src/EVCB_OCPP.WSServer"
-RUN dotnet build "EVCB_OCPP.WSServer.csproj" -c Release -o /app/build
-
-FROM build AS publish
-RUN dotnet publish "EVCB_OCPP.WSServer.csproj" -c Release -o /app/publish /p:UseAppHost=false
-
-FROM base AS final
-WORKDIR /app
-COPY --from=publish /app/publish .
-ENTRYPOINT ["/bin/bash", "-c", "/usr/sbin/sshd && dotnet EVCB_OCPP.WSServer.dll"]
+RUN export DOTNET_PerfMapEnabled=1
+RUN dotnet build ./EVCB_OCPP.WSServer/EVCB_OCPP.WSServer.csproj
+CMD dotnet run --project ./EVCB_OCPP.WSServer/EVCB_OCPP.WSServer.csproj

+ 18 - 4
Dockerfile2

@@ -3,14 +3,28 @@
 FROM mcr.microsoft.com/dotnet/sdk:7.0 AS final
 FROM mcr.microsoft.com/dotnet/sdk:7.0 AS final
 EXPOSE 80
 EXPOSE 80
 EXPOSE 443
 EXPOSE 443
-EXPOSE 54088
+EXPOSE 2222 
+
 RUN sed -i 's/TLSv1.2/TLSv1/g' /etc/ssl/openssl.cnf
 RUN sed -i 's/TLSv1.2/TLSv1/g' /etc/ssl/openssl.cnf
 RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf
 RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf
-RUN dotnet tool install --tool-path /bin dotnet-trace
-RUN dotnet tool install --tool-path /bin dotnet-counters
+
+RUN apt-get update \
+    && apt-get install -y --no-install-recommends dialog \
+    && apt-get install -y --no-install-recommends openssh-server \
+	&& mkdir -p /run/sshd \
+    && echo "root:Docker!" | chpasswd 
+	
+COPY sshd_config /etc/ssh/sshd_config
+
+# Install dotnet debug tools
+RUN dotnet tool install --tool-path /tools dotnet-trace \
+ && dotnet tool install --tool-path /tools dotnet-counters \
+ && dotnet tool install --tool-path /tools dotnet-dump \
+ && dotnet tool install --tool-path /tools dotnet-gcdump
+ 
 RUN apt update
 RUN apt update
 RUN apt install -y linux-perf
 RUN apt install -y linux-perf
-RUN echo 0 > /proc/sys/kernel/kptr_restrict
+#RUN echo 0 > /proc/sys/kernel/kptr_restrict
 WORKDIR /src
 WORKDIR /src
 COPY . .
 COPY . .
 RUN export DOTNET_PerfMapEnabled=1
 RUN export DOTNET_PerfMapEnabled=1

+ 34 - 0
Dockerfile_dev

@@ -0,0 +1,34 @@
+#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
+
+FROM mcr.microsoft.com/dotnet/sdk:7.0 AS final
+EXPOSE 80
+EXPOSE 443
+EXPOSE 54088 
+EXPOSE 54089 
+EXPOSE 2222 
+
+#RUN sed -i 's/TLSv1.2/TLSv1/g' /etc/ssl/openssl.cnf
+#RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf
+
+RUN apt-get update \
+    && apt-get install -y --no-install-recommends dialog \
+    && apt-get install -y --no-install-recommends openssh-server \
+	&& mkdir -p /run/sshd \
+    && echo "root:Docker!" | chpasswd 
+	
+COPY sshd_config /etc/ssh/sshd_config
+
+# Install dotnet debug tools
+RUN dotnet tool install --tool-path /tools dotnet-trace \
+ && dotnet tool install --tool-path /tools dotnet-counters \
+ && dotnet tool install --tool-path /tools dotnet-dump \
+ && dotnet tool install --tool-path /tools dotnet-gcdump
+ 
+#RUN apt update
+#RUN apt install -y linux-perf
+#RUN echo 0 > /proc/sys/kernel/kptr_restrict
+WORKDIR /src
+COPY . .
+#RUN export DOTNET_PerfMapEnabled=1
+RUN dotnet build ./EVCB_OCPP.WSServer/EVCB_OCPP.WSServer.csproj
+CMD dotnet run --project ./EVCB_OCPP.WSServer/EVCB_OCPP.WSServer.csproj

+ 1 - 1
EVCB_OCPP.WSServer/EVCB_OCPP.WSServer.csproj

@@ -20,7 +20,7 @@
   </ItemGroup>
   </ItemGroup>
   <ItemGroup>
   <ItemGroup>
     <Content Include="appsettings.json">
     <Content Include="appsettings.json">
-      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
     </Content>
     </Content>
     <Content Include="DLL\EVCB_OCPP20.Packet.dll" />
     <Content Include="DLL\EVCB_OCPP20.Packet.dll" />
   </ItemGroup>
   </ItemGroup>

+ 0 - 1
EVCB_OCPP.WSServer/GlobalConfig.cs

@@ -141,7 +141,6 @@ namespace EVCB_OCPP.WSServer
             catch (Exception ex)
             catch (Exception ex)
             {
             {
                 Console.WriteLine(key + " Load from APPConfig " + ex.ToString());
                 Console.WriteLine(key + " Load from APPConfig " + ex.ToString());
-
             }
             }
 
 
             return result;
             return result;

+ 3 - 4
EVCB_OCPP.WSServer/Helper/AddPortalDbContext.cs

@@ -3,7 +3,9 @@ using Microsoft.Data.SqlClient;
 using Microsoft.EntityFrameworkCore;
 using Microsoft.EntityFrameworkCore;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
 using MongoDB.Driver.Core.Configuration;
 using MongoDB.Driver.Core.Configuration;
+using NLog.Extensions.Logging;
 using System;
 using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Configuration;
 using System.Configuration;
@@ -108,10 +110,7 @@ public static class AddPortalDbContext
             {
             {
                 dbOptions.CommandTimeout(commandTimeout);
                 dbOptions.CommandTimeout(commandTimeout);
             });
             });
-            if(logToConsole)
-            {
-                options.LogTo(Console.WriteLine);
-            }
+            options.UseLoggerFactory(serviceProvider.GetRequiredService<ILoggerFactory>());
         });
         });
     }
     }
 
 

+ 9 - 0
EVCB_OCPP.WSServer/HostedProtalServer.cs

@@ -119,6 +119,15 @@ namespace EVCB_OCPP.WSServer
                         .WithIntervalInMinutes(5)
                         .WithIntervalInMinutes(5)
                         .RepeatForever())
                         .RepeatForever())
                 );
                 );
+
+                q.ScheduleJob<GoogleCheckJob>(trigger =>
+                    trigger
+                    .WithIdentity("GoogleCheckJobTrigger")
+                    .StartNow()
+                    .WithSimpleSchedule(x => x
+                        .WithIntervalInSeconds(5)
+                        .RepeatForever())
+                );
             });
             });
 
 
             services.AddQuartzHostedService(opt =>
             services.AddQuartzHostedService(opt =>

+ 1 - 1
EVCB_OCPP.WSServer/Jobs/DenyModelCheckJob.cs

@@ -37,7 +37,7 @@ public class DenyModelCheckJob : IJob
 
 
     public async Task Execute(IJobExecutionContext context)
     public async Task Execute(IJobExecutionContext context)
     {
     {
-        //logger.LogDebug("{0} Started", nameof(DenyModelCheckJob));
+        logger.LogDebug("{0} Started", nameof(DenyModelCheckJob));
         try
         try
         {
         {
             GlobalConfig.DenyModelNames = await webDbService.GetDenyModelNames();
             GlobalConfig.DenyModelNames = await webDbService.GetDenyModelNames();

+ 37 - 0
EVCB_OCPP.WSServer/Jobs/GoogleCheckJob.cs

@@ -0,0 +1,37 @@
+using EVCB_OCPP.WSServer.Service;
+using Microsoft.Extensions.Logging;
+using Quartz;
+using RestSharp;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.WSServer.Jobs
+{
+    [DisallowConcurrentExecution]
+    public class GoogleCheckJob : IJob
+    {
+        public GoogleCheckJob(ILogger<GoogleCheckJob> logger)
+        {
+            this.logger = logger;
+        }
+
+        private readonly ILogger<GoogleCheckJob> logger;
+
+        public async Task Execute(IJobExecutionContext context)
+        {
+            var client = new RestClient("http://www.google.com");
+            var stopWatch = Stopwatch.StartNew();
+            await client.ExecuteAsync(new RestRequest("", method: Method.Get));
+            stopWatch.Stop();
+
+            if (stopWatch.ElapsedMilliseconds > 1000)
+            {
+                logger.LogInformation($"Google Get Cost {stopWatch.ElapsedMilliseconds}ms");
+            }
+        }
+    }
+}

+ 4 - 3
EVCB_OCPP.WSServer/Jobs/HealthCheckTriggerJob.cs

@@ -24,9 +24,9 @@ public class HealthCheckTriggerJob : IJob
     private readonly ProtalServer protalServer;
     private readonly ProtalServer protalServer;
     private readonly ILogger<HealthCheckTriggerJob> logger;
     private readonly ILogger<HealthCheckTriggerJob> logger;
 
 
-    public async Task Execute(IJobExecutionContext context)
+    public Task Execute(IJobExecutionContext context)
     {
     {
-        //logger.LogDebug("{0} Started", nameof(HealthCheckTriggerJob));
+        logger.LogDebug("{0} Started", nameof(HealthCheckTriggerJob));
 
 
         Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
         Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
 
 
@@ -34,8 +34,9 @@ public class HealthCheckTriggerJob : IJob
 
 
         foreach (var session in removeClients)
         foreach (var session in removeClients)
         {
         {
-            Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: LastActiveTime{1})", session.ChargeBoxId, session.LastActiveTime));
+            logger.LogDebug("Server forced to shut down ChargeBox ({0}: LastActiveTime{1})", session.ChargeBoxId, session.LastActiveTime);
             protalServer.RemoveClient(session);
             protalServer.RemoveClient(session);
         }
         }
+        return Task.CompletedTask;
     }
     }
 }
 }

+ 2 - 2
EVCB_OCPP.WSServer/Jobs/HeartBeatCheckJob.cs

@@ -32,7 +32,7 @@ public class HeartBeatCheckJob : IJob
 
 
     public async Task Execute(IJobExecutionContext context)
     public async Task Execute(IJobExecutionContext context)
     {
     {
-        //logger.LogDebug("{0} Started", nameof(HeartBeatCheckJob));
+        logger.LogDebug("{0} Started", nameof(HeartBeatCheckJob));
         try
         try
         {
         {
             Stopwatch watch = new Stopwatch();
             Stopwatch watch = new Stopwatch();
@@ -65,7 +65,7 @@ public class HeartBeatCheckJob : IJob
                     }
                     }
 
 
                     await db.SaveChangesAsync();
                     await db.SaveChangesAsync();
-                    transaction.Commit();
+                    await transaction.CommitAsync();
                     db.ChangeTracker.Clear();
                     db.ChangeTracker.Clear();
                 }
                 }
                 catch (Exception ex)
                 catch (Exception ex)

+ 2 - 1
EVCB_OCPP.WSServer/Jobs/ServerMessageJob.cs

@@ -38,6 +38,7 @@ public class ServerMessageJob : IJob
 
 
     public async Task Execute(IJobExecutionContext context)
     public async Task Execute(IJobExecutionContext context)
     {
     {
+        //logger.LogDebug("{0} Started", nameof(ServerMessageJob));
         try
         try
         {
         {
             await ExecuteTrigger();
             await ExecuteTrigger();
@@ -53,7 +54,7 @@ public class ServerMessageJob : IJob
         protalServer.RemoveConfirmMessage();
         protalServer.RemoveConfirmMessage();
 
 
         BasicMessageHandler msgAnalyser = new BasicMessageHandler();
         BasicMessageHandler msgAnalyser = new BasicMessageHandler();
-        using var db = maindbContextFactory.CreateDbContext();
+        using var db = await maindbContextFactory.CreateDbContextAsync();
         var dateTimeNow = DateTime.UtcNow;
         var dateTimeNow = DateTime.UtcNow;
         DateTime startDt = dateTimeNow.AddSeconds(-30);
         DateTime startDt = dateTimeNow.AddSeconds(-30);
         DateTime dt = new DateTime(1991, 1, 1);
         DateTime dt = new DateTime(1991, 1, 1);

+ 2 - 2
EVCB_OCPP.WSServer/Jobs/ServerSetFeeJob.cs

@@ -47,10 +47,10 @@ public class ServerSetFeeJob : IJob
 
 
     public async Task Execute(IJobExecutionContext context)
     public async Task Execute(IJobExecutionContext context)
     {
     {
-        //logger.LogDebug("{0} Started", nameof(ServerSetFeeJob));
+        logger.LogDebug("{0} Started", nameof(ServerSetFeeJob));
         //BasicMessageHandler msgAnalyser = new BasicMessageHandler();
         //BasicMessageHandler msgAnalyser = new BasicMessageHandler();
         Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
         Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
-        //using var db = maindbContextFactory.CreateDbContext();
+        //using var db = maindbContextFactory.CreateDbContextAsync();
         foreach (var item in _copyClientDic)
         foreach (var item in _copyClientDic)
         {
         {
             try
             try

+ 83 - 82
EVCB_OCPP.WSServer/Jobs/ServerUpdateJob.cs

@@ -22,7 +22,7 @@ public class ServerUpdateJob : IJob
     private readonly ILogger<ServerUpdateJob> logger;
     private readonly ILogger<ServerUpdateJob> logger;
 
 
     public ServerUpdateJob(
     public ServerUpdateJob(
-        ProtalServer protalServer, 
+        ProtalServer protalServer,
         IDbContextFactory<MainDBContext> maindbContextFactory,
         IDbContextFactory<MainDBContext> maindbContextFactory,
         ILogger<ServerUpdateJob> logger)
         ILogger<ServerUpdateJob> logger)
     {
     {
@@ -33,104 +33,105 @@ public class ServerUpdateJob : IJob
 
 
     public async Task Execute(IJobExecutionContext context)
     public async Task Execute(IJobExecutionContext context)
     {
     {
-        //logger.LogDebug("{0} Started", nameof(ServerUpdateJob));
+        logger.LogDebug("{0} Started", nameof(ServerUpdateJob));
         BasicMessageHandler msgAnalyser = new BasicMessageHandler();
         BasicMessageHandler msgAnalyser = new BasicMessageHandler();
         Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
         Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
         var checkUpdateDt = DateTime.UtcNow;
         var checkUpdateDt = DateTime.UtcNow;
-        using (var db = maindbContextFactory.CreateDbContext())
+        List<string> needUpdateChargers = new List<string>();
+        using (var db = await maindbContextFactory.CreateDbContextAsync())
         {
         {
             //var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
             //var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
             //    x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
             //    x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
             //    .Select(x => new { x.Id, x.ChargeBoxId, x.FW_AssignedMachineVersionId }).ToList();
             //    .Select(x => new { x.Id, x.ChargeBoxId, x.FW_AssignedMachineVersionId }).ToList();
 
 
-            var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true &&
+            needUpdateChargers = await db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true &&
               x.FW_AssignedVersion != x.FW_VersionReport && x.Online == true)
               x.FW_AssignedVersion != x.FW_VersionReport && x.Online == true)
-              .Select(x => x.ChargeBoxId).AsNoTracking().ToList();
+              .Select(x => x.ChargeBoxId).AsNoTracking().ToListAsync();
+        }
 
 
-            foreach (var chargeBoxId in needUpdateChargers)
+        foreach (var chargeBoxId in needUpdateChargers)
+        {
+            try
             {
             {
-                try
+                ClientData session;
+                if (_copyClientDic.TryGetValue(chargeBoxId, out session))
                 {
                 {
-                    ClientData session;
-                    if (_copyClientDic.TryGetValue(chargeBoxId, out session))
-                    {
 
 
-                        string requestId = Guid.NewGuid().ToString();
-                        // using (var db = maindbContextFactory.CreateDbContext())
+                    string requestId = Guid.NewGuid().ToString();
+                    // using (var db = maindbContextFactory.CreateDbContextAsync())
 
 
-                        if (session.IsCheckIn && !session.ISOCPP20)
-                        {
+                    if (session.IsCheckIn && !session.ISOCPP20)
+                    {
 
 
-                            var _request = new TriggerMessageRequest()
-                            {
-                                requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
-                            };
-
-                            var uuid = session.queue.store(_request);
-                            string rawRequest = BasicMessageHandler.GenerateRequest(uuid, _request.Action, _request);
-                            protalServer.SendMsg(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
-
-                            #region OCTT   ,測試韌體更新方式
-                            //--------------------> OCTT   ,測試韌體更新方式
-                            //{
-                            //    var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
-                            //        x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
-                            //        .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
-
-                            //    if (machine != null)
-                            //    {
-                            //        var mv = db.MachineVersion.Include(c => c.PublishVersion)
-                            //         .Include(c => c.PublishVersion.PublishVersionFiles)
-                            //         .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
-                            //         .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
-
-                            //        string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
-
-                            //        var _updateFWrequest = new UpdateFirmwareRequest()
-                            //        {
-                            //            location = new Uri(downloadUrl),
-                            //            retries = 3,
-                            //            retrieveDate = DateTime.UtcNow,
-                            //            retryInterval = 10
-                            //        };
-                            //        db.MachineOperateRecord.Add(new MachineOperateRecord()
-                            //        {
-                            //            CreatedOn = DateTime.UtcNow,
-                            //            ChargeBoxId = session.ChargeBoxId,
-                            //            SerialNo = requestId,
-                            //            RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
-                            //            EVSE_Status = 0,
-                            //            EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
-                            //            Status = 0,
-                            //            RequestType = 0,
-
-                            //        });
-
-                            //        db.ServerMessage.Add(new ServerMessage()
-                            //        {
-                            //            ChargeBoxId = session.ChargeBoxId,
-                            //            CreatedBy = "Server",
-                            //            CreatedOn = DateTime.UtcNow,
-                            //            OutAction = _updateFWrequest.Action.ToString(),
-                            //            OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
-                            //            SerialNo = requestId,
-                            //            InMessage = string.Empty
-
-                            //        });
-
-                            //        await db.SaveChangesAsync();
-
-                            //    }
-
-                            //}
-                            #endregion
-                        }
+                        var _request = new TriggerMessageRequest()
+                        {
+                            requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
+                        };
+
+                        var uuid = session.queue.store(_request);
+                        string rawRequest = BasicMessageHandler.GenerateRequest(uuid, _request.Action, _request);
+                        protalServer.SendMsg(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
+
+                        #region OCTT   ,測試韌體更新方式
+                        //--------------------> OCTT   ,測試韌體更新方式
+                        //{
+                        //    var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
+                        //        x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
+                        //        .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
+
+                        //    if (machine != null)
+                        //    {
+                        //        var mv = db.MachineVersion.Include(c => c.PublishVersion)
+                        //         .Include(c => c.PublishVersion.PublishVersionFiles)
+                        //         .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
+                        //         .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
+
+                        //        string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
+
+                        //        var _updateFWrequest = new UpdateFirmwareRequest()
+                        //        {
+                        //            location = new Uri(downloadUrl),
+                        //            retries = 3,
+                        //            retrieveDate = DateTime.UtcNow,
+                        //            retryInterval = 10
+                        //        };
+                        //        db.MachineOperateRecord.Add(new MachineOperateRecord()
+                        //        {
+                        //            CreatedOn = DateTime.UtcNow,
+                        //            ChargeBoxId = session.ChargeBoxId,
+                        //            SerialNo = requestId,
+                        //            RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
+                        //            EVSE_Status = 0,
+                        //            EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
+                        //            Status = 0,
+                        //            RequestType = 0,
+
+                        //        });
+
+                        //        db.ServerMessage.Add(new ServerMessage()
+                        //        {
+                        //            ChargeBoxId = session.ChargeBoxId,
+                        //            CreatedBy = "Server",
+                        //            CreatedOn = DateTime.UtcNow,
+                        //            OutAction = _updateFWrequest.Action.ToString(),
+                        //            OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
+                        //            SerialNo = requestId,
+                        //            InMessage = string.Empty
+
+                        //        });
+
+                        //        await db.SaveChangesAsync();
+
+                        //    }
+
+                        //}
+                        #endregion
                     }
                     }
                 }
                 }
-                catch (Exception ex)
-                {
-                    logger.LogError("serverUpdateTrigger ChargeBoxId:{0}  Ex:{1}", chargeBoxId, ex.ToString());
-                }
+            }
+            catch (Exception ex)
+            {
+                logger.LogError("serverUpdateTrigger ChargeBoxId:{0}  Ex:{1}", chargeBoxId, ex.ToString());
             }
             }
         }
         }
     }
     }

+ 1 - 1
EVCB_OCPP.WSServer/Jobs/SmartChargingJob.cs

@@ -38,7 +38,7 @@ public class SmartChargingJob : IJob
 
 
     public async Task Execute(IJobExecutionContext context)
     public async Task Execute(IJobExecutionContext context)
     {
     {
-        //logger.LogDebug("{0} Started", nameof(SmartChargingJob));
+        logger.LogDebug("{0} Started", nameof(SmartChargingJob));
         List<StationInfoDto> stations = null;
         List<StationInfoDto> stations = null;
         using (SqlConnection conn = await webDbConnectionFactory.CreateAsync())
         using (SqlConnection conn = await webDbConnectionFactory.CreateAsync())
         {
         {

+ 26 - 22
EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs

@@ -88,11 +88,11 @@ internal partial class ProfileHandler
     //private readonly IDbContextFactory<MeterValueDBContext> metervaluedbContextFactory;
     //private readonly IDbContextFactory<MeterValueDBContext> metervaluedbContextFactory;
     private readonly IBusinessServiceFactory businessServiceFactory;
     private readonly IBusinessServiceFactory businessServiceFactory;
     private readonly IMainDbService mainDbService;
     private readonly IMainDbService mainDbService;
-    private OuterHttpClient httpClient = new OuterHttpClient();
+    private OuterHttpClient httpClient;
 
 
     public ProfileHandler(
     public ProfileHandler(
         IConfiguration configuration,
         IConfiguration configuration,
-        IDbContextFactory<MainDBContext> maindbContextFactory, 
+        IDbContextFactory<MainDBContext> maindbContextFactory,
         SqlConnectionFactory<WebDBConetext> webDbConnectionFactory,
         SqlConnectionFactory<WebDBConetext> webDbConnectionFactory,
         //IDbContextFactory<MeterValueDBContext> metervaluedbContextFactory,
         //IDbContextFactory<MeterValueDBContext> metervaluedbContextFactory,
         MeterValueDbService meterValueDbService,
         MeterValueDbService meterValueDbService,
@@ -100,7 +100,8 @@ internal partial class ProfileHandler
         IMainDbService mainDbService,
         IMainDbService mainDbService,
         ILogger<ProfileHandler> logger,
         ILogger<ProfileHandler> logger,
         BlockingTreePrintService blockingTreePrintService,
         BlockingTreePrintService blockingTreePrintService,
-        GoogleGetTimePrintService googleGetTimePrintService)
+        GoogleGetTimePrintService googleGetTimePrintService,
+        OuterHttpClient httpClient)
     {
     {
         //webConnectionString = configuration.GetConnectionString("WebDBContext");
         //webConnectionString = configuration.GetConnectionString("WebDBContext");
 
 
@@ -113,6 +114,7 @@ internal partial class ProfileHandler
         this.mainDbService = mainDbService;
         this.mainDbService = mainDbService;
         //this.metervaluedbContextFactory = metervaluedbContextFactory;
         //this.metervaluedbContextFactory = metervaluedbContextFactory;
         this.businessServiceFactory = businessServiceFactory;
         this.businessServiceFactory = businessServiceFactory;
+        this.httpClient = httpClient;
     }
     }
 
 
     async internal Task<MessageResult> ExecuteCoreRequest(Actions action, ClientData session, IRequest request)
     async internal Task<MessageResult> ExecuteCoreRequest(Actions action, ClientData session, IRequest request)
@@ -381,7 +383,7 @@ internal partial class ProfileHandler
                                         energyRegister = energy_Register.unit.Value == UnitOfMeasure.kWh ? decimal.Multiply(energyRegister, 1000) : energyRegister;
                                         energyRegister = energy_Register.unit.Value == UnitOfMeasure.kWh ? decimal.Multiply(energyRegister, 1000) : energyRegister;
 
 
 
 
-                                        using (var maindb = maindbContextFactory.CreateDbContext())
+                                        using (var maindb = await maindbContextFactory.CreateDbContextAsync())
                                         {
                                         {
                                             meterStart = await maindb.TransactionRecord
                                             meterStart = await maindb.TransactionRecord
                                                 .Where(x => x.Id == _request.transactionId.Value).Select(x => x.MeterStart)
                                                 .Where(x => x.Id == _request.transactionId.Value).Select(x => x.MeterStart)
@@ -536,7 +538,7 @@ internal partial class ProfileHandler
                         }
                         }
 
 
 
 
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var _CustomerId = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).Include(x => x.Customer).
                             var _CustomerId = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).Include(x => x.Customer).
                                  Select(x => x.CustomerId).FirstOrDefaultAsync();
                                  Select(x => x.CustomerId).FirstOrDefaultAsync();
@@ -642,7 +644,7 @@ internal partial class ProfileHandler
                         }
                         }
                         try
                         try
                         {
                         {
-                            using (var db = maindbContextFactory.CreateDbContext())
+                            using (var db = await maindbContextFactory.CreateDbContextAsync())
                             {
                             {
                                 var transaction = db.TransactionRecord.Where(x => x.Id == _request.transactionId
                                 var transaction = db.TransactionRecord.Where(x => x.Id == _request.transactionId
                                  && x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
                                  && x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
@@ -776,6 +778,8 @@ internal partial class ProfileHandler
                             result.Exception = new Exception("TransactionId " + _request.transactionId + " " + ex.Message);
                             result.Exception = new Exception("TransactionId " + _request.transactionId + " " + ex.Message);
                             result.CallErrorMsg = "Reject Response Message";
                             result.CallErrorMsg = "Reject Response Message";
                             result.Success = false;
                             result.Success = false;
+
+                            logger.LogCritical("StopTransaction {msg} trace:{trace}", ex.Message, ex.StackTrace);
                             // return result;
                             // return result;
                         }
                         }
 
 
@@ -871,11 +875,11 @@ internal partial class ProfileHandler
 
 
         if (watch.ElapsedMilliseconds > 5_000)
         if (watch.ElapsedMilliseconds > 5_000)
         {
         {
-            ThreadPool.GetAvailableThreads(out int workerThreads,out int completionThreads);
-            logger.LogInformation($"ThreadPool workerThreads:{workerThreads} completionThreads:{completionThreads}");
+            //ThreadPool.GetAvailableThreads(out int workerThreads,out int completionThreads);
+            //logger.LogInformation($"ThreadPool workerThreads:{workerThreads} completionThreads:{completionThreads}");
 
 
-            await blockingTreePrintService.PrintDbBlockingTree();
-            await googleGetTimePrintService.Print();
+            //await blockingTreePrintService.PrintDbBlockingTree();
+            //await googleGetTimePrintService.Print();
         }
         }
 
 
         return result;
         return result;
@@ -893,7 +897,7 @@ internal partial class ProfileHandler
                     {
                     {
                         DataTransferConfirmation _confirm = confirm as DataTransferConfirmation;
                         DataTransferConfirmation _confirm = confirm as DataTransferConfirmation;
                         DataTransferRequest _request = _confirm.GetRequest() as DataTransferRequest;
                         DataTransferRequest _request = _confirm.GetRequest() as DataTransferRequest;
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1204,7 +1208,7 @@ internal partial class ProfileHandler
                                         #region 提供給PHA 過CDFA認證 使用
                                         #region 提供給PHA 過CDFA認證 使用
                                         if (tx.CustomerId == Guid.Parse("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
                                         if (tx.CustomerId == Guid.Parse("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
                                         {
                                         {
-                                            var mail_response = new OuterHttpClient().PostFormDataAsync("http://ocpp.phihong.com.tw/CDFA/" + tx.Id, new Dictionary<string, string>()
+                                            var mail_response = httpClient.PostFormDataAsync("http://ocpp.phihong.com.tw/CDFA/" + tx.Id, new Dictionary<string, string>()
                                             {
                                             {
                                                 { "email","2"},
                                                 { "email","2"},
                                                 { "to","wonderj@phihongusa.com;jessica_tseng@phihong.com.tw"}
                                                 { "to","wonderj@phihongusa.com;jessica_tseng@phihong.com.tw"}
@@ -1298,7 +1302,7 @@ internal partial class ProfileHandler
                         ChangeAvailabilityConfirmation _confirm = confirm as ChangeAvailabilityConfirmation;
                         ChangeAvailabilityConfirmation _confirm = confirm as ChangeAvailabilityConfirmation;
                         ChangeAvailabilityRequest _request = _confirm.GetRequest() as ChangeAvailabilityRequest;
                         ChangeAvailabilityRequest _request = _confirm.GetRequest() as ChangeAvailabilityRequest;
 
 
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1319,7 +1323,7 @@ internal partial class ProfileHandler
                         ClearCacheConfirmation _confirm = confirm as ClearCacheConfirmation;
                         ClearCacheConfirmation _confirm = confirm as ClearCacheConfirmation;
                         ClearCacheRequest _request = _confirm.GetRequest() as ClearCacheRequest;
                         ClearCacheRequest _request = _confirm.GetRequest() as ClearCacheRequest;
 
 
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1340,7 +1344,7 @@ internal partial class ProfileHandler
                         RemoteStartTransactionConfirmation _confirm = confirm as RemoteStartTransactionConfirmation;
                         RemoteStartTransactionConfirmation _confirm = confirm as RemoteStartTransactionConfirmation;
                         RemoteStartTransactionRequest _request = _confirm.GetRequest() as RemoteStartTransactionRequest;
                         RemoteStartTransactionRequest _request = _confirm.GetRequest() as RemoteStartTransactionRequest;
 
 
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1361,7 +1365,7 @@ internal partial class ProfileHandler
                         RemoteStopTransactionConfirmation _confirm = confirm as RemoteStopTransactionConfirmation;
                         RemoteStopTransactionConfirmation _confirm = confirm as RemoteStopTransactionConfirmation;
                         RemoteStopTransactionRequest _request = _confirm.GetRequest() as RemoteStopTransactionRequest;
                         RemoteStopTransactionRequest _request = _confirm.GetRequest() as RemoteStopTransactionRequest;
 
 
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1382,7 +1386,7 @@ internal partial class ProfileHandler
                         ResetConfirmation _confirm = confirm as ResetConfirmation;
                         ResetConfirmation _confirm = confirm as ResetConfirmation;
                         ResetRequest _request = _confirm.GetRequest() as ResetRequest;
                         ResetRequest _request = _confirm.GetRequest() as ResetRequest;
 
 
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1403,7 +1407,7 @@ internal partial class ProfileHandler
                         ChangeConfigurationConfirmation _confirm = confirm as ChangeConfigurationConfirmation;
                         ChangeConfigurationConfirmation _confirm = confirm as ChangeConfigurationConfirmation;
                         ChangeConfigurationRequest _request = _confirm.GetRequest() as ChangeConfigurationRequest;
                         ChangeConfigurationRequest _request = _confirm.GetRequest() as ChangeConfigurationRequest;
 
 
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                      x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                      x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1451,9 +1455,9 @@ internal partial class ProfileHandler
                             GetConfigurationConfirmation _confirm = confirm as GetConfigurationConfirmation;
                             GetConfigurationConfirmation _confirm = confirm as GetConfigurationConfirmation;
                             //  GetConfigurationRequest _request = _confirm.GetRequest() as GetConfigurationRequest;
                             //  GetConfigurationRequest _request = _confirm.GetRequest() as GetConfigurationRequest;
 
 
-                            using (var db = maindbContextFactory.CreateDbContext())
+                            using (var db = await maindbContextFactory.CreateDbContextAsync())
                             {
                             {
-                                var configure = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId).ToList();
+                                var configure = await db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId).ToListAsync();
 
 
                                 if (_confirm.configurationKey != null)
                                 if (_confirm.configurationKey != null)
                                 {
                                 {
@@ -1548,7 +1552,7 @@ internal partial class ProfileHandler
                         UnlockConnectorConfirmation _confirm = confirm as UnlockConnectorConfirmation;
                         UnlockConnectorConfirmation _confirm = confirm as UnlockConnectorConfirmation;
                         UnlockConnectorRequest _request = _confirm.GetRequest() as UnlockConnectorRequest;
                         UnlockConnectorRequest _request = _confirm.GetRequest() as UnlockConnectorRequest;
 
 
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1603,7 +1607,7 @@ internal partial class ProfileHandler
                         logger.LogDebug(string.Format("DataTransfer Error {0}: {1}", session.ChargeBoxId, requestId));
                         logger.LogDebug(string.Format("DataTransfer Error {0}: {1}", session.ChargeBoxId, requestId));
                     }
                     }
 
 
-                    using (var db = maindbContextFactory.CreateDbContext())
+                    using (var db = await maindbContextFactory.CreateDbContextAsync())
                     {
                     {
                         var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                         var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                         x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                         x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();

+ 4 - 4
EVCB_OCPP.WSServer/Message/FirmwareManagementProfileHandler.cs

@@ -30,7 +30,7 @@ namespace EVCB_OCPP.WSServer.Message
                             if (_request.status == Packet.Messages.SubTypes.FirmwareStatus.Idle)
                             if (_request.status == Packet.Messages.SubTypes.FirmwareStatus.Idle)
                             {
                             {
                                 string requestId = Guid.NewGuid().ToString();
                                 string requestId = Guid.NewGuid().ToString();
-                                using (var db = maindbContextFactory.CreateDbContext())
+                                using (var db = await maindbContextFactory.CreateDbContextAsync())
                                 {
                                 {
                                     var machine = await db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true && x.FW_AssignedVersion.HasValue
                                     var machine = await db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true && x.FW_AssignedVersion.HasValue
                                        && x.FW_AssignedVersion != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
                                        && x.FW_AssignedVersion != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
@@ -82,7 +82,7 @@ namespace EVCB_OCPP.WSServer.Message
                             }
                             }
                             else
                             else
                             {
                             {
-                                using (var db = maindbContextFactory.CreateDbContext())
+                                using (var db = await maindbContextFactory.CreateDbContextAsync())
                                 {
                                 {
                                     var item = await db.MachineOperateRecord.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.RequestType == 0)
                                     var item = await db.MachineOperateRecord.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.RequestType == 0)
                                         .OrderByDescending(x => x.CreatedOn).FirstOrDefaultAsync();
                                         .OrderByDescending(x => x.CreatedOn).FirstOrDefaultAsync();
@@ -154,7 +154,7 @@ namespace EVCB_OCPP.WSServer.Message
                             var confirmation = confirm as GetDiagnosticsConfirmation;
                             var confirmation = confirm as GetDiagnosticsConfirmation;
                             evse_rep = confirmation.fileName;
                             evse_rep = confirmation.fileName;
                         }
                         }
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord
                             var operation = await db.MachineOperateRecord
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)
@@ -192,7 +192,7 @@ namespace EVCB_OCPP.WSServer.Message
                 case Actions.GetDiagnostics:
                 case Actions.GetDiagnostics:
                 case Actions.DiagnosticsStatusNotification:
                 case Actions.DiagnosticsStatusNotification:
                     {
                     {
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord
                             var operation = await db.MachineOperateRecord
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)

+ 3 - 3
EVCB_OCPP.WSServer/Message/LocalAuthListManagementProfileHandler.cs

@@ -22,7 +22,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                     {
                         GetLocalListVersionConfirmation _confirm = confirm as GetLocalListVersionConfirmation;
                         GetLocalListVersionConfirmation _confirm = confirm as GetLocalListVersionConfirmation;
                         GetLocalListVersionRequest _request = _confirm.GetRequest() as GetLocalListVersionRequest;
                         GetLocalListVersionRequest _request = _confirm.GetRequest() as GetLocalListVersionRequest;
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -42,7 +42,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                     {
                         SendLocalListConfirmation _confirm = confirm as SendLocalListConfirmation;
                         SendLocalListConfirmation _confirm = confirm as SendLocalListConfirmation;
                         SendLocalListRequest _request = _confirm.GetRequest() as SendLocalListRequest;
                         SendLocalListRequest _request = _confirm.GetRequest() as SendLocalListRequest;
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -77,7 +77,7 @@ namespace EVCB_OCPP.WSServer.Message
                 case Actions.SendLocalList:
                 case Actions.SendLocalList:
                 case Actions.GetLocalListVersion:
                 case Actions.GetLocalListVersion:
                     {
                     {
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();

+ 2 - 2
EVCB_OCPP.WSServer/Message/RemoteTriggerHandler.cs

@@ -24,7 +24,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                     {
                         TriggerMessageConfirmation _confirm = confirm as TriggerMessageConfirmation;
                         TriggerMessageConfirmation _confirm = confirm as TriggerMessageConfirmation;
                         TriggerMessageRequest _request = _confirm.GetRequest() as TriggerMessageRequest;
                         TriggerMessageRequest _request = _confirm.GetRequest() as TriggerMessageRequest;
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -58,7 +58,7 @@ namespace EVCB_OCPP.WSServer.Message
             {
             {
                 case Actions.TriggerMessage:
                 case Actions.TriggerMessage:
                     {
                     {
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();

+ 4 - 4
EVCB_OCPP.WSServer/Message/ReservationProfileHandler.cs

@@ -24,7 +24,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                     {
                         ReserveNowConfirmation _confirm = confirm as ReserveNowConfirmation;
                         ReserveNowConfirmation _confirm = confirm as ReserveNowConfirmation;
                         ReserveNowRequest _request = _confirm.GetRequest() as ReserveNowRequest;
                         ReserveNowRequest _request = _confirm.GetRequest() as ReserveNowRequest;
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -44,7 +44,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                     {
                         CancelReservationConfirmation _confirm = confirm as CancelReservationConfirmation;
                         CancelReservationConfirmation _confirm = confirm as CancelReservationConfirmation;
                         CancelReservationRequest _request = _confirm.GetRequest() as CancelReservationRequest;
                         CancelReservationRequest _request = _confirm.GetRequest() as CancelReservationRequest;
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -78,7 +78,7 @@ namespace EVCB_OCPP.WSServer.Message
             {
             {
                 case Actions.ReserveNow:
                 case Actions.ReserveNow:
                     {
                     {
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -96,7 +96,7 @@ namespace EVCB_OCPP.WSServer.Message
                     break;
                     break;
                 case Actions.CancelReservation:
                 case Actions.CancelReservation:
                     {
                     {
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();

+ 4 - 4
EVCB_OCPP.WSServer/Message/SmartChargingProfileHandler.cs

@@ -80,7 +80,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                     {
                         ClearChargingProfileConfirmation _confirm = confirm as ClearChargingProfileConfirmation;
                         ClearChargingProfileConfirmation _confirm = confirm as ClearChargingProfileConfirmation;
                         ClearChargingProfileRequest _request = _confirm.GetRequest() as ClearChargingProfileRequest;
                         ClearChargingProfileRequest _request = _confirm.GetRequest() as ClearChargingProfileRequest;
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -100,7 +100,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                     {
                         SetChargingProfileConfirmation _confirm = confirm as SetChargingProfileConfirmation;
                         SetChargingProfileConfirmation _confirm = confirm as SetChargingProfileConfirmation;
                         SetChargingProfileRequest _request = _confirm.GetRequest() as SetChargingProfileRequest;
                         SetChargingProfileRequest _request = _confirm.GetRequest() as SetChargingProfileRequest;
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -120,7 +120,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                     {
                         GetCompositeScheduleConfirmation _confirm = confirm as GetCompositeScheduleConfirmation;
                         GetCompositeScheduleConfirmation _confirm = confirm as GetCompositeScheduleConfirmation;
                         GetCompositeScheduleRequest _request = _confirm.GetRequest() as GetCompositeScheduleRequest;
                         GetCompositeScheduleRequest _request = _confirm.GetRequest() as GetCompositeScheduleRequest;
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord
                             var operation = await db.MachineOperateRecord
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)
@@ -157,7 +157,7 @@ namespace EVCB_OCPP.WSServer.Message
                 case Actions.SetChargingProfile:
                 case Actions.SetChargingProfile:
                 case Actions.GetCompositeSchedule:
                 case Actions.GetCompositeSchedule:
                     {
                     {
-                        using (var db = maindbContextFactory.CreateDbContext())
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                         {
                         {
                             var operation = await db.MachineOperateRecord
                             var operation = await db.MachineOperateRecord
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)

+ 4 - 0
EVCB_OCPP.WSServer/Program.cs

@@ -15,6 +15,8 @@ using System.IO;
 using System.Data.Common;
 using System.Data.Common;
 using Microsoft.Data.SqlClient;
 using Microsoft.Data.SqlClient;
 using EVCB_OCPP.WSServer.Helper;
 using EVCB_OCPP.WSServer.Helper;
+using Quartz;
+using EVCB_OCPP.WSServer.Jobs;
 
 
 namespace EVCB_OCPP.WSServer
 namespace EVCB_OCPP.WSServer
 {
 {
@@ -23,6 +25,8 @@ namespace EVCB_OCPP.WSServer
     {
     {
         static void Main(string[] args)
         static void Main(string[] args)
         {
         {
+            AppContext.SetData("System.Net.Security.TlsCacheSize", 200);
+
             Console.WriteLine("====================================================================================================");
             Console.WriteLine("====================================================================================================");
             Console.WriteLine("=================" +
             Console.WriteLine("=================" +
                 "===================================================================================");
                 "===================================================================================");

+ 13 - 11
EVCB_OCPP.WSServer/ProtalServer.cs

@@ -65,7 +65,7 @@ namespace EVCB_OCPP.WSServer
 
 
         public ProtalServer(
         public ProtalServer(
             ILogger<ProtalServer> logger
             ILogger<ProtalServer> logger
-            ,IConfiguration configuration
+            , IConfiguration configuration
             , IDbContextFactory<MainDBContext> maindbContextFactory
             , IDbContextFactory<MainDBContext> maindbContextFactory
             , IMainDbService mainDbService
             , IMainDbService mainDbService
             , IDbContextFactory<ConnectionLogDBContext> connectionLogdbContextFactory
             , IDbContextFactory<ConnectionLogDBContext> connectionLogdbContextFactory
@@ -75,7 +75,8 @@ namespace EVCB_OCPP.WSServer
             , IOCPPWSServerFactory ocppWSServerFactory
             , IOCPPWSServerFactory ocppWSServerFactory
             , IConnectionLogdbService connectionLogdbService
             , IConnectionLogdbService connectionLogdbService
             , WebDbService webDbService
             , WebDbService webDbService
-            ,IServiceProvider serviceProvider)
+            , IServiceProvider serviceProvider,
+            OuterHttpClient httpClient)
         {
         {
             _ct = _cts.Token;
             _ct = _cts.Token;
             this.logger = logger;
             this.logger = logger;
@@ -87,17 +88,18 @@ namespace EVCB_OCPP.WSServer
             this.ocppWSServerFactory = ocppWSServerFactory;
             this.ocppWSServerFactory = ocppWSServerFactory;
             this.connectionLogdbService = connectionLogdbService;
             this.connectionLogdbService = connectionLogdbService;
             this.webDbService = webDbService;
             this.webDbService = webDbService;
+            this.httpClient = httpClient;
             isInDocker = !string.IsNullOrEmpty(configuration["DOTNET_RUNNING_IN_CONTAINER"]);
             isInDocker = !string.IsNullOrEmpty(configuration["DOTNET_RUNNING_IN_CONTAINER"]);
 
 
             // = configuration.GetConnectionString("WebDBContext");
             // = configuration.GetConnectionString("WebDBContext");
             this.profileHandler = serviceProvider.GetService<ProfileHandler>();// new ProfileHandler(configuration, serviceProvider);
             this.profileHandler = serviceProvider.GetService<ProfileHandler>();// new ProfileHandler(configuration, serviceProvider);
-            _loadingBalanceService = new LoadingBalanceService(mainDbConnectionFactory, webDbConnectionFactory );
+            _loadingBalanceService = new LoadingBalanceService(mainDbConnectionFactory, webDbConnectionFactory);
 
 
             WarmUpLog();
             WarmUpLog();
         }
         }
 
 
         #region private fields
         #region private fields
-        private OuterHttpClient httpClient = new OuterHttpClient();
+        private OuterHttpClient httpClient;
         private DateTime lastcheckdt = DateTime.UtcNow.AddSeconds(-20);
         private DateTime lastcheckdt = DateTime.UtcNow.AddSeconds(-20);
         private ConcurrentDictionary<string, ClientData> clientDic = new ConcurrentDictionary<string, ClientData>();
         private ConcurrentDictionary<string, ClientData> clientDic = new ConcurrentDictionary<string, ClientData>();
         //private readonly Object _lockClientDic = new object();
         //private readonly Object _lockClientDic = new object();
@@ -560,7 +562,7 @@ namespace EVCB_OCPP.WSServer
 
 
         private void AppServer_SessionClosed(ClientData session, CloseReason value)
         private void AppServer_SessionClosed(ClientData session, CloseReason value)
         {
         {
-            _ = WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
+            WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
             RemoveClient(session);
             RemoveClient(session);
         }
         }
 
 
@@ -594,7 +596,7 @@ namespace EVCB_OCPP.WSServer
                 // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
                 // logger.LogDebug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
                 WriteMachineLog(session, "NewSessionConnected", "Connection", "");
                 WriteMachineLog(session, "NewSessionConnected", "Connection", "");
 
 
-                using (var db = maindbContextFactory.CreateDbContext())
+                using (var db = await maindbContextFactory.CreateDbContextAsync())
                 {
                 {
                     var machine = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
                     var machine = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
                     if (machine != null)
                     if (machine != null)
@@ -637,7 +639,7 @@ namespace EVCB_OCPP.WSServer
                 BasicMessageHandler msgAnalyser = new BasicMessageHandler();
                 BasicMessageHandler msgAnalyser = new BasicMessageHandler();
                 MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
                 MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
 
 
-                await WriteMachineLog(session, rawdata,
+                WriteMachineLog(session, rawdata,
                      string.Format("{0} {1}", string.IsNullOrEmpty(analysisResult.Action) ? "unknown" : analysisResult.Action, analysisResult.Id == 2 ? "Request" : (analysisResult.Id == 3 ? "Confirmation" : "Error")), analysisResult.Exception == null ? "" : analysisResult.Exception.Message);
                      string.Format("{0} {1}", string.IsNullOrEmpty(analysisResult.Action) ? "unknown" : analysisResult.Action, analysisResult.Id == 2 ? "Request" : (analysisResult.Id == 3 ? "Confirmation" : "Error")), analysisResult.Exception == null ? "" : analysisResult.Exception.Message);
 
 
                 if (session.ResetSecurityProfile)
                 if (session.ResetSecurityProfile)
@@ -919,7 +921,7 @@ namespace EVCB_OCPP.WSServer
                                     }
                                     }
                                     else
                                     else
                                     {
                                     {
-                                        using (var db = maindbContextFactory.CreateDbContext())
+                                        using (var db = await maindbContextFactory.CreateDbContextAsync())
                                         {
                                         {
                                             var machine = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
                                             var machine = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
                                             if (machine != null)
                                             if (machine != null)
@@ -1215,7 +1217,7 @@ namespace EVCB_OCPP.WSServer
 
 
                 if (session != null)
                 if (session != null)
                 {
                 {
-                    WriteMachineLog(session, msg, messageType, errorMsg, true).Wait();
+                    WriteMachineLog(session, msg, messageType, errorMsg, true);
                     session.Send(msg);
                     session.Send(msg);
                 }
                 }
 
 
@@ -1352,7 +1354,7 @@ namespace EVCB_OCPP.WSServer
                     foundRequest.SentInterval = 0;
                     foundRequest.SentInterval = 0;
                     analysisResult.RequestId = foundRequest.RequestId;
                     analysisResult.RequestId = foundRequest.RequestId;
 
 
-                    using (var db = maindbContextFactory.CreateDbContext())
+                    using (var db = await maindbContextFactory.CreateDbContextAsync())
                     {
                     {
                         var sc = await db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefaultAsync();
                         var sc = await db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefaultAsync();
                         sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
                         sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
@@ -1440,7 +1442,7 @@ namespace EVCB_OCPP.WSServer
             connectionLogdbService.WarmUpLog();
             connectionLogdbService.WarmUpLog();
         }
         }
 
 
-        private async Task WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
+        private void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
         {
         {
             try
             try
             {
             {

+ 7 - 4
EVCB_OCPP.WSServer/Service/BusinessServiceFactory.cs

@@ -25,8 +25,11 @@ public static class BusinessServiceFactoryRegistration
 {
 {
     public static void AddBusinessServiceFactory(this IServiceCollection services)
     public static void AddBusinessServiceFactory(this IServiceCollection services)
     {
     {
-        services.AddSingleton<OuterBusinessService>();
-        services.AddSingleton<LocalBusinessService>();
+        services.AddSingleton<HttpClientService>();
+        services.AddSingleton<OuterHttpClient>();
+
+        services.AddTransient<OuterBusinessService>();
+        services.AddTransient<LocalBusinessService>();
         services.AddSingleton<IBusinessServiceFactory, BusinessServiceFactory>();
         services.AddSingleton<IBusinessServiceFactory, BusinessServiceFactory>();
     }
     }
 }
 }
@@ -53,12 +56,12 @@ public class BusinessServiceFactory : IBusinessServiceFactory
     public async Task<IBusinessService> CreateBusinessService(string customerId)
     public async Task<IBusinessService> CreateBusinessService(string customerId)
     {
     {
         bool isCallOut = false;
         bool isCallOut = false;
-        //using (var db = this.mainDBContextFactory.CreateDbContext())
+        //using (var db = this.mainDBContextFactory.CreateDbContextAsync())
         //{
         //{
         //    isCallOut = await db.Customer.Where(x => x.Id == new Guid(customerId)).Select(x => x.CallPartnerApiOnSchedule).FirstOrDefaultAsync();
         //    isCallOut = await db.Customer.Where(x => x.Id == new Guid(customerId)).Select(x => x.CallPartnerApiOnSchedule).FirstOrDefaultAsync();
         //}
         //}
         CustomerSignMaterial _customer = null;
         CustomerSignMaterial _customer = null;
-        //using (var db = this.mainDBContextFactory.CreateDbContext())
+        //using (var db = this.mainDBContextFactory.CreateDbContextAsync())
         //{
         //{
         //    _customer = await db.Customer.Where(x => x.Id == new Guid(customerId)).Select(x => new CustomerSignMaterial() { Id = x.Id.ToString(), APIUrl = x.ApiUrl, SaltKey = x.ApiKey, CallsThirdParty = x.CallPartnerApiOnSchedule }).FirstOrDefaultAsync();
         //    _customer = await db.Customer.Where(x => x.Id == new Guid(customerId)).Select(x => new CustomerSignMaterial() { Id = x.Id.ToString(), APIUrl = x.ApiUrl, SaltKey = x.ApiKey, CallsThirdParty = x.CallPartnerApiOnSchedule }).FirstOrDefaultAsync();
         //}
         //}

+ 4 - 4
EVCB_OCPP.WSServer/Service/ConnectionLogdbService.cs

@@ -154,7 +154,7 @@ public class ConnectionLogdbService : IConnectionLogdbService
             {
             {
                 logger.LogCritical(log.clientData.Path + "]********************session ChargeBoxId null sessionId=" + log.clientData.SessionID);
                 logger.LogCritical(log.clientData.Path + "]********************session ChargeBoxId null sessionId=" + log.clientData.SessionID);
             }
             }
-            using (var db = connectionLogdbContextFactory.CreateDbContext())
+            using (var db = await connectionLogdbContextFactory.CreateDbContextAsync())
             {
             {
                 string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
                 string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
                       "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
                       "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
@@ -216,7 +216,7 @@ public class ConnectionLogdbService : IConnectionLogdbService
 
 
         t1 = watch.ElapsedMilliseconds;
         t1 = watch.ElapsedMilliseconds;
         using SqlConnection sqlConnection = await sqlConnectionFactory.CreateAsync();
         using SqlConnection sqlConnection = await sqlConnectionFactory.CreateAsync();
-        using var tans = sqlConnection.BeginTransaction();
+        using var tans = await sqlConnection.BeginTransactionAsync();
 
 
         t2 = watch.ElapsedMilliseconds;
         t2 = watch.ElapsedMilliseconds;
         var tableName = GetTableName(workTime);
         var tableName = GetTableName(workTime);
@@ -238,11 +238,11 @@ public class ConnectionLogdbService : IConnectionLogdbService
             parameters.Add("EVSEEndPoint", log.clientData.RemoteEndPoint == null ? "123" : log.clientData.RemoteEndPoint.ToString(), DbType.String, size: 25);
             parameters.Add("EVSEEndPoint", log.clientData.RemoteEndPoint == null ? "123" : log.clientData.RemoteEndPoint.ToString(), DbType.String, size: 25);
             parameters.Add("Session", log.clientData.SessionID == null ? "123" : log.clientData.SessionID, DbType.String, size: 36);
             parameters.Add("Session", log.clientData.SessionID == null ? "123" : log.clientData.SessionID, DbType.String, size: 36);
 
 
-            sqlConnection.Execute(command, parameters, tans);
+            await sqlConnection.ExecuteAsync(command, parameters, tans);
         }
         }
 
 
         t3 = watch.ElapsedMilliseconds;
         t3 = watch.ElapsedMilliseconds;
-        tans.Commit();
+        await tans.CommitAsync();
 
 
         watch.Stop();
         watch.Stop();
         t4 = watch.ElapsedMilliseconds;
         t4 = watch.ElapsedMilliseconds;

+ 5 - 1
EVCB_OCPP.WSServer/Service/HttpClientService.cs

@@ -41,8 +41,12 @@ namespace EVCB_OCPP.WSServer.Service
         private int _maxConnectionsPerServer = 300;
         private int _maxConnectionsPerServer = 300;
         private int _timeout = 60;
         private int _timeout = 60;
 
 
+        public HttpClientService()
+        {
+            Init("");
+        }
 
 
-        public HttpClientService(string baseAddress = "")
+        public HttpClientService(string baseAddress)
         {
         {
             Init(baseAddress);
             Init(baseAddress);
         }
         }

+ 7 - 3
EVCB_OCPP.WSServer/Service/LocalBusinessService.cs

@@ -14,10 +14,14 @@ namespace EVCB_OCPP.WSServer.Service
     {
     {
         public string CustomerId { get; set; }
         public string CustomerId { get; set; }
         private readonly IConfiguration configuration;
         private readonly IConfiguration configuration;
+        private readonly HttpClientService service;
+        private readonly OuterHttpClient _client;
 
 
-        public LocalBusinessService(IConfiguration configuration)
+        public LocalBusinessService(IConfiguration configuration, HttpClientService service, OuterHttpClient client)
         {
         {
             this.configuration = configuration;
             this.configuration = configuration;
+            this.service = service;
+            _client = client;
         }
         }
 
 
         async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag)
         async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag)
@@ -34,13 +38,13 @@ namespace EVCB_OCPP.WSServer.Service
                 }
                 }
 
 
 
 
-                OuterHttpClient _client = new OuterHttpClient();
+                //OuterHttpClient _client = new OuterHttpClient();
 
 
 
 
                 string url = configuration["LocalAuthAPI"];
                 string url = configuration["LocalAuthAPI"];
 
 
 
 
-                HttpClientService service = new HttpClientService();
+                //HttpClientService service = new HttpClientService();
 
 
                 Dictionary<string, string> postData = new Dictionary<string, string>()
                 Dictionary<string, string> postData = new Dictionary<string, string>()
                 {
                 {

+ 14 - 34
EVCB_OCPP.WSServer/Service/MainDbService.cs

@@ -72,7 +72,7 @@ public class MainDbService : IMainDbService
     public async Task<MachineAndCustomerInfo> GetMachineIdAndCustomerInfo(string ChargeBoxId)
     public async Task<MachineAndCustomerInfo> GetMachineIdAndCustomerInfo(string ChargeBoxId)
     {
     {
         using var semaphoreWrapper = await startupSemaphore.GetToken();
         using var semaphoreWrapper = await startupSemaphore.GetToken();
-        using var db = contextFactory.CreateDbContext();
+        using var db = await contextFactory.CreateDbContextAsync();
         var machine = await db.Machine.Where(x => x.ChargeBoxId == ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefaultAsync();
         var machine = await db.Machine.Where(x => x.ChargeBoxId == ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefaultAsync();
         if (machine == null)
         if (machine == null)
         {
         {
@@ -87,7 +87,7 @@ public class MainDbService : IMainDbService
     public async Task<string> GetMachineConfiguration(string ChargeBoxId, string configName)
     public async Task<string> GetMachineConfiguration(string ChargeBoxId, string configName)
     {
     {
         using var semaphoreWrapper = await startupSemaphore.GetToken();
         using var semaphoreWrapper = await startupSemaphore.GetToken();
-        using var db = contextFactory.CreateDbContext();
+        using var db = await contextFactory.CreateDbContextAsync();
         return await db.MachineConfigurations
         return await db.MachineConfigurations
             .Where(x => x.ChargeBoxId == ChargeBoxId && x.ConfigureName == configName)
             .Where(x => x.ChargeBoxId == ChargeBoxId && x.ConfigureName == configName)
             .Select(x => x.ConfigureSetting).FirstOrDefaultAsync();
             .Select(x => x.ConfigureSetting).FirstOrDefaultAsync();
@@ -111,7 +111,7 @@ public class MainDbService : IMainDbService
     public async Task UpdateMachineBasicInfo(string ChargeBoxId, Machine machine)
     public async Task UpdateMachineBasicInfo(string ChargeBoxId, Machine machine)
     {
     {
         //using var semaphoreWrapper = await startupSemaphore.GetToken();
         //using var semaphoreWrapper = await startupSemaphore.GetToken();
-        //using var db = await contextFactory.CreateDbContextAsync();
+        //using var db = await await contextFactory.CreateDbContextAsyncAsyncAsync();
 
 
         //var _machine = db.Machine.FirstOrDefault(x => x.ChargeBoxId == ChargeBoxId);
         //var _machine = db.Machine.FirstOrDefault(x => x.ChargeBoxId == ChargeBoxId);
         //_machine.ChargeBoxSerialNumber = machine.ChargeBoxSerialNumber;
         //_machine.ChargeBoxSerialNumber = machine.ChargeBoxSerialNumber;
@@ -131,7 +131,7 @@ public class MainDbService : IMainDbService
 
 
     public async Task AddOCMF(OCMF oCMF)
     public async Task AddOCMF(OCMF oCMF)
     {
     {
-        using var db = contextFactory.CreateDbContext();
+        using var db = await contextFactory.CreateDbContextAsync();
         db.OCMF.Add(oCMF);
         db.OCMF.Add(oCMF);
         await db.SaveChangesAsync();
         await db.SaveChangesAsync();
     }
     }
@@ -140,7 +140,7 @@ public class MainDbService : IMainDbService
         string ChargeBoxId, byte ConnectorId, DateTime CreatedOn, int Status,
         string ChargeBoxId, byte ConnectorId, DateTime CreatedOn, int Status,
         int ChargePointErrorCodeId, string ErrorInfo, string VendorId, string VendorErrorCode)
         int ChargePointErrorCodeId, string ErrorInfo, string VendorId, string VendorErrorCode)
     {
     {
-        using var db = contextFactory.CreateDbContext();
+        using var db = await contextFactory.CreateDbContextAsync();
         var _currentStatus = new Domain.Models.Database.ConnectorStatus()
         var _currentStatus = new Domain.Models.Database.ConnectorStatus()
         {
         {
             ChargeBoxId = ChargeBoxId,
             ChargeBoxId = ChargeBoxId,
@@ -157,12 +157,7 @@ public class MainDbService : IMainDbService
 
 
         await db.SaveChangesAsync();
         await db.SaveChangesAsync();
 
 
-        Task.Run(() => { 
-        lock (memoryCache)
-        {
-            memoryCache.Set($"{ChargeBoxId}{ConnectorId}", _currentStatus, TimeSpan.FromHours(12));
-        }
-        });
+        memoryCache.Set($"{ChargeBoxId}{ConnectorId}", _currentStatus, TimeSpan.FromHours(12));
     }
     }
 
 
     public async ValueTask<ConnectorStatus> GetConnectorStatus(string ChargeBoxId, int ConnectorId)
     public async ValueTask<ConnectorStatus> GetConnectorStatus(string ChargeBoxId, int ConnectorId)
@@ -172,16 +167,11 @@ public class MainDbService : IMainDbService
         {
         {
             return status;
             return status;
         }
         }
-        using var db = contextFactory.CreateDbContext();
+        using var db = await contextFactory.CreateDbContextAsync();
         var statusFromDb = await db.ConnectorStatus.Where(x => x.ChargeBoxId == ChargeBoxId
         var statusFromDb = await db.ConnectorStatus.Where(x => x.ChargeBoxId == ChargeBoxId
                             && x.ConnectorId == ConnectorId).AsNoTracking().FirstOrDefaultAsync();
                             && x.ConnectorId == ConnectorId).AsNoTracking().FirstOrDefaultAsync();
 
 
-        Task.Run(() => {
-        lock (memoryCache)
-        {
-            memoryCache.Set(key, statusFromDb, TimeSpan.FromHours(12));
-        }
-        });
+        memoryCache.Set(key, statusFromDb, TimeSpan.FromHours(12));
         return statusFromDb;
         return statusFromDb;
     }
     }
 
 
@@ -192,12 +182,7 @@ public class MainDbService : IMainDbService
         await UpdateConnectorStatusDapper(Id, Status);
         await UpdateConnectorStatusDapper(Id, Status);
 
 
         var key = $"{Status.ChargeBoxId}{Status.ConnectorId}";
         var key = $"{Status.ChargeBoxId}{Status.ConnectorId}";
-        Task.Run(() => {
-        lock (memoryCache)
-        {
-            memoryCache.Set(key, Status, TimeSpan.FromHours(12));
-        }
-        });
+        memoryCache.Set(key, Status, TimeSpan.FromHours(12));
         return;
         return;
     }
     }
 
 
@@ -257,7 +242,7 @@ public class MainDbService : IMainDbService
     public async ValueTask AddMachineError(byte ConnectorId, DateTime CreatedOn, int Status, string ChargeBoxId,
     public async ValueTask AddMachineError(byte ConnectorId, DateTime CreatedOn, int Status, string ChargeBoxId,
     int ErrorCodeId, string ErrorInfo, int PreStatus, string VendorErrorCode, string VendorId)
     int ErrorCodeId, string ErrorInfo, int PreStatus, string VendorErrorCode, string VendorId)
     {
     {
-        using var db = contextFactory.CreateDbContext();
+        using var db = await contextFactory.CreateDbContextAsync();
         db.MachineError.Add(new MachineError()
         db.MachineError.Add(new MachineError()
         {
         {
             ConnectorId = ConnectorId,
             ConnectorId = ConnectorId,
@@ -328,19 +313,14 @@ public class MainDbService : IMainDbService
         }
         }
 
 
         Customer toReturn = null;
         Customer toReturn = null;
-        using (var db = contextFactory.CreateDbContext())
+        using (var db = await contextFactory.CreateDbContextAsync())
         {
         {
             toReturn = await db.Customer.FirstOrDefaultAsync(x => x.Id == id);
             toReturn = await db.Customer.FirstOrDefaultAsync(x => x.Id == id);
         }
         }
 
 
         if (toReturn is not null)
         if (toReturn is not null)
         {
         {
-            Task.Run(() => {
-            lock (memoryCache)
-            {
-                memoryCache.Set(key, toReturn, TimeSpan.FromSeconds(15));
-            }
-            });
+            memoryCache.Set(key, toReturn, TimeSpan.FromSeconds(15));
         }
         }
 
 
         return toReturn;
         return toReturn;
@@ -431,7 +411,7 @@ public class MainDbService : IMainDbService
         }
         }
 
 
         await db.SaveChangesAsync();
         await db.SaveChangesAsync();
-        trans.Commit();
+        await trans.CommitAsync();
         db.ChangeTracker.Clear();
         db.ChangeTracker.Clear();
     }
     }
 
 
@@ -491,7 +471,7 @@ public class MainDbService : IMainDbService
         }
         }
 
 
         await db.SaveChangesAsync();
         await db.SaveChangesAsync();
-        trans.Commit();
+        await trans.CommitAsync();
         db.ChangeTracker.Clear();
         db.ChangeTracker.Clear();
     }
     }
 
 

+ 4 - 3
EVCB_OCPP.WSServer/Service/MeterValueDbService.cs

@@ -58,7 +58,7 @@ public class MeterValueDbService
             , int locationId, int unitId, int transactionId)
             , int locationId, int unitId, int transactionId)
     {
     {
         //using var token = await insertSemaphore.GetToken();
         //using var token = await insertSemaphore.GetToken();
-        //using var db = await meterValueDbContextFactory.CreateDbContextAsync();
+        //using var db = await meterValueDbContextFactory.CreateDbContextAsyncAsync();
 
 
         //string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId, @ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
         //string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId, @ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
 
 
@@ -80,8 +80,8 @@ public class MeterValueDbService
 
 
         //await db.Database.ExecuteSqlRawAsync(sp, parameter.ToArray());
         //await db.Database.ExecuteSqlRawAsync(sp, parameter.ToArray());
 
 
-        return insertMeterValueHandler.HandleAsync(param);
-        //return InsertWithDapper(param);
+        //return insertMeterValueHandler.HandleAsync(param);
+        return InsertWithDapper(param);
         //return meterValueGroupSingleHandler.HandleAsync(param);
         //return meterValueGroupSingleHandler.HandleAsync(param);
     }
     }
 
 
@@ -184,6 +184,7 @@ public class MeterValueDbService
 
 
         t2 = watch.ElapsedMilliseconds;
         t2 = watch.ElapsedMilliseconds;
 
 
+        List<Task> ExecuteTasks = new List<Task>();
         foreach (var group in gruopParams)
         foreach (var group in gruopParams)
         {
         {
 
 

+ 22 - 14
EVCB_OCPP.WSServer/Service/OuterBusinessService.cs

@@ -3,9 +3,11 @@ using EVCB_OCPP.Domain.Models.Database;
 using EVCB_OCPP.Packet.Messages.SubTypes;
 using EVCB_OCPP.Packet.Messages.SubTypes;
 using EVCB_OCPP.WSServer.Dto;
 using EVCB_OCPP.WSServer.Dto;
 using Microsoft.EntityFrameworkCore;
 using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
 using Newtonsoft.Json;
 using Newtonsoft.Json;
 using Newtonsoft.Json.Linq;
 using Newtonsoft.Json.Linq;
 using NLog;
 using NLog;
+using SuperSocket.SocketBase;
 using System;
 using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
@@ -48,13 +50,14 @@ namespace EVCB_OCPP.WSServer.Service
     }
     }
     public class OuterBusinessService : IBusinessService
     public class OuterBusinessService : IBusinessService
     {
     {
-        static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
-        private OuterHttpClient httpClient = new OuterHttpClient();
-        private CustomerSignMaterial signMaterial = null;
 
 
-        private string _CustomerId = string.Empty;
+        private readonly ILogger<OuterBusinessService> logger;
         private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
         private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
         private readonly IMainDbService mainDbService;
         private readonly IMainDbService mainDbService;
+        private readonly OuterHttpClient httpClient;
+
+        private string _CustomerId = string.Empty;
+        private CustomerSignMaterial signMaterial = null;
 
 
         public string CustomerId
         public string CustomerId
         {
         {
@@ -76,11 +79,16 @@ namespace EVCB_OCPP.WSServer.Service
             }
             }
         }
         }
 
 
-        public OuterBusinessService(IDbContextFactory<MainDBContext> maindbContextFactory,
-            IMainDbService mainDbService)
+        public OuterBusinessService(
+            ILogger<OuterBusinessService> logger,
+            IDbContextFactory<MainDBContext> maindbContextFactory,
+            IMainDbService mainDbService,
+            OuterHttpClient httpClient)
         {
         {
+            this.logger = logger;
             this.maindbContextFactory = maindbContextFactory;
             this.maindbContextFactory = maindbContextFactory;
             this.mainDbService = mainDbService;
             this.mainDbService = mainDbService;
+            this.httpClient = httpClient;
         }
         }
 
 
 
 
@@ -95,8 +103,8 @@ namespace EVCB_OCPP.WSServer.Service
 
 
                // if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
                // if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
                 {
                 {
-                    logger.Info(chargeBoxId + " Charging Monitor======================================>");
-                    logger.Info(signMaterial.APIUrl + requestParams);
+                    logger.LogInformation(chargeBoxId + " Charging Monitor======================================>");
+                    logger.LogInformation(signMaterial.APIUrl + requestParams);
                 }
                 }
                 var response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
                 var response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
                             {
                             {
@@ -105,7 +113,7 @@ namespace EVCB_OCPP.WSServer.Service
                             }, null, signMaterial.SaltKey).ConfigureAwait(false);
                             }, null, signMaterial.SaltKey).ConfigureAwait(false);
                // if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
                // if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
                 {
                 {
-                    logger.Info(JsonConvert.SerializeObject(response));
+                    logger.LogInformation(JsonConvert.SerializeObject(response));
                 }
                 }
                 if (response.Success)
                 if (response.Success)
                 {
                 {
@@ -171,7 +179,7 @@ namespace EVCB_OCPP.WSServer.Service
                 }
                 }
                 else
                 else
                 {
                 {
-                    logger.Error(chargeBoxId + " OuterBusinessService.Authorize Fail: " + response.Response);
+                    logger.LogError(chargeBoxId + " OuterBusinessService.Authorize Fail: " + response.Response);
                 }
                 }
 
 
             }
             }
@@ -179,7 +187,7 @@ namespace EVCB_OCPP.WSServer.Service
             {
             {
                 result.IdTagInfo.status = AuthorizationStatus.Invalid;
                 result.IdTagInfo.status = AuthorizationStatus.Invalid;
 
 
-                logger.Error(chargeBoxId + " OuterBusinessService.Authorize Ex: " + ex.ToString());
+                logger.LogError(chargeBoxId + " OuterBusinessService.Authorize Ex: " + ex.ToString());
             }
             }
 
 
             return result;
             return result;
@@ -203,7 +211,7 @@ namespace EVCB_OCPP.WSServer.Service
             catch (Exception ex)
             catch (Exception ex)
             {
             {
 
 
-                logger.Error(details.ChargeBoxId + " OuterBusinessService.NotifyFaultStatus Ex: " + ex.ToString());
+                logger.LogError(details.ChargeBoxId + " OuterBusinessService.NotifyFaultStatus Ex: " + ex.ToString());
             }
             }
 
 
 
 
@@ -232,7 +240,7 @@ namespace EVCB_OCPP.WSServer.Service
             catch (Exception ex)
             catch (Exception ex)
             {
             {
 
 
-                logger.Error(chargeBoxId + " OuterBusinessService.NotifyConnectorUnplugged Ex: " + ex.ToString());
+                logger.LogError(chargeBoxId + " OuterBusinessService.NotifyConnectorUnplugged Ex: " + ex.ToString());
             }
             }
 
 
         }
         }
@@ -244,7 +252,7 @@ namespace EVCB_OCPP.WSServer.Service
 
 
 
 
             //using (var db = new MainDBContext())
             //using (var db = new MainDBContext())
-            //using (var db = maindbContextFactory.CreateDbContext())
+            //using (var db = maindbContextFactory.CreateDbContextAsync())
             //{
             //{
             //    _customer = await db.Customer.Where(x => x.Id == Id).Select(x => new CustomerSignMaterial() { Id = x.Id.ToString(), APIUrl = x.ApiUrl, SaltKey = x.ApiKey, CallsThirdParty = x.CallPartnerApiOnSchedule }).FirstOrDefaultAsync();
             //    _customer = await db.Customer.Where(x => x.Id == Id).Select(x => new CustomerSignMaterial() { Id = x.Id.ToString(), APIUrl = x.ApiUrl, SaltKey = x.ApiKey, CallsThirdParty = x.CallPartnerApiOnSchedule }).FirstOrDefaultAsync();
             //}
             //}

+ 6 - 1
EVCB_OCPP.WSServer/Service/OuterHttpClient.cs

@@ -10,7 +10,12 @@ namespace EVCB_OCPP.WSServer.Service
 {
 {
     public class OuterHttpClient
     public class OuterHttpClient
     {
     {
-        private HttpClientService httpClient = new HttpClientService();
+        private HttpClientService httpClient;
+
+        public OuterHttpClient(HttpClientService httpClient)
+        {
+            this.httpClient = httpClient;
+        }
 
 
         async public Task<HttpResult> Post(string url, Dictionary<string, string> headers, object requestBody, string saltkey)
         async public Task<HttpResult> Post(string url, Dictionary<string, string> headers, object requestBody, string saltkey)
         {
         {

+ 18 - 0
EVCB_OCPP.WSServer/appsettings.json

@@ -32,6 +32,12 @@
     "clientCertificateRequired": "false",
     "clientCertificateRequired": "false",
     "keyStorageFlags": "Exportable"
     "keyStorageFlags": "Exportable"
   },
   },
+  "Logging": {
+    "LogLevel": {
+      "Default": "Information",
+      "Microsoft.AspNetCore": "Warning"
+    }
+  },
   "NLog": {
   "NLog": {
     "targets": {
     "targets": {
       "async": true,
       "async": true,
@@ -85,6 +91,18 @@
         "logger": "EVCB_OCPP.*",
         "logger": "EVCB_OCPP.*",
         "minlevel": "Trace",
         "minlevel": "Trace",
         "writeTo": "console"
         "writeTo": "console"
+      },
+      {
+        "ruleName": "MsFileLog",
+        "logger": "Microsoft.*",
+        "minLevel": "Warn",
+        "writeTo": "f"
+      },
+      {
+        "ruleName": "MsConsoleLog",
+        "logger": "Microsoft.*",
+        "minlevel": "Warn",
+        "writeTo": "console"
       }
       }
     ]
     ]
   },
   },

+ 9 - 14
SocketEngine/SocketSession.cs

@@ -278,20 +278,15 @@ namespace SuperSocket.SocketEngine
 
 
         private void Send(SendingQueue queue)
         private void Send(SendingQueue queue)
         {
         {
-            var stopwatch = Stopwatch.StartNew();
-            if (SyncSend)
-            {
-                SendSync(queue);
-            }
-            else
-            {
-                SendAsync(queue);
-            }
-            stopwatch.Stop();
-            if(stopwatch.ElapsedMilliseconds/1000 > 1)
-            {
-                Console.WriteLine($"SocketSession Send take {stopwatch.ElapsedMilliseconds / 1000} sec");
-            }
+            //if (SyncSend)
+            //{
+            //    SendSync(queue);
+            //}
+            //else
+            //{
+            //    SendAsync(queue);
+            //}
+            SendAsync(queue);
         }
         }
 
 
         private void StartSend(SendingQueue queue, int sendingTrackID, bool initial)
         private void StartSend(SendingQueue queue, int sendingTrackID, bool initial)

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

@@ -903,7 +903,7 @@ namespace TestTool.RemoteTriggerAPP
 
 
                 });
                 });
 
 
-                await db.SaveChangesAsync();
+                db.SaveChanges();
             }
             }
         }
         }
 
 
@@ -1057,7 +1057,7 @@ namespace TestTool.RemoteTriggerAPP
             using (var db = new MainDBContext())
             using (var db = new MainDBContext())
             {
             {
                 db.UploadFile.Add(ufObj);
                 db.UploadFile.Add(ufObj);
-                await db.SaveChangesAsync();
+                db.SaveChanges();
 
 
             }
             }
 
 
@@ -1121,11 +1121,11 @@ namespace TestTool.RemoteTriggerAPP
                 db.MachineVersionFile.Add(obj);
                 db.MachineVersionFile.Add(obj);
 
 
                 //將machine的軟體更新更新到這個值
                 //將machine的軟體更新更新到這個值
-                await db.SaveChangesAsync();
+                db.SaveChanges();
 
 
                 machine.FW_AssignedVersion = obj.Id;
                 machine.FW_AssignedVersion = obj.Id;
 
 
-                await db.SaveChangesAsync();
+                db.SaveChanges();
 
 
 
 
             }
             }
@@ -1147,7 +1147,7 @@ namespace TestTool.RemoteTriggerAPP
 
 
                 var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
                 var machine = db.Machine.Where(x => x.ChargeBoxId == uxChargeBoxIdTb.Text).FirstOrDefault();
                 machine.FW_AssignedVersion = null;
                 machine.FW_AssignedVersion = null;
-                await db.SaveChangesAsync();
+                db.SaveChanges();
             }
             }
 
 
             uxMsgTb.Text = "Clear Publish";
             uxMsgTb.Text = "Clear Publish";