Bläddra i källkod

1. 取得站點資訊含槍頭

Jessica Tseng 4 år sedan
förälder
incheckning
0af860f16c

+ 44 - 30
EVCB_OCPP.WEBAPI/Controllers/Version1/CPOController.cs

@@ -11,6 +11,10 @@ using System.Web.Http.Description;
 using Newtonsoft.Json;
 using System.Threading.Tasks;
 using EVCB_OCPP.WEBAPI.Models.WebAPI.Dto;
+using System.Net.Http.Headers;
+using EVCB_OCPP.Packet.Messages.SubTypes;
+using System.Security.Cryptography.X509Certificates;
+using OCPPPackage.Profiles;
 
 namespace EVCB_OCPP.WEBAPI.Controllers.Version1
 {
@@ -260,7 +264,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
                 InternalHttpClient _client = new InternalHttpClient();
                 CustomerService _customer = new CustomerService();
 
-                string[] parts = Request.RequestUri.ToString().Split('/');              
+                string[] parts = Request.RequestUri.ToString().Split('/');
 
                 string urlformat = "{0}//{1}/api/v1/ocpp16/transaction?ChargeBoxId={2}&TransactionId={3}";
 
@@ -305,7 +309,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
         [Route("commands/reserve_now")]
         [ResponseType(typeof(CPOOuterResponse))]
         [HttpPost]
-        async public Task<HttpResponseMessage> ReserveNow([FromBody]ReserveNowRequest request)
+        async public Task<HttpResponseMessage> ReserveNow([FromBody] ReserveNowRequest request)
         {
             var result = new CPOOuterResponse();
             HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
@@ -651,7 +655,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
         [Route("commands/set_locallist")]
         [ResponseType(typeof(CPOOuterResponse))]
         [HttpPost]
-        async public Task<HttpResponseMessage> SendLocalList(string ChargeBoxId, [FromBody]LocalListRequest request)
+        async public Task<HttpResponseMessage> SendLocalList(string ChargeBoxId, [FromBody] LocalListRequest request)
         {
             var result = new CPOOuterResponse();
             HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
@@ -1028,7 +1032,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
 
                 // query meter value
                 ChargePointService _service = new ChargePointService();
-                var transactionData = _service.GetActiveSessionInfo(ChargeBoxId, new List<Packet.Messages.SubTypes.Measurand>()
+                var transactionDatas = _service.GetActiveSessionInfo(ChargeBoxId, new List<Packet.Messages.SubTypes.Measurand>()
                 {   Packet.Messages.SubTypes.Measurand.Voltage,
                     Packet.Messages.SubTypes.Measurand.Current_Import,
                     Packet.Messages.SubTypes.Measurand.SoC,
@@ -1036,7 +1040,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
                     Packet.Messages.SubTypes.Measurand.Energy_Active_Import_Interval
                 }, SessionId, IdTag);
 
-                if (transactionData == null)
+                if (transactionDatas == null)
                 {
                     result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
                     result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CANT_FIND_RESULT;
@@ -1044,25 +1048,32 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
                 }
                 else
                 {
-                    var _innerData = new
+                    List<ActiveSession> _innerData = new List<ActiveSession>();
+                  
+                    foreach (var transactionData in transactionDatas)
                     {
-                        ChargeBoxId= ChargeBoxId,
-                        SessionId = transactionData.Id,
-                        ElaspedTime = (int)DateTime.UtcNow.Subtract(transactionData.StartTime).TotalMinutes,
-                        ConnectorId = transactionData.ConnectorId,
-                        IdTag = transactionData.StartIdTag,
-                        Power = transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Power_Active_Import).Select(x => x.Value).FirstOrDefault(),
-                        Power_Format = transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Power_Active_Import).Select(x => x.Unit.ToString()).FirstOrDefault(),
-                        Current = transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Current_Import).Select(x => x.Value).FirstOrDefault(),
-                        Current_Format = transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Current_Import).Select(x => x.Unit.ToString()).FirstOrDefault(),
-                        Energy = transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Energy_Active_Import_Interval).Select(x => x.Value).FirstOrDefault(),
-                        Energy_Format = transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Energy_Active_Import_Interval).Select(x => x.Unit.ToString()).FirstOrDefault(),
-                        Voltage = transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Voltage).Select(x => x.Value).FirstOrDefault(),
-                        Voltage_Format = transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Voltage).Select(x => x.Unit.ToString()).FirstOrDefault(),
-                        SOC = transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Unit.ToString()).FirstOrDefault()==null?null: transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Value).FirstOrDefault(),
-                        SOC_Format = transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Unit.ToString()).FirstOrDefault(),
-                    };
 
