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

add get diagnostic restrict

shayne_lo 5 сар өмнө
parent
commit
5c19ce3457

+ 21 - 0
EVCB_OCPP.WSServer/Jobs/ServerMessageJob.cs

@@ -5,6 +5,7 @@ using EVCB_OCPP.Packet.Messages;
 using EVCB_OCPP.Packet.Messages.Core;
 using EVCB_OCPP.WSServer.Message;
 using EVCB_OCPP.WSServer.Service;
+using EVCB_OCPP.WSServer.Service.DbService;
 using EVCB_OCPP.WSServer.Service.WsService;
 using Microsoft.EntityFrameworkCore;
 using Microsoft.Extensions.Configuration;
@@ -30,12 +31,14 @@ public class ServerMessageJob : IJob
         //VendorIdUpdateService vendorIdReplaceService,
         IConfiguration configuration,
         IDbContextFactory<MainDBContext> maindbContextFactory,
+        IMainDbService mainDbService,
         ILogger<ServerMessageJob> logger)
     {
         this.protalServer = protalServer;
         this.confirmWaitingMessageSerevice = confirmWaitingMessageSerevice;
         //this.vendorIdUpdateService = vendorIdReplaceService;
         this.maindbContextFactory = maindbContextFactory;
+        this.mainDbService = mainDbService;
         this.logger = logger;
     }
 
@@ -43,6 +46,7 @@ public class ServerMessageJob : IJob
     private readonly ConfirmWaitingMessageSerevice confirmWaitingMessageSerevice;
     //private readonly VendorIdUpdateService vendorIdUpdateService;
     private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
+    private readonly IMainDbService mainDbService;
     private readonly ILogger<ServerMessageJob> logger;
 
     public async Task Execute(IJobExecutionContext context)
@@ -140,6 +144,23 @@ public class ServerMessageJob : IJob
                     {
                         ReplaceVID(session, action, request);
                     }
+                    if (action == Actions.GetDiagnostics)
+                    {
+                        if (!await mainDbService.GetIsEvseDiagnosticsStatusAvalaible(charger_SN))
+                        {
+                            using (var db = await maindbContextFactory.CreateDbContextAsync())
+                            {
+                                var last = await db.ServerMessage.FirstOrDefaultAsync(x => x.Id == item.Id);
+                                if (last != null)
+                                {
+                                    last.ReceivedOn = dateTimeNow;
+                                }
+                                await db.SaveChangesAsync();
+                            }
+                            await mainDbService.ContinueLastEvseDiagnostic(charger_SN);
+                            continue;
+                        }
+                    }
                     uuid = session.queue.store(request);
                     rawRequest = BasicMessageHandler.GenerateRequest(uuid, item.OutAction, request);
                     protalServer.SendMsg(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");

+ 19 - 1
EVCB_OCPP.WSServer/Message/FirmwareManagementProfileHandler.cs

@@ -113,7 +113,7 @@ namespace EVCB_OCPP.WSServer.Message
                                 using (var db = await maindbContextFactory.CreateDbContextAsync())
                                 {
                                     var item = db.MachineOperateRecord.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.Action == "GetDiagnostics" && x.RequestType == 1)
-                                        .OrderByDescending(x => x.CreatedOn).FirstOrDefault();
+                                        .OrderByDescending(x => x.Id).FirstOrDefault();
                                     if (item != null)
                                     {
                                         item.EvseStatus = (int)_request.status;
@@ -124,6 +124,24 @@ namespace EVCB_OCPP.WSServer.Message
                                 }
 
                             }
+                            else
+                            {
+                                using (var db = await maindbContextFactory.CreateDbContextAsync())
+                                {
+                                    var item = db.MachineOperateRecord
+                                        .Where(x => x.ChargeBoxId == session.ChargeBoxId && x.Action == "GetDiagnostics" && x.RequestType == 1)
+                                        .OrderByDescending(x => x.Id).FirstOrDefault();
+
+                                    if (item != null &&
+                                        item.EvseStatus != (int)Packet.Messages.SubTypes.DiagnosticsStatus.Uploaded)
+                                    {
+                                        item.EvseStatus = (int)Packet.Messages.SubTypes.DiagnosticsStatus.UploadFailed;
+                                        item.FinishedOn = DateTime.UtcNow;
+                                    }
+
+                                    await db.SaveChangesAsync();
+                                }
+                            }
 
                             var confirm = new DiagnosticsStatusNotificationConfirmation() { };
 

+ 39 - 7
EVCB_OCPP.WSServer/ProtalServer.cs

