Browse Source

fix stop session with wrong session id return worng message

Robert 1 year ago
parent
commit
093afbed90

+ 2 - 0
Dev_Build.bat

@@ -0,0 +1,2 @@
+docker build ./ -t evdevcontainerregistry.azurecr.io/api:test
+docker push evdevcontainerregistry.azurecr.io/api:test

+ 45 - 47
EVCB_OCPP.WEBAPI/Controllers/Version1/CPOController.cs

@@ -17,6 +17,7 @@ using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Logging;
 using System.Diagnostics;
 using EVCB_OCPP.Domain.Models.Database;
+using Azure.Core;
 
 namespace EVCB_OCPP.WEBAPI.Controllers.Version1
 {
@@ -177,68 +178,64 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
 
                 ChargePointService _CPService = serviceProvider.GetRequiredService<ChargePointService>();
 
-                if (!string.IsNullOrEmpty(request.ChargeBoxId) && 
-                    request.ChargeBoxId.Length <= 25 && 
-                    (!request.ConnectorId.HasValue ||
-                        (_CPService.GetNumberofConnectors(request.ChargeBoxId) >= request.ConnectorId && request.ConnectorId > 0)) &&
-                    !string.IsNullOrEmpty(request.Token) &&
-                    request.Token.Length <= 20)
+                if (string.IsNullOrEmpty(request.ChargeBoxId) ||
+                    request.ChargeBoxId.Length > 25 ||
+                    request.ConnectorId.HasValue &&
+                        (!(_CPService.GetNumberofConnectors(request.ChargeBoxId) >= request.ConnectorId) || !(request.ConnectorId > 0)) ||
+                    string.IsNullOrEmpty(request.Token) ||
+                    request.Token.Length > 20)
                 {
-                    InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
-                    ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();
-
-                    //trigger to charge
-                    var _request = new Models.WebAPI.StartTransactionRequest()
-                    {
-                        ConnectorId = request.ConnectorId,
-                        IdTag = request.Token
-                    };
+                    // 參數不符合定義
+                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_PARAMETER_OUTOFRANGE_INCORRECT;
+                    result.StatusCode = (int)CPO_StatusCode.PARAMETER_OUTOFRANGE_INCORRECT;
+                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
+                    //statusCode = HttpStatusCode.BadRequest;
+                    statusCode = StatusCodes.Status400BadRequest;
 
-                    string urlformat = "{0}://{1}";
+                    return StatusCode(statusCode, result);
+                }
 
-                    var _innerResult = await _client.Post(
-                        string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent())
-                        , $"/api/v1/ocpp16/transaction?ChargeBoxId={request.ChargeBoxId}"
-                        , new Dictionary<string, string>()
-                        {
-                            { "PartnerId",_CustomerId}
-                        }, _request, _customer.GetAPIKey(new Guid(_CustomerId)));
+                InternalHttpClient _client = serviceProvider.GetRequiredService<InternalHttpClient>();
+                ICustomerService _customer = serviceProvider.GetRequiredService<ICustomerService>();
 
-                    _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
-                    result = GetErrorDescription(_innerResult);
-                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
+                //trigger to charge
+                var _request = new Models.WebAPI.StartTransactionRequest()
+                {
+                    ConnectorId = request.ConnectorId,
+                    IdTag = request.Token
+                };
 
-                    if (_innerResult.Status == HttpStatusCode.InternalServerError)
-                    {
+                string urlformat = "{0}://{1}";
 
-                        result.StatusCode = _innerResult.ErrorCode;
-                        result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
-                        //statusCode = HttpStatusCode.InternalServerError;
-                        statusCode = StatusCodes.Status500InternalServerError;
-                    }
-                    else
+                var _innerResult = await _client.Post(
+                    string.Format(urlformat, Request.Scheme, Request.Host.ToUriComponent())
+                    , $"/api/v1/ocpp16/transaction?ChargeBoxId={request.ChargeBoxId}"
+                    , new Dictionary<string, string>()
                     {
-                        result.SerialNo = _innerResult.SerialNo;
-                        result.StatusCode = _innerResult.ErrorCode;
-                        result.StatusMessage = _innerResult.Message;
-                        //statusCode = HttpStatusCode.OK;
-                        statusCode = StatusCodes.Status200OK;
-                    }
+                        { "PartnerId",_CustomerId}
+                    }, _request, _customer.GetAPIKey(new Guid(_CustomerId)));
 
+                _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
+                result = GetErrorDescription(_innerResult);
+                result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
 