+
+                        _innerData.Add(new ActiveSession()
+                        {
+                            ChargeBoxId = ChargeBoxId,
+                            SessionId = transactionData.Id,
+                            ElaspedTime = (int)DateTime.UtcNow.Subtract(transactionData.StartTime).TotalMinutes,
+                            ConnectorId = transactionData.ConnectorId,
+                            IdTag = transactionData.StartIdTag,
+                            Power = transactionData.MeterValues==null? "0":transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Power_Active_Import).Select(x => x.Value).FirstOrDefault(),
+                            Power_Format = transactionData.MeterValues == null ? UnitOfMeasure.W.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Power_Active_Import).Select(x => x.Unit.ToString()).FirstOrDefault(),
+                            Current = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Current_Import).Select(x => x.Value).FirstOrDefault(),
+                            Current_Format = transactionData.MeterValues == null ? UnitOfMeasure.A.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Current_Import).Select(x => x.Unit.ToString()).FirstOrDefault(),
+                            Energy = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Energy_Active_Import_Interval).Select(x => x.Value).FirstOrDefault(),
+                            Energy_Format = transactionData.MeterValues == null ? UnitOfMeasure.Wh.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Energy_Active_Import_Interval).Select(x => x.Unit.ToString()).FirstOrDefault(),
+                            Voltage = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Voltage).Select(x => x.Value).FirstOrDefault(),
+                            Voltage_Format = transactionData.MeterValues == null ? UnitOfMeasure.V.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Voltage).Select(x => x.Unit.ToString()).FirstOrDefault(),
+                            SOC = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Unit.ToString()).FirstOrDefault() == null ? null : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Value).FirstOrDefault(),
+                            SOC_Format = transactionData.MeterValues == null ? UnitOfMeasure.Percent.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Unit.ToString()).FirstOrDefault(),
+                        });
+
+                    }
                     result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
                     result.StatusCode = (int)CPO_StatusCode.Success;
                     result.StatusMessage = CPO_StatusMessage.Success;
@@ -1081,11 +1092,12 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
             }
 
         }
+      
 
         [Route("completedsession")]
         [ResponseType(typeof(CPOOuterResponse))]
         [HttpGet]
-        public HttpResponseMessage CompletedSession(string ChargeBoxId, string SessionId = "", string IdTag = "", DateTime SearchTime = new DateTime())
+        public HttpResponseMessage CompletedSession(string ChargeBoxId, string SessionId = "", string IdTag = "",string StartTime="", string StopTime = "")
         {
             var result = new CPOOuterResponse();
             HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
@@ -1103,9 +1115,11 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
                     return Request.CreateResponse(statusCode, result);
                 }
 
+                DateTime startDt =  string.IsNullOrEmpty(StartTime) ?new DateTime(1991,1,1):DateTime.Parse(StartTime);
+                DateTime stopDt = string.IsNullOrEmpty(StopTime) ? new DateTime(1991, 1, 1) : DateTime.Parse(StopTime);
                 // query meter value
                 ChargePointService _service = new ChargePointService();
