浏览代码

1. 加入 連接Portal Auth 功能
2. 拿掉 ocpp2.0

Jessica Tseng 4 年之前
父节点
当前提交
f9c1340016

+ 3 - 7
EVCB_OCPP.WSServer/App.config

@@ -7,20 +7,16 @@
     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
   </configSections>
    <connectionStrings>
-    <!--<add name="ConnectionLogDBContext" connectionString="data source=172.1.0.142\SQLEXPRESS;initial catalog=OCPP_ConnectionLogDBContext;persist security info=True;user id=sa;password=Ph0930118811;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
-    <add name="MainDBContext" connectionString="data source=172.1.0.142\SQLEXPRESS;initial catalog=OCPP_MainDBContext;;persist security info=True;user id=sa;password=Ph0930118811;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
-    <add name="MeterValueDBContext" connectionString="data source=172.1.0.142\SQLEXPRESS;initial catalog=OCPP_MeterValueDBContext;;persist security info=True;user id=sa;password=Ph0930118811;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />-->
    <add name="ConnectionLogDBContext" connectionString="data source=172.1.2.187,1434\SQLEXPRESS2017;initial catalog=StandardOCPP_ConnectionLog;persist security info=True;user id=sa;password=Ph0930118811;MultipleActiveResultSets=True;App=EntityFramework; Max Pool Size=500" providerName="System.Data.SqlClient" />
    <add name="MainDBContext" connectionString="data source=172.1.2.187\SQLEXPRESS2017;initial catalog=StandardOCPP_Main;persist security info=True;user id=sa;password=Ph0930118811;MultipleActiveResultSets=True;App=EntityFramework; Max Pool Size=500" providerName="System.Data.SqlClient" />
    <add name="MeterValueDBContext" connectionString="data source=172.1.2.187\SQLEXPRESS2017;initial catalog=StandardOCPP_MeterValue;persist security info=True;user id=sa;password=Ph0930118811;MultipleActiveResultSets=True;App=EntityFramework; Max Pool Size=500" providerName="System.Data.SqlClient" />
    <add name="WebDBContext" connectionString="data source=172.1.2.187\SQLEXPRESS2017;initial catalog=StandardOCPP_Web;persist security info=True;user id=sa;password=Ph0930118811;MultipleActiveResultSets=True;App=EntityFramework; Max Pool Size=500" providerName="System.Data.SqlClient" />
 
    </connectionStrings>
-  <appSettings>
-    <add key="ServerIP" value="" />
+  <appSettings>   
+     <add key="LocalAuthAPI" value="http://172.1.2.187/PortalApi/1" />
     <add key="WSPort" value="8080" />
-    <add key="WSSPort" value="2013" />
-  
+    <add key="WSSPort" value="2013" />  
   </appSettings>
   <startup>
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" />

+ 1 - 4
EVCB_OCPP.WSServer/GlobalConfig.cs

@@ -23,10 +23,7 @@ namespace EVCB_OCPP.WSServer
         /// </summary>
         private static int DEFAULT_HEARTBEAT_INTERVAL = 15;
 
-        /// <summary>
-        ///Server IP
-        /// </summary>
-        private static string ServerIP = "127.0.0.1";
+   
 
         /// <summary>
         ///WS Port

+ 3 - 4
EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs

@@ -267,8 +267,7 @@ namespace EVCB_OCPP.WSServer.Message
                             int _transactionId = -1;
 
                             var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
-                            var _idTagInfo = _request.idTag == "Backend" ? new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted } : await businessService.Authorize(session.ChargeBoxId, _request.idTag);
-
+                            var _idTagInfo = new IdTagInfo() { status = AuthorizationStatus.Accepted };                        
 
                             using (var db = new MainDBContext())
                             {
@@ -331,7 +330,7 @@ namespace EVCB_OCPP.WSServer.Message
                             int _ConnectorId = 0;
 
                             var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
-                            var _idTagInfo = _request.idTag == "Backend" ? new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted } : await businessService.Authorize(session.ChargeBoxId, _request.idTag);
+                            var _idTagInfo =  new IdTagInfo() {  status = AuthorizationStatus.Accepted };
 
 
                             using (var db = new MainDBContext())
