Jelajahi Sumber

2020/04/23 Jessica
Actions:
1.跟第三方平台驗證卡片
2.電樁告警拋送至第三方平台

Jessica.Tseng 4 tahun lalu
induk
melakukan
d42f098dc7

+ 39 - 3
EVCB_OCPP.WSServer/App.config

@@ -16,9 +16,9 @@
  
   </connectionStrings>
   <appSettings>
-    <add key="ServerIP" value=""/>
-    <add key="WSPort" value="8080"/>
-    <add key="WSSPort" value="2013"/>
+    <add key="ServerIP" value="" />
+    <add key="WSPort" value="8080" />
+    <add key="WSSPort" value="2013" />
   
   </appSettings>
   <startup>
@@ -42,6 +42,42 @@
         <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
         <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
       </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.Extensions.Primitives" publicKeyToken="adb9793829ddae60" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.Extensions.Configuration.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.Extensions.DependencyInjection.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.Extensions.Options" publicKeyToken="adb9793829ddae60" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.Extensions.DependencyInjection" publicKeyToken="adb9793829ddae60" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="Microsoft.Extensions.Logging" publicKeyToken="adb9793829ddae60" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-3.1.2.0" newVersion="3.1.2.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
+      </dependentAssembly>
     </assemblyBinding>
   </runtime>
   <entityFramework>

+ 0 - 40
EVCB_OCPP.WSServer/BusinessService/FakeLocalBusinessService.cs

@@ -1,40 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using EVCB_OCPP.Packet.Messages.SubTypes;
-
-namespace EVCB_OCPP.WSServer.BusinessService
-{
-    public class FakeLocalBusinessService : IBusinessService
-    {
-        Dictionary<string, IdTagInfo> localAuthDic = new Dictionary<string, IdTagInfo>()
-        {
-            { "AC5CDC3D", new IdTagInfo(){  status= AuthorizationStatus.Invalid} },
-            { "48C4CBD9257A", new IdTagInfo(){  status= AuthorizationStatus.Invalid} },
-            { "3DDC5CAC", new IdTagInfo(){  status= AuthorizationStatus.Invalid} },
-           { "3EFBDEAC", new IdTagInfo(){  status= AuthorizationStatus.Invalid} },
-
-        };
-
-        string customerId = string.Empty;
-
-        public FakeLocalBusinessService(string customerId)
-        {
-            this.customerId = customerId;
-        }
-
-        public IdTagInfo Authorize(string idTag)
-        {
-            IdTagInfo result = new IdTagInfo() { status = AuthorizationStatus.Accepted };
-
-            if (localAuthDic.ContainsKey(idTag))
-            {
-                result = localAuthDic[idTag];
-            }
-            return result;
-
-        }
-    }
-}

+ 0 - 22
EVCB_OCPP.WSServer/BusinessService/OuterBusinessService.cs

@@ -1,22 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using EVCB_OCPP.Packet.Messages.SubTypes;
-
-namespace EVCB_OCPP.WSServer.BusinessService
-{
-    public class OuterBusinessService : IBusinessService
-    {
-        public OuterBusinessService(string customerId)
-        {
-
-        }
-
-        public IdTagInfo Authorize(string idTag)
-        {
-           return new IdTagInfo() { status = AuthorizationStatus.Accepted };
-        }
-    }
-}

+ 26 - 0
EVCB_OCPP.WSServer/Dto/ErrorDetails.cs

@@ -0,0 +1,26 @@
+using EVCB_OCPP.Packet.Messages.SubTypes;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.WSServer.Dto
+{
+    public class ErrorDetails
+    {
+        public string ChargeBoxId { set; get; }
+
+        public int ConnectorId { set; get; }
+
+        public ChargePointErrorCode ErrorCode { set; get; }
+
+        public string Info { set; get; }
+
+        public string VendorId { set; get; }
+
+        public string VendorErrorCode { set; get; }
+
+        public DateTime OCcuredOn { set; get; }
+    }
+}

+ 58 - 4
EVCB_OCPP.WSServer/EVCB_OCPP.WSServer.csproj

@@ -50,6 +50,39 @@
     <Reference Include="log4net, Version=1.2.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
       <HintPath>..\packages\log4net.2.0.3\lib\net40-full\log4net.dll</HintPath>
     </Reference>
+    <Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.1.1.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Configuration, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Configuration.3.1.2\lib\netstandard2.0\Microsoft.Extensions.Configuration.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Configuration.Abstractions.3.1.2\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Configuration.Binder, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Configuration.Binder.3.1.2\lib\netstandard2.0\Microsoft.Extensions.Configuration.Binder.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.DependencyInjection, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.DependencyInjection.3.1.2\lib\net461\Microsoft.Extensions.DependencyInjection.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.3.1.2\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Http, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Http.3.1.2\lib\netstandard2.0\Microsoft.Extensions.Http.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Logging, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Logging.3.1.2\lib\netstandard2.0\Microsoft.Extensions.Logging.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Logging.Abstractions.3.1.2\lib\netstandard2.0\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Options, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Options.3.1.2\lib\netstandard2.0\Microsoft.Extensions.Options.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Extensions.Primitives, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Extensions.Primitives.3.1.2\lib\netstandard2.0\Microsoft.Extensions.Primitives.dll</HintPath>
+    </Reference>
     <Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
       <HintPath>..\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
     </Reference>