+                if (_innerResult.Status == HttpStatusCode.InternalServerError)
+                {
 
+                    result.StatusCode = _innerResult.ErrorCode;
+                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
+                    //statusCode = HttpStatusCode.InternalServerError;
+                    statusCode = StatusCodes.Status500InternalServerError;
                 }
                 else
                 {
-                    // 參數不符合定義
-                    result.StatusMessage = CPO_StatusMessage.ERROR_MSG_PARAMETER_OUTOFRANGE_INCORRECT;
-                    result.StatusCode = (int)CPO_StatusCode.PARAMETER_OUTOFRANGE_INCORRECT;
-                    result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
-                    //statusCode = HttpStatusCode.BadRequest;
-                    statusCode = StatusCodes.Status400BadRequest;
+                    result.SerialNo = _innerResult.SerialNo;
+                    result.StatusCode = _innerResult.ErrorCode;
+                    result.StatusMessage = _innerResult.Message;
+                    //statusCode = HttpStatusCode.OK;
+                    statusCode = StatusCodes.Status200OK;
                 }
 
-
                 //return Request.CreateResponse(statusCode, result);
                 return StatusCode(statusCode, result);
             }
@@ -267,6 +264,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
             try
             {
                 string _CustomerId = GetCustomerId();
+                logger.LogTrace($"{nameof(StopSession)} {ChargeBoxId} {_CustomerId}");
 
                 if (!await ContainsChargePointAsync(ChargeBoxId, _CustomerId))
                 {

+ 32 - 33
EVCB_OCPP.WEBAPI/Controllers/Version1/InternalController.cs

@@ -20,6 +20,7 @@ using System.ComponentModel;
 using System.Linq;
 using System.Net;
 using System.Net.Http;
+using System.Threading.Tasks;
 using StartTransactionRequest = EVCB_OCPP.WEBAPI.Models.WebAPI.StartTransactionRequest;
 
 namespace EVCB_OCPP.WEBAPI.Controllers.Version1
@@ -507,7 +508,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
         //[Produces(typeof(ErrorResponse))]
         [Produces(typeof(InternalGenericResponse))]
         [HttpPost]
-        public IActionResult StartTransaction(string ChargeBoxId, [FromBody] StartTransactionRequest StartTransaction)
+        public async Task<IActionResult> StartTransaction(string ChargeBoxId, [FromBody] StartTransactionRequest StartTransaction)
         {
             string uuid = Guid.NewGuid().ToString();
             var result = new InternalGenericResponse();
@@ -595,40 +596,38 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
                             Message = EVCBConfiguration.ERROR_MSG_CONNECTOR_ISNOT_AVAILIABLE_MODE 
                         });
                 }