@@ -739,13 +739,7 @@ namespace EVCB_OCPP.WSServer
                                     if (bootNotificationConfirmation.status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
                                     {
                                         session.IsCheckIn = true;
-
-                                        var sendTask = async () => await messageService.SendDataTransferRequest(
-                                            session.ChargeBoxId,
-                                            messageId: "ID_FirmwareVersion",
-                                            vendorId: "Phihong Technology",
-                                            data: string.Empty);
-                                        await sendTask();
+                                        session.AddTask(StartLateInitializeEVSE(session));
                                         //await confirmWaitingMessageSerevice.SendAndWaitUntilResultAsync(sendTask, session.DisconnetCancellationToken);
                                     }
                                 }
@@ -1086,6 +1080,44 @@ namespace EVCB_OCPP.WSServer
             //await StationConfigService?.CheckAndUpdateEvseConfig(session, session.DisconnetCancellationToken);
         }
 
+        private async Task StartLateInitializeEVSE(WsClientData session)
+        {
+            try
+            {
+                await Task.Delay(TimeSpan.FromMinutes(5));
+                await LateInitializeEVSE(session);
+            }
+            catch (Exception e)
+            {
+                logger.LogCritical("StartLateInitializeEVSE:{errormsg}", e.Message);
+                logger.LogCritical("StartLateInitializeEVSE:{errorStackTrace}", e.StackTrace);
+            }
+            finally
+            {
+                session.BootStatus = BootStatus.Pending;
+                //bootSemaphore.Release();
+            }
+        }
+
+        private async Task LateInitializeEVSE(WsClientData session)
+        {
+            Func<string, Task<string>> sendTask; 
+
+            sendTask  = async (string serialNo) => await messageService.SendDataTransferRequest(
+                session.ChargeBoxId,
+                messageId: "ID_FirmwareVersion",
+                vendorId: "Phihong Technology",
+                data: string.Empty,
+                serialNo: serialNo);
+            await confirmWaitingMessageSerevice.SendAndWaitUntilResultAsync(sendTask, session.DisconnetCancellationToken);
+
+            sendTask = async (string serialNo) => await messageService.SendTriggerMessageRequest(
+                session.ChargeBoxId,
+                messageTrigger: MessageTrigger.DiagnosticsStatusNotification,
+                serialNo: serialNo);
+            await confirmWaitingMessageSerevice.SendAndWaitUntilResultAsync(sendTask, session.DisconnetCancellationToken);
+        }
+
         private void Send(WsClientData session, string msg, string messageType, string errorMsg = "")
         {
             try

+ 94 - 0
EVCB_OCPP.WSServer/Service/DbService/MainDbService.cs

@@ -1,4 +1,5 @@
 using Azure;
+using Azure.Core;
 using Dapper;
 using EVCB_OCPP.Domain;
 using EVCB_OCPP.Domain.ConnectionFactory;
@@ -74,6 +75,8 @@ public interface IMainDbService
     Task<TransactionRecord> GetTransaction(int txId);
     Task SetPncNotifiyResult(int txid, bool isNotifySuccess, string eVCCID);
     Task ReportStopTx(int txid, NotifyTransactionCompletedResult reportResults);
+    Task<bool> GetIsEvseDiagnosticsStatusAvalaible(string charger_SN);
+    Task ContinueLastEvseDiagnostic(string chargeboxId);
 }
 
 public class MainDbService : IMainDbService
@@ -663,6 +666,97 @@ public class MainDbService : IMainDbService
         await dbConn.ExecuteAsync(cmd, parameters);
     }
 