@@ -57,12 +90,31 @@
       <HintPath>..\packages\NLog.4.6.6\lib\net45\NLog.dll</HintPath>
     </Reference>
     <Reference Include="System" />
+    <Reference Include="System.Buffers, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Buffers.4.4.0\lib\netstandard2.0\System.Buffers.dll</HintPath>
+    </Reference>
+    <Reference Include="System.ComponentModel.Annotations, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.ComponentModel.Annotations.4.7.0\lib\net461\System.ComponentModel.Annotations.dll</HintPath>
+    </Reference>
     <Reference Include="System.ComponentModel.DataAnnotations" />
     <Reference Include="System.Configuration" />
     <Reference Include="System.Core" />
     <Reference Include="System.IO.Compression" />
+    <Reference Include="System.Memory, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Memory.4.5.2\lib\netstandard2.0\System.Memory.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Numerics" />
+    <Reference Include="System.Numerics.Vectors, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.6.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.7.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
+    </Reference>
     <Reference Include="System.Runtime.Serialization" />
     <Reference Include="System.ServiceModel" />
+    <Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.2\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll</HintPath>
+    </Reference>
     <Reference Include="System.Transactions" />
     <Reference Include="System.Xml.Linq" />
     <Reference Include="System.Data.DataSetExtensions" />
@@ -72,10 +124,11 @@
     <Reference Include="System.Xml" />
   </ItemGroup>
   <ItemGroup>
-    <Compile Include="BusinessService\BusinessServiceFactory.cs" />
-    <Compile Include="BusinessService\FakeLocalBusinessService.cs" />
-    <Compile Include="BusinessService\LocalBusinessService.cs" />
-    <Compile Include="BusinessService\OuterBusinessService.cs" />
+    <Compile Include="Dto\ErrorDetails.cs" />
+    <Compile Include="Service\BusinessServiceFactory.cs" />
+    <Compile Include="Service\HttpClientService.cs" />
+    <Compile Include="Service\LocalBusinessService.cs" />
+    <Compile Include="Service\OuterBusinessService.cs" />
     <Compile Include="Dto\ConnectorErrorStauts.cs" />
     <Compile Include="GlobalConfig.cs" />
     <Compile Include="Helper\Convertor.cs" />
@@ -91,6 +144,7 @@
     <Compile Include="Program.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="ProtalServer.cs" />
+    <Compile Include="Service\OuterHttpClient.cs" />
     <Compile Include="SuperSocket.Command\ProcessCallCmd.cs" />
     <Compile Include="SuperSocket.Command\ProcessCallErrorCmd.cs" />
     <Compile Include="SuperSocket.Command\ProcessCallResultCmd.cs" />

+ 9 - 1
EVCB_OCPP.WSServer/GlobalConfig.cs

@@ -1,4 +1,5 @@
-using System;
+using Newtonsoft.Json;
+using System;
 using System.Collections.Generic;
 using System.Configuration;
 using System.Linq;
@@ -102,7 +103,14 @@ namespace EVCB_OCPP.WSServer
             return DEFAULT_HEARTBEAT_INTERVAL;
         }
 
+        public static readonly int DB_DefaultConnectionTimeout = 60;
+        public static readonly string UTC_DATETIMEFORMAT = "yyyy/MM/dd'T'HH':'mm':'ss'Z'";
+        /// <summary>
+        /// 預設 Null的 DateTime 
+        /// </summary>
+        public static DateTime DefaultNullTime = new DateTime(1991, 1, 1);
 
+        public static JsonSerializerSettings JSONSERIALIZER_FORMAT = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None };
 
 
 

+ 79 - 45
EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs

@@ -11,7 +11,7 @@ using EVCB_OCPP.Packet.Features;
 using EVCB_OCPP.Packet.Messages;
 using EVCB_OCPP.Packet.Messages.Core;
 using EVCB_OCPP.Packet.Messages.SubTypes;
-using EVCB_OCPP.WSServer.BusinessService;
+using EVCB_OCPP.WSServer.Service;
 using EVCB_OCPP.WSServer.Dto;
 using Newtonsoft.Json;
 using OCPPPackage.Profiles;
@@ -73,21 +73,23 @@ namespace EVCB_OCPP.WSServer.Message
                             ConnectorErrorStauts _oldStatus = null;
                             using (var oldDB = new MainDBContext())
                             {
-                                if (_request.status == Packet.Messages.SubTypes.ChargePointStatus.Faulted)
+                                _oldStatus = oldDB.ConnectorStatus.Where(x => x.ChargeBoxId == session.ChargeBoxId
+                             && x.ConnectorId == _request.connectorId).Select(x => new ConnectorErrorStauts
+                             {
+                                 Status = x.Status,
+                                 ChargePointErrorCodeId = x.ChargePointErrorCodeId,
+                                 ErrorInfo = x.ErrorInfo,
+                                 VendorId = x.VendorId,
+                                 VendorErrorCode = x.VendorErrorCode
+                             }).FirstOrDefault();
+
+
+                                if (_request.status != (ChargePointStatus)_oldStatus.Status || _request.status == ChargePointStatus.Faulted)
                                 {
-                                    _oldStatus = oldDB.ConnectorStatus.Where(x => x.ChargeBoxId == session.ChargeBoxId
-                                 && x.ConnectorId == _request.connectorId).Select(x => new ConnectorErrorStauts
-                                 {
-                                     Status = x.Status,
-                                     ChargePointErrorCodeId = x.ChargePointErrorCodeId,
-                                     ErrorInfo = x.ErrorInfo,
-                                     VendorId = x.VendorId,
-                                     VendorErrorCode = x.VendorErrorCode
-                                 }).FirstOrDefault();
+                                    removeIds = oldDB.ConnectorStatus.Where(x => x.ChargeBoxId == session.ChargeBoxId
+                               && x.ConnectorId == _request.connectorId).Select(x => x.Id).ToList();
                                 }
 
-                                removeIds = oldDB.ConnectorStatus.Where(x => x.ChargeBoxId == session.ChargeBoxId
-                                 && x.ConnectorId == _request.connectorId).Select(x => x.Id).ToList();
                             }
 
                             using (var db = new MainDBContext())