-                else
+
+                var _request = new RemoteStartTransactionRequest()
                 {
-                    var _request = new RemoteStartTransactionRequest()
-                    {
 
-                        connectorId = StartTransaction.ConnectorId,
-                        idTag = StartTransaction.IdTag,
-                        chargingProfile = StartTransaction.ChargingProfile == null ? null :
-                         new csChargingProfiles()
-                         {
-                             chargingProfileId = StartTransaction.ChargingProfile.chargingProfileId,
-                             stackLevel = StartTransaction.ChargingProfile.stackLevel,
-                             chargingProfilePurpose = ChargingProfilePurposeType.TxProfile,
-                             chargingProfileKind = StartTransaction.ChargingProfile.chargingProfileKind,
-                             recurrencyKind = StartTransaction.ChargingProfile.recurrencyKind,
-                             validFrom = StartTransaction.ChargingProfile.validFrom == null ? (DateTime?)null : DateTime.SpecifyKind(StartTransaction.ChargingProfile.validFrom.Value, DateTimeKind.Utc),
-                             validTo = StartTransaction.ChargingProfile.validTo == null ? (DateTime?)null : DateTime.SpecifyKind(StartTransaction.ChargingProfile.validTo.Value, DateTimeKind.Utc),
-                             chargingSchedule = new ChargingSchedule()
-                             {
-                                 chargingRateUnit = StartTransaction.ChargingProfile.chargingSchedule.chargingRateUnit,
-                                 chargingSchedulePeriod = StartTransaction.ChargingProfile.chargingSchedule.chargingSchedulePeriod,
-                                 duration = StartTransaction.ChargingProfile.chargingSchedule.duration,
-                                 minChargingRate = StartTransaction.ChargingProfile.chargingSchedule.minChargingRate,
-                                 startSchedule = StartTransaction.ChargingProfile.chargingSchedule.startSchedule == null ? (DateTime?)null : DateTime.SpecifyKind(StartTransaction.ChargingProfile.chargingSchedule.startSchedule.Value, DateTimeKind.Utc)
-                             }
-                         }
+                    connectorId = StartTransaction.ConnectorId,
+                    idTag = StartTransaction.IdTag,
+                    chargingProfile = StartTransaction.ChargingProfile == null ? null :
+                        new csChargingProfiles()
+                        {
+                            chargingProfileId = StartTransaction.ChargingProfile.chargingProfileId,
+                            stackLevel = StartTransaction.ChargingProfile.stackLevel,
+                            chargingProfilePurpose = ChargingProfilePurposeType.TxProfile,
+                            chargingProfileKind = StartTransaction.ChargingProfile.chargingProfileKind,
+                            recurrencyKind = StartTransaction.ChargingProfile.recurrencyKind,
+                            validFrom = StartTransaction.ChargingProfile.validFrom == null ? (DateTime?)null : DateTime.SpecifyKind(StartTransaction.ChargingProfile.validFrom.Value, DateTimeKind.Utc),
+                            validTo = StartTransaction.ChargingProfile.validTo == null ? (DateTime?)null : DateTime.SpecifyKind(StartTransaction.ChargingProfile.validTo.Value, DateTimeKind.Utc),
+                            chargingSchedule = new ChargingSchedule()
+                            {
+                                chargingRateUnit = StartTransaction.ChargingProfile.chargingSchedule.chargingRateUnit,
+                                chargingSchedulePeriod = StartTransaction.ChargingProfile.chargingSchedule.chargingSchedulePeriod,
+                                duration = StartTransaction.ChargingProfile.chargingSchedule.duration,
+                                minChargingRate = StartTransaction.ChargingProfile.chargingSchedule.minChargingRate,
+                                startSchedule = StartTransaction.ChargingProfile.chargingSchedule.startSchedule == null ? (DateTime?)null : DateTime.SpecifyKind(StartTransaction.ChargingProfile.chargingSchedule.startSchedule.Value, DateTimeKind.Utc)
+                            }
+                        }
 
-                    };
+                };
 
 
-                    if (!AddCommandtoServer(ChargeBoxId, uuid, _request))
-                    {
-                        throw new Exception("Write Command Fail!!");
-                    }
+                if (!AddCommandtoServer(ChargeBoxId, uuid, _request))
+                {
+                    throw new Exception("Write Command Fail!!");
                 }
 
                 statusCode = StatusCodes.Status200OK;
@@ -686,9 +685,9 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
                         });
                 }
 
-                var _ConnectorId = chargePointService.GetConnectorwithOngoingTransaction(ChargeBoxId, TransactionId);
+                int? _ConnectorId = chargePointService.GetConnectorwithOngoingTransaction(ChargeBoxId, TransactionId);
 
-                if (_ConnectorId == -1)
+                if (_ConnectorId is null)
                 {
                     // 充完電 & 這個充電序不存在
                     //return Request.CreateResponse(HttpStatusCode.BadRequest, new ErrorResponse() { Code = 2106, Message = EVCBConfiguration.ERROR_MSG_TX_FINISHED_OR_NOTFOUND });
@@ -700,7 +699,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
                         });
                 }
 
-                var _ConnectorStatus = chargePointService.GetChargePointCurrentSatus(ChargeBoxId, _ConnectorId);
+                var _ConnectorStatus = chargePointService.GetChargePointCurrentSatus(ChargeBoxId, _ConnectorId.Value);
 
                 if (!(_ConnectorStatus.HasValue && _ConnectorStatus == ChargePointStatus.Charging || _ConnectorStatus == ChargePointStatus.SuspendedEVSE || _ConnectorStatus == ChargePointStatus.SuspendedEV))
                 {

+ 3 - 3
EVCB_OCPP.WEBAPI/Services/ChargePointService.cs

@@ -351,9 +351,9 @@ namespace EVCB_OCPP.WEBAPI.Services
             return exists;
         }
 