+    public async Task<bool> GetIsEvseDiagnosticsStatusAvalaible(string chargeboxId)
+    {
+        var cmd = """
+            SELECT TOP (1) [EVSE_Status]
+            FROM [dbo].[MachineOperateRecord]
+            where [Action] = 'GetDiagnostics' and [EVSE_Value] != '' and ChargeBoxId = @ChargeBoxId
+            order by id desc
+            """;
+        var parameters = new DynamicParameters();
+        parameters.Add("@ChargeBoxId", chargeboxId, size: 50);
+
+        using var dbConn = await sqlConnectionFactory.CreateAsync();
+        var result = await dbConn.QueryFirstOrDefaultAsync<int?>(cmd, parameters);
+        return result == null ? true : (result.Value == (int)DiagnosticsStatus.Uploaded || result.Value == (int)DiagnosticsStatus.UploadFailed);
+    }
+
+    public async Task ContinueLastEvseDiagnostic(string chargeboxId)
+    {
+        using var db = await contextFactory.CreateDbContextAsync();
+
+        var updatedRecord = await db.MachineOperateRecord
+            .Where(x => x.ChargeBoxId == chargeboxId && x.Action == "GetDiagnostics" && x.RequestType == 1 && x.EvseValue != "")
+            .OrderByDescending(x => x.Id)
+            .FirstOrDefaultAsync();
+
+        var needUpdateRecord = await db.MachineOperateRecord
+            .Where(x => x.ChargeBoxId == chargeboxId && x.Action == "GetDiagnostics" && x.RequestType == 1 && x.EvseValue == "")
+            .OrderByDescending(x => x.Id)
+            .FirstOrDefaultAsync();
+
+        if (updatedRecord == null)
+        {
+            logger.LogInformation("chargeboxId:{0} updatedRecord null", chargeboxId);
+            return;
+        }
+
+        if (needUpdateRecord == null)
+        {
+            logger.LogInformation("chargeboxId:{0} needUpdateRecord null", chargeboxId);
+            return;
+        }
+
+        needUpdateRecord.EvseStatus = updatedRecord.EvseStatus;
+        needUpdateRecord.EvseValue = updatedRecord.EvseValue;
+        needUpdateRecord.Status = updatedRecord.Status;
+        await db.SaveChangesAsync();
+
+        //var getLastUpdatedDataCmd = """
+        //    SELECT TOP (1) [Id], [EVSE_Value], [EVSE_Status]
+        //    FROM [dbo].[MachineOperateRecord]
+        //    WHERE [Action] = 'GetDiagnostics' and [EVSE_Status] != 0 and ChargeBoxId = @ChargeBoxId
+        //    order by Id desc
+        //    """;
+        //var getLastIdCmd = """
+        //    SELECT TOP (1) [Id]
+        //    FROM [dbo].[MachineOperateRecord]
+        //    WHERE [Action] = 'GetDiagnostics' and ChargeBoxId = @ChargeBoxId
+        //    order by Id desc
+        //    """;
+        //var updateLastCmd = """
+        //    Update [dbo].[MachineOperateRecord]
+        //    SET [EVSE_Value] = @EVSE_Value, [EVSE_Status] = @EVSE_Status
+        //    WHERE [Id] = @Id
+        //    """;
+
+        //using var dbConn = await sqlConnectionFactory.CreateAsync();
+        //var parameters = new DynamicParameters();
+
+        //parameters.Add("@ChargeBoxId", chargeboxId, size: 50);
+        //var getDataResult = await dbConn.QueryFirstOrDefaultAsync<MachineOperateRecord>(getLastUpdatedDataCmd, parameters);
+        //if (getDataResult is null)
+        //{
+        //    logger.LogInformation("chargebox:{0} diagnostic get updated faied", chargeboxId);
+        //}
+
+        //var getNeedUpdateIdResult = await dbConn.QueryFirstOrDefaultAsync<int?>(getLastIdCmd, parameters);
+        //if (getNeedUpdateIdResult is null)
+        //{
+        //    logger.LogInformation("chargebox:{0} diagnostic get update id faied", chargeboxId);
+        //}
+
+        //parameters = new DynamicParameters();
+        //parameters.Add("@EVSE_Value", getDataResult.EvseValue);
+        //parameters.Add("@EVSE_Status", getDataResult.EvseStatus);
+        //var updateResult = await dbConn.ExecuteAsync(updateLastCmd, parameters);
+        //if (updateResult == 0)
+        //{
+        //    logger.LogInformation("chargebox:{0} diagnostic update faied", chargeboxId);
+        //}
+    }
+
     private void InitUpdateConnectorStatusHandler()
     {
         if (statusNotificationHandler is not null)

+ 18 - 2
EVCB_OCPP.WSServer/Service/ServerMessageService.cs

@@ -6,6 +6,8 @@ using System.ServiceModel.Channels;
 using EVCB_OCPP.WSServer.Service.DbService;
 using Azure;
 using EVCB_OCPP.WSServer.Message;
+using EVCB_OCPP.Packet.Messages.RemoteTrigger;
+using EVCB_OCPP.Packet.Messages.SubTypes;
 
 namespace EVCB_OCPP.WSServer.Service;
 
@@ -48,7 +50,7 @@ public class ServerMessageService
             );
     }
 
-    internal Task<string> SendDataTransferRequest(string chargeBoxId, string messageId, string vendorId, string data)
+    internal Task<string> SendDataTransferRequest(string chargeBoxId, string messageId, string vendorId, string data, string serialNo = "")
     {
         return mainDbService.AddServerMessage(
             ChargeBoxId: chargeBoxId,
@@ -58,7 +60,21 @@ public class ServerMessageService
                 messageId = messageId,
                 vendorId = vendorId,
                 data = data
-            }
+            },
+            SerialNo: serialNo
+            );
+    }
+
+    internal Task<string> SendTriggerMessageRequest(string chargeBoxId, MessageTrigger messageTrigger, string serialNo = "")
+    {
+        return mainDbService.AddServerMessage(
+            ChargeBoxId: chargeBoxId,
+            OutAction: Actions.TriggerMessage.ToString(),
+            OutRequest: new TriggerMessageRequest()
+            {
+                requestedMessage = messageTrigger
+            },
+            SerialNo: serialNo
             );
     }
 }