@@ -135,6 +137,21 @@ namespace EVCB_OCPP.WSServer.Message
                             }
                         }
 
+                        if (_request.status == Packet.Messages.SubTypes.ChargePointStatus.Faulted)
+                        {
+                            var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString(), false);
+                            businessService.NotifyFaultStatus(new ErrorDetails()
+                            {
+                                ChargeBoxId = session.ChargeBoxId,
+                                ConnectorId = _request.connectorId,
+                                ErrorCode = _request.errorCode,
+                                Info = _request.info,
+                                OCcuredOn = _request.timestamp.Value,
+                                VendorErrorCode = _request.vendorErrorCode,
+
+                            });
+                        }
+
                         var confirm = new StatusNotificationConfirmation() { };
                         result.Message = confirm;
                         result.Success = true;
@@ -214,7 +231,7 @@ namespace EVCB_OCPP.WSServer.Message
                         if (DateTime.Compare(DateTime.UtcNow.AddSeconds(-10), _request.timestamp.ToUniversalTime()) >= 0)
                         {
                             var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString(), true);
-                            _idTagInfo = businessService.Authorize(_request.idTag);
+                            _idTagInfo = businessService.Authorize(session.ChargeBoxId, _request.idTag);
 
                         }
 
@@ -276,32 +293,10 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                         StopTransactionRequest _request = request as StopTransactionRequest;
                         List<TransactionDataRecord> _TransactionDatas = new List<TransactionDataRecord>();
-                        if (_request.transactionData != null)
-                        {
-                            if (_request.transactionData.Count > 0)
-                            {
-                                foreach (var item in _request.transactionData)
-                                {
-                                    foreach (var sampleVaule in item.sampledValue)
-                                    {
-                                        _TransactionDatas.Add(new TransactionDataRecord()
-                                        {
-                                            ChargeBoxId = session.ChargeBoxId,
-                                            MeasuredOn = item.timestamp,
-                                            TransactionId = _request.transactionId,
-                                            ContextId = sampleVaule.context.HasValue ? (int)sampleVaule.context : 0,
-                                            FormatId = sampleVaule.format.HasValue ? (int)sampleVaule.format : 0,
-                                            LocationId = sampleVaule.location.HasValue ? (int)sampleVaule.location : 0,
-                                            MeasurandId = sampleVaule.measurand.HasValue ? (int)sampleVaule.measurand : 0,
-                                            PhaseId = sampleVaule.phase.HasValue ? (int)sampleVaule.phase : 0,
-                                            UnitId = sampleVaule.unit.HasValue ? (int)sampleVaule.unit : 0,
-                                            Value = sampleVaule.value
-                                        });
-                                    }
-                                }
+                        int _ConnectorId = 0;
 
-                            }
-                        }
+                        var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString(), true);
+                        var _idTagInfo = businessService.Authorize(session.ChargeBoxId, _request.idTag);
 
                         using (var db = new MainDBContext())
                         {
@@ -310,6 +305,7 @@ namespace EVCB_OCPP.WSServer.Message
 
                             if (transaction != null)
                             {
+                                _ConnectorId = transaction.ConnectorId;
                                 transaction.MeterStop = _request.meterStop;
                                 transaction.StopTime = _request.timestamp;
                                 transaction.StopReasonId = _request.reason.HasValue ? (int)_request.reason.Value : 0;
@@ -323,11 +319,7 @@ namespace EVCB_OCPP.WSServer.Message
                                 db.SaveChanges();
                                 var confirm = new StopTransactionConfirmation()
                                 {
-                                    idTagInfo = new Packet.Messages.SubTypes.IdTagInfo()
-                                    {
-
-                                        status = Packet.Messages.SubTypes.AuthorizationStatus.Accepted
-                                    }
+                                    idTagInfo = _idTagInfo
 
                                 };
                                 result.Message = confirm;
@@ -339,6 +331,48 @@ namespace EVCB_OCPP.WSServer.Message
 
                             }
                         }