-                var _innerData = _service.GetSessionDetail(ChargeBoxId, SessionId, IdTag, SearchTime);
+                var _innerData = _service.GetSessionDetail(ChargeBoxId, SessionId, IdTag, startDt, stopDt);
 
                 if (_innerData == null)
                 {
@@ -1135,7 +1149,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
         [Route("statistics/charging_sessions")]
         [ResponseType(typeof(CPOOuterResponse))]
         [HttpPost]
-        async public Task<HttpResponseMessage> ChargingSessionsStatistics([FromBody]StatisticsRequest request)
+        async public Task<HttpResponseMessage> ChargingSessionsStatistics([FromBody] StatisticsRequest request)
         {
             var result = new CPOOuterResponse();
             HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
@@ -1192,7 +1206,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
         [Route("statistics/energy_delivered")]
         [ResponseType(typeof(CPOOuterResponse))]
         [HttpPost]
-        async public Task<HttpResponseMessage> Energy_Delivered([FromBody]StatisticsRequest request)
+        async public Task<HttpResponseMessage> Energy_Delivered([FromBody] StatisticsRequest request)
         {
             var result = new CPOOuterResponse();
             HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
@@ -1249,7 +1263,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
         [Route("statistics/time_of_use")]
         [ResponseType(typeof(CPOOuterResponse))]
         [HttpPost]
-        async public Task<HttpResponseMessage> Time_of_Use([FromBody]StatisticsRequest request)
+        async public Task<HttpResponseMessage> Time_of_Use([FromBody] StatisticsRequest request)
         {
             var result = new CPOOuterResponse();
             HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
@@ -1306,7 +1320,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
         [Route("statistics/peak_load")]
         [ResponseType(typeof(CPOOuterResponse))]
         [HttpPost]
-        async public Task<HttpResponseMessage> Peak_Load([FromBody]StatisticsRequest request)
+        async public Task<HttpResponseMessage> Peak_Load([FromBody] StatisticsRequest request)
         {
             var result = new CPOOuterResponse();
             HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
@@ -1362,7 +1376,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
         [Route("statistics/sessions")]
         [ResponseType(typeof(CPOOuterResponse))]
         [HttpPost]
-        async public Task<HttpResponseMessage> Sessions([FromBody]StatisticsRequest request)
+        async public Task<HttpResponseMessage> Sessions([FromBody] StatisticsRequest request)
         {
             var result = new CPOOuterResponse();
             HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
@@ -1420,7 +1434,7 @@ namespace EVCB_OCPP.WEBAPI.Controllers.Version1
         [Route("statistics/fault")]
         [ResponseType(typeof(CPOOuterResponse))]
         [HttpPost]
-        async public Task<HttpResponseMessage> Fault([FromBody]StatisticsRequest request)
+        async public Task<HttpResponseMessage> Fault([FromBody] StatisticsRequest request)
         {
             var result = new CPOOuterResponse();
             HttpStatusCode statusCode = HttpStatusCode.InternalServerError;

+ 3 - 1
EVCB_OCPP.WEBAPI/EVCB_OCPP.WEBAPI.csproj

@@ -226,6 +226,7 @@
     <Compile Include="Handlers\CPOAuthentication.cs" />
     <Compile Include="Handlers\GlobalExceptionHandler .cs" />
     <Compile Include="Handlers\InernalAuthentication.cs" />
+    <Compile Include="Helpers\ConnectorTypeConverter .cs" />
     <Compile Include="Helpers\WebApiHelper.cs" />
     <Compile Include="Models\ApiLogEntry.cs" />
     <Compile Include="Models\ConnectorMeterValue.cs" />
@@ -236,6 +237,7 @@
     <Compile Include="Models\WebAPI\ComandExecution.cs" />
     <Compile Include="Models\WebAPI\CPOResponseDescription.cs" />
     <Compile Include="Models\WebAPI\CPOOuterResponse.cs" />
+    <Compile Include="Models\WebAPI\Dto\ActiveSession.cs" />
     <Compile Include="Models\WebAPI\Dto\CommandResponseType.cs" />
     <Compile Include="Models\WebAPI\Dto\CommandResultType.cs" />
     <Compile Include="Models\WebAPI\Dto\CommandType.cs" />
@@ -375,7 +377,7 @@
           <AutoAssignPort>True</AutoAssignPort>
           <DevelopmentServerPort>63823</DevelopmentServerPort>
           <DevelopmentServerVPath>/</DevelopmentServerVPath>
-          <IISUrl>http://localhost:63823/</IISUrl>
+          <IISUrl>http://localhost:60123/</IISUrl>
           <NTLMAuthentication>False</NTLMAuthentication>
           <UseCustomServer>False</UseCustomServer>
           <CustomServerUrl>

+ 34 - 0
EVCB_OCPP.WEBAPI/Helpers/ConnectorTypeConverter .cs

@@ -0,0 +1,34 @@
+using EVCB_OCPP.WEBAPI.Models.WebAPI.Dto;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+
+namespace EVCB_OCPP.WEBAPI.Helpers
+{
+    public class ConnectorTypeConverter : JsonConverter
+    {
+        public override bool CanConvert(Type objectType)
+        {
+            return objectType == typeof(string);
+        }
+
+        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+        {
+            var enumString = (string)reader.Value;
+
+            return Enum.Parse(typeof(ConnectorType), enumString, true);
+        }
+
+        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+        {
+            ConnectorType messageTransportResponseStatus = (ConnectorType)value;
+
+            string result = messageTransportResponseStatus.ToString();
+            result=  result.Replace('_', ' ');
+
+            writer.WriteValue(result);
+        }
+    }
+}

+ 42 - 0
EVCB_OCPP.WEBAPI/Models/WebAPI/Dto/ActiveSession.cs

@@ -0,0 +1,42 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+
+namespace EVCB_OCPP.WEBAPI.Models.WebAPI.Dto
+{
+    public class ActiveSession
+    {
+        public string ChargeBoxId { set; get; }
+
+        public int SessionId { set; get; }
+
+        public int ConnectorId { set; get; }
+
+        public string IdTag { set; get; }
+
+        public int ElaspedTime { set; get; }
+
+        public string Power { set; get; }
+
+        public string Power_Format { set; get; }
+
+        public string Current { set; get; }
+
+        public string Current_Format { set; get; }
+
+        public string Energy { set; get; }
+
+
+        public string Energy_Format { set; get; }
+
+        public string Voltage { set; get; }
+
+        public string Voltage_Format { set; get; }
+
+        public string SOC { set; get; }
+
+        public string SOC_Format { set; get; }
+
+    }
+}

+ 3 - 2
EVCB_OCPP.WEBAPI/Models/WebAPI/Dto/Connector.cs

@@ -1,4 +1,5 @@
-using Newtonsoft.Json;
+using EVCB_OCPP.WEBAPI.Helpers;
+using Newtonsoft.Json;
 using Newtonsoft.Json.Converters;
 using System;
 using System.Collections.Generic;
@@ -14,7 +15,7 @@ namespace EVCB_OCPP.WEBAPI.Models.WebAPI.Dto
         [JsonConverter(typeof(StringEnumConverter))]
         public Status Status { set; get; }
 
-        [JsonConverter(typeof(StringEnumConverter))]
+        [JsonConverter(typeof(ConnectorTypeConverter))]
         public ConnectorType ConnectorType { set; get; }
 
         public string FaultMessage { set; get; }

+ 13 - 7
EVCB_OCPP.WEBAPI/Models/WebAPI/Dto/ConnectorType.cs

@@ -1,4 +1,5 @@
-using System;
+using Newtonsoft.Json;
+using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
@@ -7,12 +8,17 @@ namespace EVCB_OCPP.WEBAPI.Models.WebAPI.Dto
 {
     public enum ConnectorType
     {
-        Other=-1,
-        CHADEMO =1,
-        AC=4,
-        CCS=2,
-        GBT=3
-      
+        Other = -1,
+        Type_1=1,
+        Type_2 = 2,
+        GBT_AC = 3,
+        CCS2_AC=4,
+        Type_E = 5,
+        CHAdeMO=6,
+        CCS_1=7,
+        CCS_2=8,
+        GBT_DC=9
+
     }
 
     

+ 4 - 1
EVCB_OCPP.WEBAPI/Models/WebAPI/Station.cs

@@ -1,4 +1,5 @@
-using Newtonsoft.Json;
+using EVCB_OCPP.WEBAPI.Models.WebAPI.Dto;
+using Newtonsoft.Json;
 using System;
 using System.Collections.Generic;
 using System.Linq;
@@ -20,6 +21,8 @@ namespace EVCB_OCPP.WEBAPI.Models.WebAPI
         public decimal Longitude { set; get; }
 
         public GetLocation Coordinates { set; get; }
+
+        public List<EVSE> EVSEs { set; get; }
     }
 
     public class GetLocation

+ 87 - 86
EVCB_OCPP.WEBAPI/Services/ChargePointService.cs

@@ -35,6 +35,8 @@ namespace EVCB_OCPP.WEBAPI.Services
                 parameters.Add("@LastUpdatedTime", lastUpdatedOn, DbType.DateTime, ParameterDirection.Output);
                 conn.Execute("GetBasicInfoLastUpdatedTimeById", parameters, commandType: System.Data.CommandType.StoredProcedure);
                 lastUpdatedOn = DateTime.SpecifyKind(parameters.Get<DateTime>("@LastUpdatedTime"), DateTimeKind.Utc);
+
+
             }
 
             return lastUpdatedOn;
@@ -118,7 +120,7 @@ namespace EVCB_OCPP.WEBAPI.Services
                         FaultMessage = ((ChargePointErrorCode)_RefConnector.ChargePointErrorCodeId).ToString() + (string.IsNullOrEmpty(_RefConnector.VendorErrorCode) ? "" : "-" + _RefConnector.VendorErrorCode)
 
                     });
-                }                
+                }
             }
             return _machine == null ? null : cp;
         }
