Browse Source

add main commit 44477
加入 PnC 邏輯

Robert 1 year ago
parent
commit
76090ad0fe

+ 43 - 25
EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs

@@ -19,6 +19,7 @@ using System.Data;
 using System.Diagnostics;
 using System.Globalization;
 using SuperSocket.SocketBase;
+using Microsoft.AspNetCore.Http;
 
 namespace EVCB_OCPP.WSServer.Message;
 
@@ -502,6 +503,16 @@ internal partial class ProfileHandler
                         t0 = timer.ElapsedMilliseconds;
 
                         var _idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
+
+                        #region PnC 邏輯
+
+                        if (!string.IsNullOrEmpty(_request.idTag))
+                        {
+                            _request.idTag = _request.idTag.StartsWith("vid:") ? _request.idTag.Replace("vid:", "") : _request.idTag;
+                        }
+
+                        #endregion
+
                         if (_request.idTag != "Backend")
                         {
                             var authorization_result = await businessService.Authorize(session.ChargeBoxId, _request.idTag);
@@ -624,18 +635,36 @@ internal partial class ProfileHandler
                     break;
                 case Actions.StopTransaction:
                     {
+                        StopTransactionRequest _request = request as StopTransactionRequest;
+
+                        //遠傳太久以前的停止充電 直接拒絕 避免電樁持續重送~~~~~~~
+                        if (_request.timestamp < new DateTime(2021, 11, 1))
+                        {
+                            var confirm = new StopTransactionConfirmation()
+                            {
+                                idTagInfo = new IdTagInfo()
+                                {
+                                    status = AuthorizationStatus.Invalid
+                                }
+                            };
+
+                            result.Message = confirm;
+                            result.Success = true;
+                            return result;
+                        }
+
                         long getDateTimeTime, getServiceTime, getTagInfoTime, dbOpTime = 0, meterValueTime = 0;
                         var stopTrasactionTimer = Stopwatch.StartNew();
 
-                        StopTransactionRequest _request = request as StopTransactionRequest;
-
                         int _ConnectorId = 0;
-
                         var utcNow = DateTime.UtcNow;
+
                         getDateTimeTime = stopTrasactionTimer.ElapsedMilliseconds;
                         var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
                         getServiceTime = stopTrasactionTimer.ElapsedMilliseconds;
 
+                        TransactionRecord transaction;
+                        transaction = await mainDbService.GetTransactionForStopTransaction(_request.transactionId, session.ChargeBoxId);
 
                         var _idTagInfo = string.IsNullOrEmpty(_request.idTag) ? null : (
                             _request.idTag == "Backend" ?
@@ -644,7 +673,7 @@ internal partial class ProfileHandler
                                     expiryDate = utcNow.AddDays(1),
                                     status = AuthorizationStatus.Accepted
                                 } :
-                                (await businessService.Authorize(session.ChargeBoxId, _request.idTag)).IdTagInfo
+                                (await businessService.Authorize(session.ChargeBoxId, _request.idTag, transaction?.ConnectorId)).IdTagInfo
                             );
                         getTagInfoTime = stopTrasactionTimer.ElapsedMilliseconds;
 
@@ -653,28 +682,16 @@ internal partial class ProfileHandler
                         {
                             _idTagInfo = new IdTagInfo() { expiryDate = utcNow.AddDays(1), status = AuthorizationStatus.Accepted };
                         }
-                        try
-                        {
-                            //遠傳太久以前的停止充電 直接拒絕 避免電樁持續重送~~~~~~~
-                            if (_request.timestamp < new DateTime(2021, 11, 1))
-                            {
-                                var confirm = new StopTransactionConfirmation()
-                                {
-                                    idTagInfo = new IdTagInfo()
-                                    {
-                                        status = AuthorizationStatus.Invalid
-                                    }
-
-                                };
 
-                                result.Message = confirm;
-                                result.Success = true;
-                                return result;
-                            }
-
-                            TransactionRecord transaction;
-                            transaction = await mainDbService.GetTransactionForStopTransaction(_request.transactionId, session.ChargeBoxId);
+                        #region PnC 邏輯
+                        if (!string.IsNullOrEmpty(_request.idTag))
+                        {
+                            _request.idTag = _request.idTag.StartsWith("vid:") ? _request.idTag.Replace("vid:", "") : _request.idTag;
+                        }
+                        #endregion
 
+                        try
+                        {
                             if (transaction is null)
                             {
                                 result.Exception = new Exception("Can't find transactionId " + _request.transactionId);
@@ -702,7 +719,8 @@ internal partial class ProfileHandler
                                     await mainDbService.UpdateTransactionSOC(
                                         transaction.Id,
                                         startsoc: SOCCollection.Count == 0 ? "" : SOCCollection.First().ToString("0"),
-                                        stopsoc: SOCCollection.Count == 0 ? "" : SOCCollection.Last().ToString("0");
+                                        stopsoc: SOCCollection.Count == 0 ? "" : SOCCollection.Last().ToString("0")
+                                        );
                                 }
                                 #endregion
 

+ 1 - 1
EVCB_OCPP.WSServer/Service/BusinessServiceFactory.cs

@@ -13,7 +13,7 @@ namespace EVCB_OCPP.WSServer.Service;
 
 public interface IBusinessService
 {
-    Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag);
+    Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag, int? connectorId = null);
 
     Task NotifyFaultStatus(ErrorDetails details);
 

+ 1 - 1
EVCB_OCPP.WSServer/Service/LocalBusinessService.cs

@@ -24,7 +24,7 @@ namespace EVCB_OCPP.WSServer.Service
             _client = client;
         }
 
-        async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag)
+        async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag, int? connectorId = null)
         {
             await Task.Delay(10);
             IdTokenInfo info = new IdTokenInfo() { IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Invalid } };