+
+                        if (_request.transactionData != null)
+                        {
+                            if (_request.transactionData.Count > 0)
+                            {
+                                using (var _meterDb = new MeterValueDBContext())
+                                {
+                                    foreach (var item in _request.transactionData)
+                                    {
+                                        foreach (var sampleVaule in item.sampledValue)
+                                        {
+                                            decimal value = Convert.ToDecimal(sampleVaule.value);
+
+                                            string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId," +
+                         "@ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
+
+                                            List<SqlParameter> parameter = new List<SqlParameter>
+                                        {
+                                              new SqlParameter("ChargeBoxId",session.ChargeBoxId),
+                                              new SqlParameter("ConnectorId",  (byte)_ConnectorId),
+                                              new SqlParameter("Value",value),
+                                              new SqlParameter("CreatedOn",item.timestamp),
+                                              new SqlParameter("ContextId",sampleVaule.context.HasValue ? (int)sampleVaule.context : 0),
+                                              new SqlParameter("FormatId",sampleVaule.format.HasValue ? (int)sampleVaule.format : 0),
+                                              new SqlParameter("MeasurandId",sampleVaule.measurand.HasValue ? (int)sampleVaule.measurand : 0),
+                                              new SqlParameter("PhaseId",sampleVaule.phase.HasValue ? (int)sampleVaule.phase : 0),
+                                              new SqlParameter("LocationId",sampleVaule.location.HasValue ? (int)sampleVaule.location : 0),
+                                              new SqlParameter("UnitId",sampleVaule.unit.HasValue ? (int)sampleVaule.unit : 0),
+                                              new SqlParameter("TransactionId",_request.transactionId),
+                                          };
+
+
+                                            _meterDb.Database.ExecuteSqlCommand(sp, parameter.ToArray());
+                                        }
+                                    }
+                                }
+
+
+                            }
+                        }
+
+
                     }
                     break;
                 case Actions.Authorize:
@@ -347,7 +381,7 @@ namespace EVCB_OCPP.WSServer.Message
                         var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString(), true);
                         var confirm = new AuthorizeConfirmation()
                         {
-                            idTagInfo = businessService.Authorize(_request.idTag)
+                            idTagInfo = businessService.Authorize(session.ChargeBoxId, _request.idTag)
                         };
                         result.Message = confirm;
                         result.Success = true;

+ 1 - 1
EVCB_OCPP.WSServer/ProtalServer.cs

@@ -110,7 +110,7 @@ namespace EVCB_OCPP.WSServer
             serverUpdateTask.Start();
 
 
-            Task serverHealthTask = new Task(HealthAlarmTrigger, _ct);
+          //  Task serverHealthTask = new Task(HealthAlarmTrigger, _ct);
            // serverHealthTask.Start();
 
             while (true)

+ 7 - 3
EVCB_OCPP.WSServer/BusinessService/BusinessServiceFactory.cs → EVCB_OCPP.WSServer/Service/BusinessServiceFactory.cs

@@ -1,16 +1,20 @@
 using EVCB_OCPP.Packet.Messages.SubTypes;
+using EVCB_OCPP.WSServer.Dto;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 
-namespace EVCB_OCPP.WSServer.BusinessService
+namespace EVCB_OCPP.WSServer.Service
 {
 
     public interface IBusinessService
     {
-        IdTagInfo Authorize(string idTag);
+        IdTagInfo Authorize(string chargeBoxId,string idTag);
+
+        void NotifyFaultStatus( ErrorDetails details);
+
     }
 
     static public class BusinessServiceFactory
@@ -19,7 +23,7 @@ namespace EVCB_OCPP.WSServer.BusinessService
         static public IBusinessService CreateBusinessService(string customerId, bool isLocalHandle)
         {
 
-            return new FakeLocalBusinessService(customerId);
+            return new OuterBusinessService(customerId);
         }
 
     }

+ 308 - 0
EVCB_OCPP.WSServer/Service/HttpClientService.cs