@@ -293,30 +295,45 @@ namespace EVCB_OCPP.WEBAPI.Services
             return existed;
         }
 
-        public TransasctionData GetActiveSessionInfo(string chargeBoxId, List<Measurand> requiredMeasurands, string sessionId = "", string idTag = "")
+        public List<TransasctionData> GetActiveSessionInfo(string chargeBoxId, List<Measurand> requiredMeasurands, string sessionId = "", string idTag = "")
         {
             List<ConnectorMeterValue> meterValues = new List<ConnectorMeterValue>();
             ConnectorMeterValueModel meterModel = null;
-            TransasctionData transactionData = null;
-            if (string.IsNullOrEmpty(chargeBoxId)) return transactionData;
+            List<TransasctionData> transactionDatas = null;
+            if (string.IsNullOrEmpty(chargeBoxId)) return transactionDatas;
 
 
             try
             {
                 var parameters = new DynamicParameters();
                 parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input);
-                parameters.Add(string.IsNullOrEmpty(sessionId) ? "@StartIdTag" : "@TransactionId", string.IsNullOrEmpty(sessionId) ? idTag : sessionId, DbType.String, ParameterDirection.Input);
+
 
                 using (SqlConnection conn = new SqlConnection(mainConnectionString))
                 {
                     string date = DateTime.UtcNow.ToString("yyMMdd");
-                    string strSql = "Select Top(1) Id , ConnectorId, StartTime,StartIdTag from [dbo].[TransactionRecord] where ChargeBoxId=@ChargeBoxId and " + (string.IsNullOrEmpty(sessionId) ? "StartIdTag=@StartIdTag" : "Id=@TransactionId") + " and StopTime='1991-01-01 00:00:00.000'  order by Id desc;";
-                    transactionData = conn.Query<TransasctionData>(strSql, parameters, null, true, EVCBConfiguration.DB_DefaultConnectionTimeout).FirstOrDefault();
+                    string strSql = string.Empty;
+                    if (string.IsNullOrEmpty(sessionId) && string.IsNullOrEmpty(idTag))
+                    {
+                        strSql = "Select Id, ConnectorId, StartTime, StartIdTag from TransactionRecord " +
+                            "where StopTime = '1991-01-01 00:00:00.000' and ChargeBoxId = @ChargeBoxId and StartTime in (select  max(StartTime) from[TransactionRecord] where StopTime = '1991-01-01 00:00:00.000' and ChargeBoxId = @ChargeBoxId group by ConnectorId )";
+                    }
+                    else
+                    {
+                        parameters.Add(string.IsNullOrEmpty(sessionId) ? "@StartIdTag" : "@TransactionId", string.IsNullOrEmpty(sessionId) ? idTag : sessionId, DbType.String, ParameterDirection.Input);
+
+                        strSql = "Select Id, ConnectorId, StartTime, StartIdTag from TransactionRecord" +
+                          "where StopTime = '1991-01-01 00:00:00.000' and ChargeBoxId = @ChargeBoxId and StartTime in (select  max(StartTime) from [TransactionRecord] where  " + (string.IsNullOrEmpty(sessionId) ? "StartIdTag=@StartIdTag" : "Id=@TransactionId") + " and StopTime = '1991-01-01 00:00:00.000' and ChargeBoxId = @ChargeBoxId group by ConnectorId )";
+
+                    }
+
+                    transactionDatas = conn.Query<TransasctionData>(strSql, parameters, null, true, EVCBConfiguration.DB_DefaultConnectionTimeout).ToList();
+
 
                 }
 
             }