@@ -731,7 +730,7 @@ namespace EVCB_OCPP.WSServer.Message
                             db.SaveChanges();
 
                         }
-                       
+
                     }
                     break;
                 case Actions.UnlockConnector:

+ 1 - 1
EVCB_OCPP.WSServer/ProtalServer.cs

@@ -308,7 +308,7 @@ namespace EVCB_OCPP.WSServer
         {
 
             //載入OCPP Protocol
-            var appServer = new OCPPWSServer(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6"), new OCPPSubProtocol("ocpp2.0"), new OCPPSubProtocol(" ocpp2.0") });
+            var appServer = new OCPPWSServer(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6")});
 
             List<IListenerConfig> llistener = new List<IListenerConfig>();
             //System.Net.IPAddress.Any.ToString()

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

@@ -262,6 +262,61 @@ namespace EVCB_OCPP.WSServer.Service
             return result;
         }
 
+        public virtual async Task<HttpResponse> PostFormDataAsync(string Url, Dictionary<string, 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);
+
+                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
+
+                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);
+                    }
+                }
+
+                var content = new MultipartFormDataContent();
+
+                foreach (var keyValuePair in bodyData)
+                {
+                    content.Add(new StringContent(keyValuePair.Value), "\"" + keyValuePair.Key + "\"");
+                }
+
+                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;
+        }
+
+
+
     }
 
 

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

@@ -1,10 +1,13 @@
 using System;
 using System.Collections.Generic;
+using System.Configuration;
 using System.Linq;
+using System.Net;
 using System.Text;
 using System.Threading.Tasks;
 using EVCB_OCPP.Packet.Messages.SubTypes;
 using EVCB_OCPP.WSServer.Dto;
+using Newtonsoft.Json.Linq;
 
 namespace EVCB_OCPP.WSServer.Service
 {
@@ -21,7 +24,53 @@ namespace EVCB_OCPP.WSServer.Service
         async public Task<IdTagInfo> Authorize(string chargeBoxId, string idTag)
         {
             await Task.Delay(10);
-            return new IdTagInfo() { status = AuthorizationStatus.Accepted };
+            IdTagInfo info = new IdTagInfo() { status = AuthorizationStatus.Invalid };
+            try
+            {
+
+                OuterHttpClient _client = new OuterHttpClient();
+
+
+                string url = ConfigurationManager.AppSettings["LocalAuthAPI"];
+
+
+                HttpClientService service = new HttpClientService();
+
+                Dictionary<string, string> postData = new Dictionary<string, string>()
+                {
+                  { "ChargeBoxId", chargeBoxId },
+                  { "IdTag", idTag },
+
+
+                };
+                var _innerresult = await service.PostFormDataAsync(url, postData, null);
+
+
+                if (_innerresult.StatusCode == HttpStatusCode.OK)
+                {
+                    JObject jo = JObject.Parse(_innerresult.Response);
+                    if (jo["code"].ToString() == "1")
+                    {
+                        try
+                        {
+                            info.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), jo["message"].ToString());
+                        }
+                        catch(Exception)
+                        {
+                            ;
+                        }
+
+                     
+                    }
+                 
+                }
+              
+            }
+            catch (Exception ex)
+            {
+                ;
+            }
+            return info;
 
         }
 

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

@@ -37,6 +37,33 @@ namespace EVCB_OCPP.WSServer.Service
             return result;
         }
 
+
+        async public Task<HttpResult> PostFormDataAsync(string url, Dictionary<string, string> bodyData, Dictionary<string, string> headers, string clientName = "Default", bool bearerToken = false, string authorizationToken = null)
+        {
+            HttpResult result = new HttpResult() { Success = false };
+
+            try
+            {
+               
+                var _response = await httpClient.PostFormDataAsync(url, bodyData, null);
+
+                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)
         {
 

+ 1 - 1
SuperWebSocket/WebSocketSession.cs

@@ -225,7 +225,7 @@ namespace SuperWebSocket
 
         string IWebSocketSession.GetAvailableSubProtocol(string protocol)
         {
-            protocol = "ocpp1.6, ocpp2.0";
+            
             if (string.IsNullOrEmpty(protocol))
             {
                 SubProtocol = AppServer.DefaultSubProtocol;