@@ -0,0 +1,308 @@
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.WSServer.Service
+{
+    public class HttpClientService
+    {
+        /// <summary>
+        /// 要求逾時前等候的時間長度
+        /// #網域名稱系統(DNS)查詢最多可能需要15秒的時間才會傳回或超時
+        /// 預設60秒
+        /// </summary>
+        public int Timeout { get => _timeout; set => _timeout = value; }
+
+        /// <summary>
+        /// 取得或設定使用 HttpClient 物件提出要求時,所允許的同時連線 數目上限 (每個伺服器端點)。
+        /// 請注意,此限制是按照每個伺服器端點計算,例如值 256 允許 http://www.adatum.com/ 使用 256 個同時連線,
+        /// 而 http://www.adventure-works.com/ 另有 256 個同時連線。
+        /// 預設100個
+        /// </summary>
+        public int MaxConnectionsPerServer { get => _maxConnectionsPerServer; set => _maxConnectionsPerServer = value; }
+
+
+        /// <summary>
+        /// 設定HttpMessageHandler的生命週期,如果其存留期間尚未過期,HttpMessageHandler 執行個體可從集區重複使用(建立新的 HttpClient 執行個體時)
+        /// 因為處理常式通常會管理自己專屬的底層 HTTP 連線。 建立比所需數目更多的處理常式,可能會導致連線延遲。 有些處理常式也會保持連線無限期地開啟,這可能導致處理常式無法回應 DNS (網域名稱系統)變更。
+        /// 預設處理常式存留時間為120秒。
+        /// </summary>
+        public int HandlerLifetime { get => _handlerLifetime; set => _handlerLifetime = value; }
+
+
+        private IHttpClientFactory _clientFactory = null;
+        private IServiceCollection _services = new ServiceCollection();
+        private int _handlerLifetime = 2;
+        private int _maxConnectionsPerServer = 20;
+        private int _timeout = 60;
+
+
+        public HttpClientService(string baseAddress = "")
+        {
+
+            _services.AddHttpClient("Default", c =>
+            {
+                if (!string.IsNullOrEmpty(baseAddress))
+                {
+                    c.BaseAddress = new Uri(baseAddress);
+                }
+                c.Timeout = TimeSpan.FromSeconds(_timeout);
+                c.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
+            })
+          .AddTypedClient<HttpClient>().SetHandlerLifetime(TimeSpan.FromSeconds(_handlerLifetime)).ConfigurePrimaryHttpMessageHandler((h =>
+          {
+              return new HttpClientHandler
+              {
+                  MaxConnectionsPerServer = _maxConnectionsPerServer
+
+              };
+          }));
+
+            Init();
+        }
+
+
+        private void Init()
+        {
+            _clientFactory = _services.BuildServiceProvider()
+                     .GetRequiredService<IHttpClientFactory>();
+        }
+
+
+        public virtual async Task<HttpResponse> PostJsonAsync(string Url, string bodyData, Dictionary<string, string> headers, string clientName = "Default", bool bearerToken = false, string authorizationToken = null)
+        {
+            HttpResponse result = new HttpResponse() { IsError = false };
+
+            try
+            {
+                var client = _clientFactory.CreateClient(clientName);
+
+                if (!string.IsNullOrEmpty(authorizationToken))
+                {
+                    client.DefaultRequestHeaders.Authorization = bearerToken ? new AuthenticationHeaderValue("Bearer", authorizationToken) : new AuthenticationHeaderValue(authorizationToken);
+                }
+                if (headers != null)
+                {
+                    for (int idx = 0; idx < headers.Count; idx++)
+                    {
+                        client.DefaultRequestHeaders.Add(headers.ElementAt(idx).Key, headers.ElementAt(idx).Value);
+                    }
+                }
+
+                HttpContent content = new StringContent(bodyData);
+                content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
+                content.Headers.ContentType.CharSet = "UTF-8";
+
+                var response = await client.PostAsync(Url, content).ConfigureAwait(false);
+
+                result.IsSuccessStatusCode = response.IsSuccessStatusCode;
+                result.Headers = response.Headers;
+                result.RequestMessage = response.RequestMessage;
+                result.StatusCode = response.StatusCode;
+                result.Response = await response.Content.ReadAsStringAsync();
+
+
+
+            }
+            catch (Exception ex)
+            {
+                result.IsError = true;
+                result.Exception = ex;
+
+            }
+
+
+            return result;
+        }
+
+        public virtual async Task<HttpResponse> GetJsonAsync(string Url, Dictionary<string, string> headers, string clientName = "Default", bool bearerToken = false, string authorizationToken = null)
+        {
+            HttpResponse result = new HttpResponse() { IsError = false };
+
+            try
+            {
+                var client = _clientFactory.CreateClient(clientName);
+
+                if (!string.IsNullOrEmpty(authorizationToken))
+                {
+                    client.DefaultRequestHeaders.Authorization = bearerToken ? new AuthenticationHeaderValue("Bearer", authorizationToken) : new AuthenticationHeaderValue(authorizationToken);
+                }
+
+                if (headers != null)
+                {
+                    for (int idx = 0; idx < headers.Count; idx++)
+                    {
+                        client.DefaultRequestHeaders.Add(headers.ElementAt(idx).Key, headers.ElementAt(idx).Value);
+                    }
+                }
+
+                // client.DefaultRequestHeaders.Add("Content-Type", "application/json");
+
+
+                var response = await client.GetAsync(Url).ConfigureAwait(false);
+
+                result.IsSuccessStatusCode = response.IsSuccessStatusCode;
+                result.Headers = response.Headers;
+                result.RequestMessage = response.RequestMessage;
+                result.StatusCode = response.StatusCode;
+                result.Response = await response.Content.ReadAsStringAsync();
+
+
+
+            }
+            catch (Exception ex)
+            {
+                result.IsError = true;
+                result.Exception = ex;
+
+            }
+
+
+            return result;
+        }
+
+        public virtual async Task<HttpResponse> PutJsonAsync(string Url, string bodyData, Dictionary<string, string> headers, string clientName = "Default", bool bearerToken = false, string authorizationToken = null)
+        {
+            HttpResponse result = new HttpResponse() { IsError = false };
+
+            try
+            {
+                var client = _clientFactory.CreateClient(clientName);
+
+                if (!string.IsNullOrEmpty(authorizationToken))
+                {
+                    client.DefaultRequestHeaders.Authorization = bearerToken ? new AuthenticationHeaderValue("Bearer", authorizationToken) : new AuthenticationHeaderValue(authorizationToken);
+                }
+                if (headers != null)
+                {
+                    for (int idx = 0; idx < headers.Count; idx++)
+                    {
+                        client.DefaultRequestHeaders.Add(headers.ElementAt(idx).Key, headers.ElementAt(idx).Value);
+                    }
+                }
+
+                HttpContent content = new StringContent(bodyData);
+                content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
+                content.Headers.ContentType.CharSet = "UTF-8";
+
+                var response = await client.PutAsync(Url, content).ConfigureAwait(false);
+
+                result.IsSuccessStatusCode = response.IsSuccessStatusCode;
+                result.Headers = response.Headers;
+                result.RequestMessage = response.RequestMessage;
+                result.StatusCode = response.StatusCode;
+                result.Response = await response.Content.ReadAsStringAsync();
+
+
+
+            }
+            catch (Exception ex)
+            {
+                result.IsError = true;
+                result.Exception = ex;
+
+            }
+
+
+            return result;
+        }
+
+        public virtual async Task<HttpResponse> DeleteJsonAsync(string Url, Dictionary<string, string> headers, string clientName = "Default", bool bearerToken = false, string authorizationToken = null)
+        {
+            HttpResponse result = new HttpResponse() { IsError = false };
+
+            try
+            {
+                var client = _clientFactory.CreateClient(clientName);
+
+                if (!string.IsNullOrEmpty(authorizationToken))
+                {
+                    client.DefaultRequestHeaders.Authorization = bearerToken ? new AuthenticationHeaderValue("Bearer", authorizationToken) : new AuthenticationHeaderValue(authorizationToken);
+                }
+
+                if (headers != null)
+                {
+                    for (int idx = 0; idx < headers.Count; idx++)
+                    {
+                        client.DefaultRequestHeaders.Add(headers.ElementAt(idx).Key, headers.ElementAt(idx).Value);
+                    }
+                }
+
+                //   client.DefaultRequestHeaders.Add("Content-Type", "application/json");
+
+
+                var response = await client.DeleteAsync(Url).ConfigureAwait(false);
+
+                result.IsSuccessStatusCode = response.IsSuccessStatusCode;
+                result.Headers = response.Headers;
+                result.RequestMessage = response.RequestMessage;
+                result.StatusCode = response.StatusCode;
+                result.Response = await response.Content.ReadAsStringAsync();
+
+
+
+            }
+            catch (Exception ex)
+            {
+                result.IsError = true;
+                result.Exception = ex;
+
+            }
+
+
+            return result;
+        }
+
+    }
+
+
+    public class HttpResponse
+    {
+        public bool IsError { internal set; get; }
+
+        public Exception Exception { internal set; get; }
+
+        public string Response { internal set; get; }
+
+        /// <summary>
+        /// 摘要:
+        ///     取得或設定 HTTP 回應的狀態碼。
+        /// 傳回:
+        ///    HTTP 回應的狀態碼。
+        /// </summary>
+        public HttpStatusCode StatusCode { get; internal set; }
+
+
+        /// <summary>
+        /// 摘要:
+        ///      取得 HTTP 回應標頭的集合。
+        /// 傳回:
+        ///     HTTP 回應標頭的集合。
+        /// </summary>
+        public HttpResponseHeaders Headers { get; internal set; }
+
+
+        /// <summary>
+        /// 摘要:
+        ///     取得或設定導致此回應訊息的要求訊息。
+        /// 傳回:
+        ///       導致此回應訊息的要求訊息。
+        /// </summary>
+        public HttpRequestMessage RequestMessage { get; internal set; }
+
+        /// <summary>
+        /// 摘要:
+        ///   取得指示 HTTP 回應是否成功的值。
+        /// 傳回:
+        ///       指示 HTTP 回應是否成功的值。 如果 System.Net.Http.HttpResponseMessage.StatusCode 在 200-299
+        ///     的範圍內,則為 true;否則為 false。
+        /// </summary>
+        public bool IsSuccessStatusCode { get; internal set; }
+    }
+}