-            catch
+            catch (Exception ex)
             {
                 ;
             }
@@ -324,60 +341,64 @@ namespace EVCB_OCPP.WEBAPI.Services
 
             for (int i = 0; i < requiredMeasurands.Count; i++)
             {
-                var parameters = new DynamicParameters();
-                parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input);
-                parameters.Add("@TransactionId", transactionData.Id, DbType.String, ParameterDirection.Input);
-                parameters.Add("@MeasurandId", requiredMeasurands[i], DbType.String, ParameterDirection.Input);
-
-                try
+                for (int j = 0; j < transactionDatas.Count; j++)
                 {
-                    using (SqlConnection conn = new SqlConnection(meterConnectionString))
-                    {
-                        string date = transactionData.StartTime.ToString("yyMMdd");
-                        string strSql = "Select Top(1) * from [dbo].[ConnectorMeterValueRecord" + date + "] where ChargeBoxId=@ChargeBoxId and TransactionId=@TransactionId and MeasurandId=@MeasurandId order by CreatedOn desc;";
-                        meterModel = conn.Query<ConnectorMeterValueModel>(strSql, parameters, null, true, EVCBConfiguration.DB_DefaultConnectionTimeout).FirstOrDefault();
-
-                    }
+                    var parameters = new DynamicParameters();
+                    parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input);
+                    parameters.Add("@TransactionId", transactionDatas[j].Id, DbType.String, ParameterDirection.Input);
+                    parameters.Add("@MeasurandId", requiredMeasurands[i], DbType.String, ParameterDirection.Input);
 