-        public int GetConnectorwithOngoingTransaction(string chargeBoxId, int transactionId)
+        public int? GetConnectorwithOngoingTransaction(string chargeBoxId, int transactionId)
         {
-            int connectorId = -1;
+            int? connectorId = null;
 
             if (string.IsNullOrEmpty(chargeBoxId)) return connectorId;
 
@@ -363,7 +363,7 @@ namespace EVCB_OCPP.WEBAPI.Services
             using (SqlConnection conn = mainDbConneciotnFactory.Create())
             {
                 string strSql = "Select ConnectorId from [dbo].[TransactionRecord] where ChargeBoxId=@ChargeBoxId and Id= @TransactionId and StopTime='1991/01/01'; ";
-                connectorId = conn.QueryFirstOrDefault<Int32>(strSql, parameters);
+                connectorId = conn.QueryFirstOrDefault<int?>(strSql, parameters);
             }
 
             return connectorId;

+ 7 - 7
EVCB_OCPP.WEBAPI/appsettings.json

@@ -13,13 +13,13 @@
   "UnobtrusiveJavaScriptEnabled": true,
   "StatisticsAPI": "http://ocpp.phihong.com.tw/StatisticsReportApi/",
   "ConnectionStrings": {
-    "Main20DBContext": "data source=172.1.0.131;initial catalog=Docker_Main;;persist security info=True;user id=sa;password=B58Py42j/4cj84;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
-    "MeterValue20DBContext": "data source=172.1.0.131;initial catalog=Docker_Main;;persist security info=True;user id=sa;password=B58Py42j/4cj84;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
-    "ConnectionLogDBContext": "data source=172.1.0.131;initial catalog=Docker_ConnectionLog;persist security info=True;user id=sa;password=B58Py42j/4cj84;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
-    "MainDBContext": "data source=172.1.0.131;initial catalog=Docker_Main;;persist security info=True;user id=sa;password=B58Py42j/4cj84;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
-    "MeterValueDBContext": "data source=172.1.0.131;initial catalog=Docker_MeterValue;;persist security info=True;user id=sa;password=B58Py42j/4cj84;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
-    "APILogDBContext": "data source=172.1.0.131;initial catalog=Docker_APILog;;persist security info=True;user id=sa;password=B58Py42j/4cj84;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
-    "WebDBContext": "data source=172.1.0.131;initial catalog=Docker_Web;;persist security info=True;user id=sa;password=B58Py42j/4cj84;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true"
+    "Main20DBContext": "data source=zerova-ev-dev.database.windows.net;initial catalog=Docker_Main;;persist security info=True;user id=azdevsoftware;password=1h52dev#az;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
+    "MeterValue20DBContext": "data source=zerova-ev-dev.database.windows.net;initial catalog=Docker_Main;;persist security info=True;user id=azdevsoftware;password=1h52dev#az;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
+    "ConnectionLogDBContext": "data source=zerova-ev-dev.database.windows.net;initial catalog=StandardOCPP_ConnectionLog;persist security info=True;user id=azdevsoftware;password=1h52dev#az;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
+    "MainDBContext": "data source=zerova-ev-dev.database.windows.net;initial catalog=StandardOCPP_Main;;persist security info=True;user id=azdevsoftware;password=1h52dev#az;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
+    "MeterValueDBContext": "data source=zerova-ev-dev.database.windows.net;initial catalog=StandardOCPP_MeterValue;;persist security info=True;user id=azdevsoftware;password=1h52dev#az;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
+    "APILogDBContext": "data source=zerova-ev-dev.database.windows.net;initial catalog=StandardOCPP_ApiLog;;persist security info=True;user id=azdevsoftware;password=1h52dev#az;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true",
+    "WebDBContext": "data source=zerova-ev-dev.database.windows.net;initial catalog=StandardOCPP_Web;;persist security info=True;user id=azdevsoftware;password=1h52dev#az;MultipleActiveResultSets=True;App=EntityFramework;TrustServerCertificate=true"
   },
   "NLog": {
     "targets": {

+ 3 - 0
Prod_Build.bat

@@ -0,0 +1,3 @@
+for /f %%i in ('git rev-parse --short HEAD') do set ssha=%%i
+docker build ./ -t evdevcontainerregistry.azurecr.io/api:%ssha% --label "git-commit=%ssha%"
+docker push evdevcontainerregistry.azurecr.io/api:%ssha%

+ 0 - 5
build.bat

@@ -1,5 +0,0 @@
-for /f %%i in ('git rev-parse --short HEAD') do set ssha=%%i
-docker build ./ -t 172.1.2.214:5000/api:test --label "git-commit=%ssha%"
-::docker push 172.1.2.214:5000/api:test
-docker tag 172.1.2.214:5000/api:test evdevcontainerregistry.azurecr.io/api:test
-docker push evdevcontainerregistry.azurecr.io/api:test