+ 9 - 2
EVCB_OCPP.WSServer/BusinessService/LocalBusinessService.cs → EVCB_OCPP.WSServer/Service/LocalBusinessService.cs

@@ -4,8 +4,9 @@ using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using EVCB_OCPP.Packet.Messages.SubTypes;
+using EVCB_OCPP.WSServer.Dto;
 
-namespace EVCB_OCPP.WSServer.BusinessService
+namespace EVCB_OCPP.WSServer.Service
 {
     public class LocalBusinessService : IBusinessService
     {
@@ -19,11 +20,17 @@ namespace EVCB_OCPP.WSServer.BusinessService
             this.customerId = customerId;
         }
 
-        public IdTagInfo Authorize(string idTag)
+        public IdTagInfo Authorize(string chargeBoxId, string idTag)
         {
 
             return new IdTagInfo() { status = AuthorizationStatus.Accepted };
 
         }
+
+     
+        public void NotifyFaultStatus(ErrorDetails details)
+        {
+            
+        }
     }
 }

+ 144 - 0
EVCB_OCPP.WSServer/Service/OuterBusinessService.cs

@@ -0,0 +1,144 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using EVCB_OCPP.Domain;
+using EVCB_OCPP.Packet.Messages.SubTypes;
+using EVCB_OCPP.WSServer.Dto;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using NLog;
+
+namespace EVCB_OCPP.WSServer.Service
+{
+    internal class CPOOuterResponse
+    {
+        public CPOOuterResponse()
+        {
+            StatusCode = 0;
+
+        }
+
+        public int StatusCode { set; get; }
+
+        public string StatusMessage { set; get; }
+
+        public string Data { set; get; }
+
+        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
+        public string SerialNo { set; get; }
+
+
+        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
+        public string ErrorDetail { set; get; }
+
+
+    }
+    internal class CustomerSignMaterial
+    {
+        internal bool CallsThirdParty { set; get; }
+
+        internal string Id { set; get; }
+
+        internal string APIUrl { set; get; }
+
+        internal string SaltKey { set; get; }
+    }
+    public class OuterBusinessService : IBusinessService
+    {
+        static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
+        private OuterHttpClient httpClient = new OuterHttpClient();
+        private CustomerSignMaterial signMaterial = null;
+
+        public OuterBusinessService(string customerId)
+        {
+            signMaterial = GetSign(customerId);
+        }
+
+        public IdTagInfo Authorize(string chargeBoxId, string idTag)
+        {
+            IdTagInfo result = new IdTagInfo() { status = AuthorizationStatus.Invalid };
+            try
+            {
+                string requestParams = string.Format("charging_auth?chargeBoxId={0}&IdTag={1}", chargeBoxId, idTag);
+
+                var response = httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
+                            {
+                                { "PartnerId",signMaterial.Id}
+
+                            }, null, signMaterial.SaltKey).GetAwaiter().GetResult();
+
+                if (response.Success)
+                {
+                    var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
+                    JObject jo = JObject.Parse(_httpResult.Data);
+
+                    if (jo.ContainsKey("ExpiryDate"))
+                    {
+                        DateTime dt = jo["ExpiryDate"].Value<DateTime>();
+                        result.expiryDate = dt;
+                    }
+
+
+                    if (jo.ContainsKey("Status"))
+                    {
+                        string _Message = jo["Status"].Value<string>();
+                        result.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), _Message);
+                    }
+                }
+
+            }
+            catch (Exception ex)
+            {
+                result.status = AuthorizationStatus.Invalid;
+
+                logger.Error(chargeBoxId + " OuterBusinessService.Authorize Ex: " + ex.ToString());
+            }
+
+            return result;
+
+        }
+
+        public void NotifyFaultStatus(ErrorDetails details)
+        {
+
+            try
+            {
+                if(signMaterial.CallsThirdParty)
+                {
+                    var response = httpClient.Post(signMaterial.APIUrl + "connectorfault", new Dictionary<string, string>()
+                            {
+                                { "PartnerId",signMaterial.Id}
+
+                            }, JsonConvert.SerializeObject(details, GlobalConfig.JSONSERIALIZER_FORMAT), signMaterial.SaltKey).GetAwaiter().GetResult();
+
+
+                }
+
+
+            }
+            catch (Exception ex)
+            {
+
+                logger.Error(details.ChargeBoxId + " OuterBusinessService.NotifyFaultStatus Ex: " + ex.ToString());
+            }
+
+
+        }
+
+
+        private CustomerSignMaterial GetSign(string customerId)
+        {
+            Guid Id = new Guid(customerId);
+            CustomerSignMaterial _customer = new CustomerSignMaterial();
+
+
+            using (var db = new MainDBContext())
+            {
+                _customer = db.Customer.Where(x => x.Id == Id).Select(x => new CustomerSignMaterial() { Id = x.Id.ToString(), APIUrl = x.ApiUrl, SaltKey = x.ApiKey, CallsThirdParty = x.CallPartnerApiOnSchedule }).FirstOrDefault();
+            }
+            return _customer;
+        }
+    }
+}