-                    if (meterModel != null)
+                    try
                     {
-                        if(transactionData.MeterValues== null)
+                        using (SqlConnection conn = new SqlConnection(meterConnectionString))
                         {
-                            transactionData.MeterValues = new List<ConnectorMeterValue>();
+                            string date = transactionDatas[j].StartTime.ToString("yyMMdd");
+                            string strSql = "Select Top(1) * from [dbo].[ConnectorMeterValueRecord" + date + "] where ChargeBoxId=@ChargeBoxId and TransactionId=@TransactionId and MeasurandId=@MeasurandId order by CreatedOn desc;";
+                            meterModel = conn.Query<ConnectorMeterValueModel>(strSql, parameters, null, true, EVCBConfiguration.DB_DefaultConnectionTimeout).FirstOrDefault();
+
                         }
 
-                        transactionData.MeterValues.Add(new ConnectorMeterValue()
+                        if (meterModel != null)
                         {
-                            ChargeBoxId = meterModel.ChargeBoxId,
-                            ConnectorId = meterModel.ConnectorId,
-                            CreatedOn = meterModel.CreatedOn,
-                            Context = meterModel.ContextId < 1 ? (ReadingContext?)null : (ReadingContext?)meterModel.ContextId,
-                            Format = meterModel.FormatId < 1 ? (ValueFormat?)null : (ValueFormat?)meterModel.FormatId,
-                            Location = meterModel.LocationId < 1 ? (Location?)null : (Location?)meterModel.LocationId,
-                            Measurand = meterModel.MeasurandId < 1 ? (Measurand?)null : (Measurand?)meterModel.MeasurandId,
-                            Phase = meterModel.PhaseId < 1 ? (Phase?)null : (Phase?)meterModel.PhaseId,
-                            Unit = meterModel.UnitId < 1 ? (UnitOfMeasure?)UnitOfMeasure.Wh : (UnitOfMeasure?)meterModel.UnitId,
-                            Value = meterModel.Value,
-                            TransactionId = meterModel.TransactionId
+                            if (transactionDatas[j].MeterValues == null)
+                            {
+                                transactionDatas[j].MeterValues = new List<ConnectorMeterValue>();
+                            }
 
-                        });
+                            transactionDatas[j].MeterValues.Add(new ConnectorMeterValue()
+                            {
+                                ChargeBoxId = meterModel.ChargeBoxId,
+                                ConnectorId = meterModel.ConnectorId,
+                                CreatedOn = meterModel.CreatedOn,
+                                Context = meterModel.ContextId < 1 ? (ReadingContext?)null : (ReadingContext?)meterModel.ContextId,
+                                Format = meterModel.FormatId < 1 ? (ValueFormat?)null : (ValueFormat?)meterModel.FormatId,
+                                Location = meterModel.LocationId < 1 ? (Location?)null : (Location?)meterModel.LocationId,
+                                Measurand = meterModel.MeasurandId < 1 ? (Measurand?)null : (Measurand?)meterModel.MeasurandId,
+                                Phase = meterModel.PhaseId < 1 ? (Phase?)null : (Phase?)meterModel.PhaseId,
+                                Unit = meterModel.UnitId < 1 ? (UnitOfMeasure?)UnitOfMeasure.Wh : (UnitOfMeasure?)meterModel.UnitId,
+                                Value = meterModel.Value,
+                                TransactionId = meterModel.TransactionId
 
+                            });
 
 
+
+                        }
+                    }
+                    catch (Exception ex)
+                    {
+                        break;
                     }
                 }