+ 34 - 13
EVCB_OCPP.WSServer/Service/OuterBusinessService.cs

@@ -92,7 +92,7 @@ namespace EVCB_OCPP.WSServer.Service
         }
 
 
-        async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag)
+        async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag, int? connectorId = null)
         {
             //return new IdTokenInfo() { IdTagInfo = new IdTagInfo()
             //{
@@ -105,22 +105,16 @@ namespace EVCB_OCPP.WSServer.Service
 
             try
             {
-                string requestParams = string.Format("charging_auth?ChargeBoxId={0}&IdTag={1}", chargeBoxId, idTag);
+                logger.LogInformation(chargeBoxId + " Charging Monitor======================================>");
 
-               // if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
-                {
-                    logger.LogInformation(chargeBoxId + " Charging Monitor======================================>");
-                    logger.LogInformation(signMaterial.APIUrl + requestParams);
-                }
-                var response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
+                string requestParams = idTag.StartsWith("vid:") ? await GetRequestParamsAsPnC(chargeBoxId, idTag, connectorId) : GetRequestParamsAsNormal(chargeBoxId, idTag);
+
+                HttpResult response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
                             {
                                 { "PartnerId",signMaterial.Id}
+                            }, requestBody: null, saltkey: signMaterial.SaltKey).ConfigureAwait(false);
+                logger.LogInformation($"{chargeBoxId} response : {JsonConvert.SerializeObject(response)}");
 
-                            }, null, signMaterial.SaltKey).ConfigureAwait(false);
-               // if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
-                {
-                    logger.LogInformation($"{chargeBoxId} response : {JsonConvert.SerializeObject(response)}" );
-                }
                 if (response.Success)
                 {
                     //Console.WriteLine(response.Response);
@@ -273,6 +267,33 @@ namespace EVCB_OCPP.WSServer.Service
             return _customer;
         }
 
+        private async ValueTask<string> GetRequestParamsAsPnC(string chargeBoxId, string idTag, int? connectorId)
+        {
+            idTag = idTag.Replace("vid:", "");
+
+            if (connectorId is null)
+            {
+                using (var db = await maindbContextFactory.CreateDbContextAsync())
+                {
+                    var connectorStatuses = await db.ConnectorStatus.Where(x => x.ChargeBoxId == chargeBoxId).
+                         Select(x => new { x.ConnectorId, x.Status, x.CreatedOn }).ToListAsync();
+
+                    var connectorStatus = connectorStatuses.Where(x => x.Status == 2).OrderByDescending(x => x.CreatedOn).FirstOrDefault();
+                    if (connectorStatus != null)
+                    {
+                        connectorId = connectorStatus.ConnectorId;
+                    }
+                }
+            }
+
+            return string.Format("charging_auth?ChargeBoxId={0}&ConnectorId={1}&IdTag={2}", chargeBoxId, connectorId, idTag);
+        }
+
+        private string GetRequestParamsAsNormal(string chargeBoxId, string idTag)
+        {
+            return string.Format("charging_auth?ChargeBoxId={0}&IdTag={1}", chargeBoxId, idTag);
+        }
+
         public Task NotifyConnectorUnplugged(string data)
         {
             throw new NotImplementedException();