+ 163 - 0
EVCB_OCPP.WSServer/Service/OuterHttpClient.cs

@@ -0,0 +1,163 @@
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.WSServer.Service
+{
+    public class OuterHttpClient
+    {
+        private HttpClientService httpClient = new HttpClientService();
+
+        async public Task<HttpResult> Post(string url, Dictionary<string, string> headers, object requestBody, string saltkey)
+        {
+            HttpResult result = new HttpResult() { Success = false };
+
+            try
+            {
+                string body = PreAction(url, ref headers, requestBody, saltkey);
+                var _response = await httpClient.PostJsonAsync(url, body, headers);
+
+                result.Response = _response.Response;
+                result.Status = _response.StatusCode;
+                result.Success = _response.IsSuccessStatusCode;
+                result.Exception = _response.Exception;
+
+
+            }
+            catch (Exception ex)
+            {
+                result.Exception = ex;
+            }
+
+            return result;
+        }
+
+        async public Task<HttpResult> Get(string url, Dictionary<string, string> headers, string saltkey)
+        {
+
+            HttpResult result = new HttpResult() { Success = false };
+
+            try
+            {
+                string body = PreAction(url, ref headers, null, saltkey);
+                var _response = await httpClient.GetJsonAsync(url, headers);
+                result.Response = _response.Response;
+                result.Status = _response.StatusCode;
+                result.Success = _response.IsSuccessStatusCode;
+                result.Exception = _response.Exception;
+
+
+
+            }
+            catch (Exception ex)
+            {
+                result.Exception = ex;
+            }
+
+            return result;
+        }
+
+        async public Task<HttpResult> Delete(string url, Dictionary<string, string> headers, string saltkey)
+        {
+            HttpResult result = new HttpResult() { Success = false };
+
+            try
+            {
+                string body = PreAction(url, ref headers, null, saltkey);
+                var _response = await httpClient.DeleteJsonAsync(url, headers);
+                result.Response = _response.Response;
+                result.Status = _response.StatusCode;
+                result.Success = _response.IsSuccessStatusCode;
+                result.Exception = _response.Exception;
+
+
+            }
+            catch (Exception ex)
+            {
+                result.Exception = ex;
+            }
+
+            return result;
+        }
+
+        async public Task<HttpResult> Put(string url, Dictionary<string, string> headers, object requestBody, string saltkey)
+        {
+            HttpResult result = new HttpResult() { Success = false };
+
+            try
+            {
+                string body = PreAction(url, ref headers, requestBody, saltkey);
+                var _response = await httpClient.PutJsonAsync(url, body, headers);
+                result.Response = _response.Response;
+                result.Status = _response.StatusCode;
+                result.Success = _response.IsSuccessStatusCode;
+                result.Exception = _response.Exception;
+
+
+            }
+            catch (Exception ex)
+            {
+                result.Exception = ex;
+            }
+
+            return result;
+        }
+
+        private string PreAction(string url, ref Dictionary<string, string> headers, object requestBody, string saltkey)
+        {
+            var _body = requestBody == null ? "" : JsonConvert.SerializeObject(requestBody, GlobalConfig.JSONSERIALIZER_FORMAT);
+            headers.Add("Timestamp", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString());
+            string signature = GetSignature(GetUnencodeText(url, _body, headers["Timestamp"], headers["PartnerId"], saltkey));
+            headers.Add("Signature", signature);
+
+            return _body;
+        }
+
+
+        private string GetUnencodeText(string url, string body, string timestamp, string partnerId, string saltkey)
+        {
+
+            string tempText = url.Substring(url.IndexOf('?') + 1).ToLower();
+            tempText = tempText.StartsWith("http") ? string.Empty : tempText;
+            body = tempText + body;
+            string unencodeText = string.Format("{0}{1}{2}{3}", body, timestamp, partnerId, saltkey).ToLower();
+
+            return unencodeText;
+        }
+
+        private string GetSignature(string unencodeText)
+        {
+            if ((unencodeText == null) || (unencodeText.Length == 0))
+            {
+                return String.Empty;
+            }
+            unencodeText = unencodeText.ToLower();
+
+            MD5 md5 = new MD5CryptoServiceProvider();
+            byte[] textToHash = Encoding.UTF8.GetBytes(unencodeText);
+            byte[] result = md5.ComputeHash(textToHash);
+            return BitConverter.ToString(result).Replace("-", "").ToLower();
+        }
+
+    }
+
+    public class HttpResult
+    {
+        public int StatusCode { set; get; }
+
+        public bool Success { set; get; }
+
+        public HttpStatusCode Status { set; get; }
+
+        public Exception Exception { set; get; }
+
+        public string Response { set; get; }
+
+    }
+
+}