-                catch(Exception ex)
-                {
-                    break;
-                }
+
 
             }
 
-            return transactionData;
+            return transactionDatas;
         }
 
 
-        public List<SessionDetail> GetSessionDetail(string chargeBoxId, string sessionId, string idTag, DateTime searchTime)
+        public List<SessionDetail> GetSessionDetail(string chargeBoxId, string sessionId, string idTag, DateTime startTime, DateTime stopTime)
         {
             List<SessionDetail> detail = new List<SessionDetail>();
             List<TransactionRecordModel> transactionModel = null;
@@ -385,41 +406,49 @@ namespace EVCB_OCPP.WEBAPI.Services
 
 
             var parameters = new DynamicParameters();
-            parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input);
-            parameters.Add("@TransactionId", sessionId, DbType.String, ParameterDirection.Input);
 
             try
             {
+            
+                bool restrictedRange = false;
+                if (startTime != new DateTime(1991, 1, 1))
+                {
+                    restrictedRange = true;
+                    parameters.Add("@startTime", startTime, DbType.DateTime, ParameterDirection.Input);
+                    parameters.Add("@stopTime", stopTime, DbType.DateTime, ParameterDirection.Input);
+                }
+               
                 using (SqlConnection conn = new SqlConnection(mainConnectionString))
                 {
                     string strSql = string.Empty;
-                    if (!string.IsNullOrEmpty(sessionId))
+                    if (!string.IsNullOrEmpty(sessionId) && string.IsNullOrEmpty(idTag))
                     {
                         parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input);
                         parameters.Add("@TransactionId", sessionId, DbType.String, ParameterDirection.Input);
-                        strSql = "Select Top(1) * from [dbo].[TransactionRecord] where ChargeBoxId=@ChargeBoxId and Id=@TransactionId and StopTime!='1991-01-01 00:00:00.000' Order by Id desc ;";
+                        strSql = "Select Top(1) * from [dbo].[TransactionRecord] where ChargeBoxId=@ChargeBoxId and Id=@TransactionId and StopTime!='1991-01-01 00:00:00.000' "+ (restrictedRange ? " and StartTime >=@startTime and  StartTime <=@stopTime" : "" )+ " Order by Id desc ;";
                     }
-                    else if (!string.IsNullOrEmpty(idTag))
+                    else if (!string.IsNullOrEmpty(idTag) && string.IsNullOrEmpty(sessionId))
                     {
-                        parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input);
+                        if(!string.IsNullOrEmpty(chargeBoxId))
+                        {
+                            parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input);
+                        }
+                   
                         parameters.Add("@StartIdTag", idTag, DbType.String, ParameterDirection.Input);