+ 9 - 15
EVCB_OCPP.WSServer/SuperSocket.Protocol/OCPPWSServer.cs

@@ -68,31 +68,25 @@ namespace OCPPServer.Protocol
             using (var db = new MainDBContext())
             {
                 var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
-               
-
+                session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
                 isExistedSN = machine == null ? false : true;
             }
             if (!isExistedSN)
             {
-
-
-
-
                 StringBuilder responseBuilder = new StringBuilder();
 
-                responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}","1.1",
-                (int)HttpStatusCode.NotFound, @"Not Found");           
+                responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1",
+                (int)HttpStatusCode.NotFound, @"Not Found");
+
+                responseBuilder.AppendWithCrCf();
+                string sb = responseBuilder.ToString();
+                byte[] data = Encoding.UTF8.GetBytes(sb);
 
-                 responseBuilder.AppendWithCrCf();
-                 string sb = responseBuilder.ToString();
-                 byte[] data = Encoding.UTF8.GetBytes(sb);
-                
-                ((IWebSocketSession)session).SendRawData(data,0,data.Length);
+                ((IWebSocketSession)session).SendRawData(data, 0, data.Length);
 
                 return false;
             }
-
-
+          
 
             return true;
         }

+ 17 - 0
EVCB_OCPP.WSServer/packages.config

@@ -2,8 +2,25 @@
 <packages>
   <package id="EntityFramework" version="6.2.0" targetFramework="net471" />
   <package id="log4net" version="2.0.3" targetFramework="net471" />
+  <package id="Microsoft.Bcl.AsyncInterfaces" version="1.1.0" targetFramework="net471" />
+  <package id="Microsoft.Extensions.Configuration" version="3.1.2" targetFramework="net471" />
+  <package id="Microsoft.Extensions.Configuration.Abstractions" version="3.1.2" targetFramework="net471" />
+  <package id="Microsoft.Extensions.Configuration.Binder" version="3.1.2" targetFramework="net471" />
+  <package id="Microsoft.Extensions.DependencyInjection" version="3.1.2" targetFramework="net471" />
+  <package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="3.1.2" targetFramework="net471" />
+  <package id="Microsoft.Extensions.Http" version="3.1.2" targetFramework="net471" />
+  <package id="Microsoft.Extensions.Logging" version="3.1.2" targetFramework="net471" />
+  <package id="Microsoft.Extensions.Logging.Abstractions" version="3.1.2" targetFramework="net471" />
+  <package id="Microsoft.Extensions.Options" version="3.1.2" targetFramework="net471" />
+  <package id="Microsoft.Extensions.Primitives" version="3.1.2" targetFramework="net471" />
   <package id="Newtonsoft.Json" version="12.0.1" targetFramework="net471" />
   <package id="NLog" version="4.6.6" targetFramework="net471" />
   <package id="NLog.Config" version="4.6.6" targetFramework="net471" />
   <package id="NLog.Schema" version="4.6.6" targetFramework="net471" />
+  <package id="System.Buffers" version="4.4.0" targetFramework="net471" />
+  <package id="System.ComponentModel.Annotations" version="4.7.0" targetFramework="net471" />
+  <package id="System.Memory" version="4.5.2" targetFramework="net471" />
+  <package id="System.Numerics.Vectors" version="4.4.0" targetFramework="net471" />
+  <package id="System.Runtime.CompilerServices.Unsafe" version="4.7.0" targetFramework="net471" />
+  <package id="System.Threading.Tasks.Extensions" version="4.5.2" targetFramework="net471" />
 </packages>