-                        strSql = "Select Top(1) * from [dbo].[TransactionRecord] where ChargeBoxId=@ChargeBoxId and StartIdTag=@StartIdTag   and StopTime!='1991-01-01 00:00:00.000' Order by Id desc  ;";
+                        strSql = "Select  * from [dbo].[TransactionRecord] where "+ (!string.IsNullOrEmpty(chargeBoxId)? " ChargeBoxId=@ChargeBoxId and  " :"")+ "  StartIdTag=@StartIdTag   and StopTime!='1991-01-01 00:00:00.000' " + (restrictedRange ? " and StartTime >=@startTime and  StartTime <=@stopTime" : "") + " Order by Id desc  ;";
 
                     }
                     else
                     {
-                        if (searchTime == new DateTime())
-                        {
-                            return detail;
-                        }
 
                         parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input);
-                        parameters.Add("@StartIdTag", idTag, DbType.String, ParameterDirection.Input);
-                        strSql = "Select Top(1) * from [dbo].[TransactionRecord] where ChargeBoxId=@ChargeBoxId and StartIdTag=@StartIdTag   and StopTime!='1991-01-01 00:00:00.000' Order by Id desc  ;";
+
+                        strSql = "Select  * from [dbo].[TransactionRecord] where ChargeBoxId=@ChargeBoxId  and StopTime!='1991-01-01 00:00:00.000' " + (restrictedRange ? " and StartTime >=@startTime and  StartTime <=@stopTime" : "") + " Order by Id desc  ;";
 
                     }
 
                     transactionModel = conn.Query<TransactionRecordModel>(strSql, parameters, null, true, EVCBConfiguration.DB_DefaultConnectionTimeout).ToList();
+                   
 
                 }
 
@@ -439,7 +468,7 @@ namespace EVCB_OCPP.WEBAPI.Services
                 }
 
             }
-            catch
+            catch(Exception ex)
             {
 
             }
@@ -514,36 +543,8 @@ namespace EVCB_OCPP.WEBAPI.Services
 
         private ConnectorType ConvertConnectorType(int value)
         {
-            ConnectorType result = ConnectorType.Other;
+            ConnectorType result = (ConnectorType)value;
 
-            switch (value)
-            {
-                case 1://CHADEMO
-                    {
-                        result = ConnectorType.CHADEMO;
-                    }
-                    break;
-                case 4://AC
-                    {
-                        result = ConnectorType.AC;
-                    }
-                    break;
-                case 2:
-                    {
-                        result = ConnectorType.CCS;
-                    }
-                    break;
-                case 3://GBT
-                    {
-                        result = ConnectorType.GBT;
-                    }
-                    break;
-                default:
-                    break;
-
-
-
-            }
             return result;
         }
 

+ 17 - 6
EVCB_OCPP.WEBAPI/Services/ChargingStationService.cs

@@ -42,6 +42,8 @@ namespace EVCB_OCPP.WEBAPI.Services
                 foreach (var station in _stations)
                 {
                     station.Coordinates = new GetLocation() { Latitude = station.Latitude, Longitude = station.Longitude };
+                    station.EVSEs = GetEVSEsbyStationId(station.Id, null, null, -1, 100000);
+
                 }
             }
             return _stations;
@@ -82,8 +84,8 @@ namespace EVCB_OCPP.WEBAPI.Services
             while (startIndex < limit && startIndex < machineIds.Count)
             {
                 var _machineUpdateOn = _CPService.GetLastUpdatedTimebyMachineId(machineIds[startIndex]);
-                      
-             
+
+
                 if (dateFrom.HasValue && _machineUpdateOn < dateFrom.Value.ToUniversalTime())
                 {
                     limit++;
@@ -98,10 +100,19 @@ namespace EVCB_OCPP.WEBAPI.Services
                     continue;
                 }
 
-               var _machine = _CPService.GetBasicInfobyId(machineIds[startIndex]);
-                _machine.LastUpdated = _machineUpdateOn;
-                _machine.StationId = stationId;
-                _chargePoints.Add(_machine);
+                var _machine = _CPService.GetBasicInfobyId(machineIds[startIndex]);
+                if (_machine != null)
+                {
+                    _machine.LastUpdated = _machineUpdateOn;
+                    _machine.StationId = stationId;
+                    _chargePoints.Add(_machine);
+
+                }
+                else
+                {
+                    limit++;
+                }
+
                 startIndex++;
 
             }