瀏覽代碼

1. 資料庫版本 70179e
2. 新增UserPrice AC/DC 費率 須結合 Customer InstantStopReport 使用
3.StopTransaction StopReason 填寫兩個欄位 原有的StopReasonId & StopReason文字

Jessica Tseng 3 年之前
父節點
當前提交
3ae218b592

二進制
EVCB_OCPP.WSServer/DLL/EVCB_OCPP.Domain.dll


二進制
EVCB_OCPP.WSServer/DLL/EVCB_OCPP.Packet.dll


+ 38 - 0
EVCB_OCPP.WSServer/Dto/IdTokenInfo.cs

@@ -0,0 +1,38 @@
+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 IdTokenInfo
+    {
+
+        public IdTagInfo IdTagInfo { set; get; }
+
+        public decimal AccountBalance { set; get; }
+
+        public List<ChargePointFee> ChargePointFee { set; get; }
+    }
+
+
+    public class ChargePointFee
+    {
+        public bool IsAC { set; get; }       
+
+
+        public decimal? PerkWhFee { set; get; }
+
+        public decimal? PerHourFee { set; get; }
+
+
+        public decimal ParkingFee { set; get; }
+
+        public string Currency { set; get; }
+
+
+        public string DisplayMessage { set; get; }
+    }
+}

+ 1 - 0
EVCB_OCPP.WSServer/EVCB_OCPP.WSServer.csproj

@@ -133,6 +133,7 @@
   <ItemGroup>
     <Compile Include="Dto\ChargingPrice.cs" />
     <Compile Include="Dto\ErrorDetails.cs" />
+    <Compile Include="Dto\IdTokenInfo.cs" />
     <Compile Include="Dto\ID_GetTxUserInfo.cs" />
     <Compile Include="Dto\StationFee.cs" />
     <Compile Include="Dto\TCCWeatherDto.cs" />

+ 163 - 35
EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs

@@ -8,6 +8,7 @@ using EVCB_OCPP.Packet.Messages.SubTypes;
 using EVCB_OCPP.WSServer.Dto;
 using EVCB_OCPP.WSServer.Service;
 using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
 using NLog;
 using OCPPPackage.Profiles;
 using OCPPServer.Protocol;
@@ -102,7 +103,7 @@ namespace EVCB_OCPP.WSServer.Message
                                         TotalCost = creditDeductResult.amount,
 
                                     };
-                               
+
                                     var response = await httpClient.Post(GlobalConfig.TCC_API_URL + "prepare_issue_invoice", new Dictionary<string, string>()
                                         {
                                             { "PartnerId",session.CustomerId.ToString()}
@@ -441,7 +442,36 @@ 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() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
+                            if (_request.idTag != "Backend")
+                            {
+                                var authorization_result = await businessService.Authorize(session.ChargeBoxId, _request.idTag);
+                                _idTagInfo = authorization_result.IdTagInfo;
+
+                                if (authorization_result.ChargePointFee != null)
+                                {
+                                    var price = authorization_result.ChargePointFee.Where(x => x.IsAC == session.IsAC).First();
+                                    if (price != null)
+                                    {
+
+                                        if (session.UserPrices.ContainsKey(_request.idTag))
+                                        {
+                                            session.UserPrices[_request.idTag] = price.PerkWhFee.HasValue ? JsonConvert.SerializeObject(new List<ChargingPrice>() { new ChargingPrice() { StartTime = "00:00", EndTime = "23:59", Fee = price.PerkWhFee.Value } }) : price.PerHourFee.Value.ToString();
+                                            session.UserPrices[_request.idTag] += "|+" + authorization_result.AccountBalance + "+" + "&" + price.ParkingFee + "&|" + price.Currency;
+
+                                        }
+                                        else
+                                        {
+                                            session.UserPrices.Add(_request.idTag, price.PerkWhFee.HasValue ? JsonConvert.SerializeObject(new List<ChargingPrice>() { new ChargingPrice() { StartTime = "00:00", EndTime = "23:59", Fee = price.PerkWhFee.Value } }) : price.PerHourFee.Value.ToString());
+                                            session.UserPrices[_request.idTag] += "|+" + authorization_result.AccountBalance + "+" + "&" + price.ParkingFee + "&|" + price.Currency;
+
+                                        }
+                                    }
+                                }
+                            
+                            }
+
                             //特例****飛宏客戶旗下的電樁,若遇到Portal沒回應的狀況 ~允許充電
                             if (session.CustomerId.ToString().ToUpper() == "8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7" && _idTagInfo.status == AuthorizationStatus.ConcurrentTx)
                             {
@@ -482,11 +512,20 @@ namespace EVCB_OCPP.WSServer.Message
                                         MeterStart = _request.meterStart,
                                         CustomerId = _CustomerId,
                                         StartTime = _request.timestamp.ToUniversalTime(),
-                                        ReservationId = _request.reservationId.HasValue ? _request.reservationId.Value : 0,                                    
+                                        ReservationId = _request.reservationId.HasValue ? _request.reservationId.Value : 0,
                                     };
 
-                                    _newTransaction.Fee = !session.IsBilling ? string.Empty : session.BillingMethod == 1 ? JsonConvert.SerializeObject(session.ChargingPrices) : session.ChargingFeebyHour.ToString();
-                                    _newTransaction.Fee += !session.IsBilling ? string.Empty :"|+" + accountBalance + "+" + "&" + session.ParkingFee + "&|" + session.Currency;
+                                    if (session.UserPrices.ContainsKey(_request.idTag))
+                                    {
+                                        _newTransaction.Fee = !session.IsBilling ? string.Empty : session.UserPrices[_request.idTag];
+
+                                    }
+                                    else
+                                    {
+                                        _newTransaction.Fee = !session.IsBilling ? string.Empty : session.BillingMethod == 1 ? JsonConvert.SerializeObject(session.ChargingPrices) : session.ChargingFeebyHour.ToString();
+                                        _newTransaction.Fee += !session.IsBilling ? string.Empty : "|+" + accountBalance + "+" + "&" + session.ParkingFee + "&|" + session.Currency;
+                                    }
+
                                     db.TransactionRecord.Add(_newTransaction);
 
                                     db.SaveChanges();
@@ -523,16 +562,15 @@ namespace EVCB_OCPP.WSServer.Message
 
                             var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
 
-                            //特例****飛宏客戶旗下的電樁,若遇到Portal沒回應的狀況 ~允許充電
-                            var _idTagInfo = string.IsNullOrEmpty(_request.idTag) ? null : (_request.idTag == "Backend" ? new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted } : await businessService.Authorize(session.ChargeBoxId, _request.idTag));
+                            var _idTagInfo = string.IsNullOrEmpty(_request.idTag) ? null : (_request.idTag == "Backend" ?
+                                new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted } : (await businessService.Authorize(session.ChargeBoxId, _request.idTag)).IdTagInfo);
 
+                            //特例****飛宏客戶旗下的電樁,若遇到Portal沒回應的狀況 ~允許充電
                             if (session.CustomerId.ToString().ToUpper() == "8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7" && _idTagInfo != null && _idTagInfo.status == AuthorizationStatus.ConcurrentTx)
                             {
                                 _idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
                             }
 
-
-
                             using (var db = new MainDBContext())
                             {
                                 var transaction = db.TransactionRecord.Where(x => x.Id == _request.transactionId
@@ -562,6 +600,7 @@ namespace EVCB_OCPP.WSServer.Message
                                     transaction.MeterStop = _request.meterStop;
                                     transaction.StopTime = _request.timestamp.ToUniversalTime();
                                     transaction.StopReasonId = _request.reason.HasValue ? (int)_request.reason.Value : 0;
+                                    transaction.StopReason = _request.reason.HasValue ? _request.reason.Value.ToString() : Reason.Local.ToString();
                                     transaction.StopIdTag = _request.idTag;
                                     transaction.Receipt = string.Empty;
                                     transaction.Cost = session.IsBilling ? -1 : 0;
@@ -610,6 +649,8 @@ namespace EVCB_OCPP.WSServer.Message
                                 }
                             }
 
+                            #region Save MeterValue
+
                             if (_request.transactionData != null)
                             {
                                 if (_request.transactionData.Count > 0)
@@ -650,6 +691,7 @@ namespace EVCB_OCPP.WSServer.Message
                                 }
                             }
 
+                            #endregion
 
                         }
                         break;
@@ -657,14 +699,48 @@ namespace EVCB_OCPP.WSServer.Message
                         {
                             AuthorizeRequest _request = request as AuthorizeRequest;
 
-
-                            //特例****飛宏客戶旗下的電樁,若遇到Portal沒回應的狀況 ~允許充電
                             var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
                             var confirm = new AuthorizeConfirmation()
                             {
-                                idTagInfo = _request.idTag == "Backend" ? new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted } : await businessService.Authorize(session.ChargeBoxId, _request.idTag)
+                                idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted }
                             };
+                            if (_request.idTag != "Backend")
+                            {
+                                var authorization_result = await businessService.Authorize(session.ChargeBoxId, _request.idTag);
+                                confirm.idTagInfo = authorization_result.IdTagInfo;
+
+                                if(authorization_result.ChargePointFee!=null)
+                                {
+                                    var price = authorization_result.ChargePointFee.Where(x => x.IsAC == session.IsAC).First();
+                                    if (price != null)
+                                    {
+
+                                        if (session.UserPrices.ContainsKey(_request.idTag))
+                                        {
+                                            session.UserPrices[_request.idTag] = price.PerkWhFee.HasValue ? JsonConvert.SerializeObject(new List<ChargingPrice>() { new ChargingPrice() { StartTime = "00:00", EndTime = "23:59", Fee = price.PerkWhFee.Value } }) : price.PerHourFee.Value.ToString();
+                                            session.UserPrices[_request.idTag] += "|+" + authorization_result.AccountBalance + "+" + "&" + price.ParkingFee + "&|" + price.Currency;
 
+                                        }
+                                        else
+                                        {
+                                            session.UserPrices.Add(_request.idTag, price.PerkWhFee.HasValue ? JsonConvert.SerializeObject(new List<ChargingPrice>() { new ChargingPrice() { StartTime = "00:00", EndTime = "23:59", Fee = price.PerkWhFee.Value } }) : price.PerHourFee.Value.ToString());
+                                            session.UserPrices[_request.idTag] += "|+" + authorization_result.AccountBalance + "+" + "&" + price.ParkingFee + "&|" + price.Currency;
+
+                                        }
+
+                                        if (session.UserDisplayPrices.ContainsKey(_request.idTag))
+                                        {
+                                            session.UserDisplayPrices[_request.idTag] = price.DisplayMessage;
+                                        }
+                                        else
+                                        {
+                                            session.UserDisplayPrices.Add(_request.idTag, price.DisplayMessage);
+                                        }
+                                    }
+                                }
+                               
+                            }
+                            //特例****飛宏客戶旗下的電樁,若遇到Portal沒回應的狀況 ~允許充電
                             if (session.CustomerId.ToString().ToUpper() == "8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7" && confirm.idTagInfo.status == AuthorizationStatus.ConcurrentTx)
                             {
                                 confirm.idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
@@ -701,7 +777,7 @@ namespace EVCB_OCPP.WSServer.Message
             return result;
         }
 
-        internal MessageResult ExecuteCoreConfirm(Actions action, ClientData session, IConfirmation confirm, string requestId)
+        async internal Task<MessageResult> ExecuteCoreConfirm(Actions action, ClientData session, IConfirmation confirm, string requestId)
         {
             MessageResult result = new MessageResult() { Success = true };
 
@@ -724,7 +800,7 @@ namespace EVCB_OCPP.WSServer.Message
                                     operation.Status = 1;//電樁有回覆
                                     operation.EVSE_Status = (int)_confirm.status;
                                     operation.EVSE_Value = string.IsNullOrEmpty(_confirm.data) ? "" : _confirm.data;
-                                    db.SaveChanges();
+                                    await db.SaveChangesAsync();
                                 }
 
                                 if (_request.messageId == "ID_FirmwareVersion")
@@ -737,14 +813,15 @@ namespace EVCB_OCPP.WSServer.Message
                                         db.Machine.Attach(machine);
                                         machine.BoardVersions = _confirm.data;
                                         db.Entry(machine).Property(x => x.BoardVersions).IsModified = true;
-                                        db.SaveChanges();
+                                        await db.SaveChangesAsync();
                                     }
                                 }
 
-                                if (_request.messageId == "ID_TxEnergy")
+                                if (_request.messageId == "ID_TxEnergy") //計費
                                 {
                                     if (_confirm.status == DataTransferStatus.Accepted)
                                     {
+                                        decimal couponPoint = 0m;
                                         string receipt = string.Empty;
                                         List<ChargingBill> bill = new List<ChargingBill>();
                                         List<ChargingPrice> chargingPrices = new List<ChargingPrice>();
@@ -828,7 +905,7 @@ namespace EVCB_OCPP.WSServer.Message
 
                                         // 計算停車費
                                         var parkingFee = decimal.Parse(feedto.Fee.Split('&')[1]);
-                                        var stoptime = feedto.StopTime==GlobalConfig.DefaultNullTime ? DateTime.Parse(DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm")) : DateTime.Parse(feedto.StopTime.ToString("yyyy/MM/dd HH:mm"));
+                                        var stoptime = feedto.StopTime == GlobalConfig.DefaultNullTime ? DateTime.Parse(DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm")) : DateTime.Parse(feedto.StopTime.ToString("yyyy/MM/dd HH:mm"));
                                         var starttime = DateTime.Parse(feedto.StartTime.ToString("yyyy/MM/dd HH:mm"));
                                         var totalHours = stoptime.Subtract(starttime).TotalHours;
                                         var parkingCost = Decimal.Multiply((decimal)totalHours, parkingFee);
@@ -836,6 +913,8 @@ namespace EVCB_OCPP.WSServer.Message
 
                                         if (feedto.StopTime != GlobalConfig.DefaultNullTime)
                                         {
+                                            var customerInfo = db.Customer.Where(x => x.Id == session.CustomerId).Select(x => new { x.InstantStopTxReport, x.ApiUrl, x.ApiKey }).FirstOrDefault();
+
                                             decimal accountBalance = 0;
                                             decimal.TryParse(feedto.Fee.Split('+')[1], out accountBalance);
 
@@ -845,7 +924,10 @@ namespace EVCB_OCPP.WSServer.Message
                                                 Console.WriteLine("Tx is empty");
                                                 return result;
                                             }
-                                            if (tx.UploadedtoTTIA) return result;
+
+                                            if (tx.BillingDone) return result;
+
+
                                             var startTime = new DateTime(tx.StartTime.Year, tx.StartTime.Month, tx.StartTime.Day, tx.StartTime.Hour, 0, 0);
                                             List<ChargingBill> confirmbill = new List<ChargingBill>();
                                             receipt = string.Format("({0} )Energy:", chargedEnergy);
@@ -919,14 +1001,57 @@ namespace EVCB_OCPP.WSServer.Message
                                                 tx.Cost = chargingCost + parkingCost;
                                             }
 
+
+                                            if (customerInfo != null && customerInfo.InstantStopTxReport)
+                                            {
+
+                                                var request = new
+                                                {
+                                                    ChargeBoxId = tx.ChargeBoxId,
+                                                    ConnectorId = tx.ConnectorId,
+                                                    SessionId = tx.Id,
+                                                    MeterStart = tx.MeterStart,
+                                                    MeterStop = tx.MeterStop,
+                                                    IdTag = tx.StartIdTag,
+                                                    StartTime = tx.StartTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
+                                                    StopTime = tx.StopTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
+                                                    StopReason = tx.StopReasonId < 1 ? "Unknown" : (tx.StopReasonId > 12 ? "Unknown" : ((Reason)tx.StopReasonId).ToString()),
+                                                    Receipt = tx.Receipt,
+                                                    TotalCost = tx.Cost,
+                                                    Fee = tx.Fee
+
+                                                };
+
+                                                var response = await httpClient.Post(customerInfo.ApiUrl + "completed_session", new Dictionary<string, string>()
+                                                {
+                                                    { "PartnerId",session.CustomerId.ToString()}
+
+                                                }, request, customerInfo.ApiKey);
+
+                                                var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
+                                                JObject jo = JObject.Parse(_httpResult.Data);
+                                                if (jo.ContainsKey("CouponPoint"))
+                                                {
+                                                    couponPoint = jo["CouponPoint"].Value<Decimal>();
+
+                                                }
+
+                                                if (jo.ContainsKey("FarewellMessage"))
+                                                {
+                                                    string _Message = jo["FarewellMessage"].Value<string>();
+
+
+                                                }
+                                            }
+
                                             tx.Receipt = receipt;
-                                            tx.UploadedtoTTIA = true;
+                                            tx.BillingDone = true;
                                             db.Configuration.AutoDetectChangesEnabled = false;
                                             db.Configuration.ValidateOnSaveEnabled = false;
                                             db.TransactionRecord.Attach(tx);
                                             db.Entry(tx).Property(x => x.Cost).IsModified = true;
                                             db.Entry(tx).Property(x => x.Receipt).IsModified = true;
-                                            db.Entry(tx).Property(x => x.UploadedtoTTIA).IsModified = true;
+                                            db.Entry(tx).Property(x => x.BillingDone).IsModified = true;
 
                                             db.ServerMessage.Add(new ServerMessage()
                                             {
@@ -949,7 +1074,7 @@ namespace EVCB_OCPP.WSServer.Message
                                                                         parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
                                                                         parkingFee = parkingCost,
                                                                         currency = currency,
-                                                                        couponPoint = 0,
+                                                                        couponPoint = couponPoint,
                                                                         accountBalance = accountBalance - tx.Cost
                                                                     })
                                                                 })
@@ -961,7 +1086,7 @@ namespace EVCB_OCPP.WSServer.Message
 
                                             }); ;
 
-                                            db.SaveChanges();
+                                            await db.SaveChangesAsync();
 
                                             using (var meterdb = new MeterValueDBContext())
                                             {
@@ -993,10 +1118,11 @@ namespace EVCB_OCPP.WSServer.Message
                                                 parameters.Add("@IdTag", tx.StartIdTag, DbType.String, ParameterDirection.Input);
                                                 parameters.Add("@parentIdTag", accountBalance - tx.Cost, DbType.String, ParameterDirection.Input);
                                                 string strSql = "update [dbo].[LocalListDetail] set parentIdTag =@parentIdTag  where ListId = 27 and IdTag=@IdTag; ";
-                                                conn.Execute(strSql, parameters);
+                                                await conn.ExecuteAsync(strSql, parameters);
 
                                             }
 
+                                            #region 提供給PHA 過CDFA認證 使用
                                             if (tx.CustomerId == Guid.Parse("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
                                             {
                                                 var mail_response = new OuterHttpClient().PostFormDataAsync("http://ocpp.phihong.com.tw/CDFA/" + tx.Id, new Dictionary<string, string>()
@@ -1009,6 +1135,7 @@ namespace EVCB_OCPP.WSServer.Message
                                                 Console.WriteLine(JsonConvert.SerializeObject(mail_response));
 
                                             }
+                                            #endregion
 
                                         }
                                         else
@@ -1045,7 +1172,7 @@ namespace EVCB_OCPP.WSServer.Message
 
                                             }); ;
 
-                                            db.SaveChanges();
+                                            await db.SaveChangesAsync();
 
                                             using (var meterdb = new MeterValueDBContext())
                                             {
@@ -1076,8 +1203,9 @@ namespace EVCB_OCPP.WSServer.Message
 
                                     }
 
-
                                 }
+
+                                #region 台泥
                                 if (_request.messageId == "ID_GetTxUserInfo")
                                 {
                                     var txUserInfo = JsonConvert.DeserializeObject<ID_GetTxUserInfo>(_confirm.data);
@@ -1103,6 +1231,8 @@ namespace EVCB_OCPP.WSServer.Message
                                     }
 
                                 }
+
+                                #endregion
                             }
                         }
                         break;
@@ -1121,7 +1251,7 @@ namespace EVCB_OCPP.WSServer.Message
                                     operation.Status = 1;//電樁有回覆
                                     operation.EVSE_Status = (int)_confirm.status;
                                     operation.EVSE_Value = _confirm.status.ToString();
-                                    db.SaveChanges();
+                                    await db.SaveChangesAsync();
                                 }
 
                             }
@@ -1143,7 +1273,7 @@ namespace EVCB_OCPP.WSServer.Message
                                     operation.Status = 1;//電樁有回覆
                                     operation.EVSE_Status = (int)_confirm.status;
                                     operation.EVSE_Value = _confirm.status.ToString();
-                                    db.SaveChanges();
+                                    await db.SaveChangesAsync();
                                 }
 
                             }
@@ -1164,7 +1294,7 @@ namespace EVCB_OCPP.WSServer.Message
                                     operation.Status = 1;//電樁有回覆
                                     operation.EVSE_Status = (int)_confirm.status;
                                     operation.EVSE_Value = _confirm.status.ToString();
-                                    db.SaveChanges();
+                                    await db.SaveChangesAsync();
                                 }
 
                             }
@@ -1185,7 +1315,7 @@ namespace EVCB_OCPP.WSServer.Message
                                     operation.Status = 1;//電樁有回覆
                                     operation.EVSE_Status = (int)_confirm.status;
                                     operation.EVSE_Value = _confirm.status.ToString();
-                                    db.SaveChanges();
+                                    await db.SaveChangesAsync();
                                 }
 
                             }
@@ -1206,7 +1336,7 @@ namespace EVCB_OCPP.WSServer.Message
                                     operation.Status = 1;//電樁有回覆
                                     operation.EVSE_Status = (int)_confirm.status;
                                     operation.EVSE_Value = _confirm.status.ToString();
-                                    db.SaveChanges();
+                                    await db.SaveChangesAsync();
                                 }
 
                             }
@@ -1252,7 +1382,7 @@ namespace EVCB_OCPP.WSServer.Message
                                         });
                                     }
                                 }
-                                db.SaveChanges();
+                                await db.SaveChangesAsync();
                             }
 
                         }
@@ -1334,8 +1464,6 @@ namespace EVCB_OCPP.WSServer.Message
                                         }
                                     }
 
-
-
                                     var operation = db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                                    x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefault();
 
@@ -1348,7 +1476,7 @@ namespace EVCB_OCPP.WSServer.Message
 
                                     }
 
-                                    db.SaveChanges();
+                                    await db.SaveChangesAsync();
 
                                 }
                             }
@@ -1374,7 +1502,7 @@ namespace EVCB_OCPP.WSServer.Message
                                     operation.Status = 1;//電樁有回覆
                                     operation.EVSE_Status = (int)_confirm.status;
                                     operation.EVSE_Value = _confirm.status.ToString();
-                                    db.SaveChanges();
+                                    await db.SaveChangesAsync();
                                 }
 
                             }

+ 1 - 1
EVCB_OCPP.WSServer/Properties/AssemblyInfo.cs

@@ -35,4 +35,4 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyVersion("1.0.4.0")]
 [assembly: AssemblyFileVersion("1.0.4.0")]
 
-[assembly: AssemblyInformationalVersion("499dc33")]
+[assembly: AssemblyInformationalVersion("a89677a")]

+ 49 - 38
EVCB_OCPP.WSServer/ProtalServer.cs

@@ -372,12 +372,10 @@ namespace EVCB_OCPP.WSServer
             var appServer = new OCPPWSServer(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6"), new OCPPSubProtocol("ocpp2.0") });
 
             List<IListenerConfig> llistener = new List<IListenerConfig>();
-            //System.Net.IPAddress.Any.ToString()
-            // llistener.Add(new ListenerConfig { Ip = "", Port = Convert.ToInt32(wssserverPort), Backlog = 100, Security = serverSecurity });
+
             llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWS_Port()), Backlog = 100, Security = "None" });
             llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWSS_Port()), Backlog = 100, Security = SslProtocols.Tls12.ToString() });
 
-            // llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWSS_Port()), Backlog = 100, Security = SslProtocols.Tls11.ToString() });
             var config = ConfigurationManager.GetSection("superSocket") as IConfigurationSource;
             ICertificateConfig Certificate = config.Servers.ElementAt(0).Certificate;
             IEnumerable<IListenerConfig> listeners = llistener;
@@ -385,7 +383,6 @@ namespace EVCB_OCPP.WSServer
             //設定server config
             var serverConfig = new ServerConfig
             {
-
                 //Port = Convert.ToInt32(2012),
                 //Ip = "172.17.40.13",
                 MaxRequestLength = 204800,
@@ -395,8 +392,6 @@ namespace EVCB_OCPP.WSServer
                 //  LogAllSocketException = true,
                 KeepAliveTime = 10,
                 // LogBasicSessionActivity = true
-
-
             };
 
             //Setup with listening port
@@ -421,10 +416,8 @@ namespace EVCB_OCPP.WSServer
 
         private void AppServer_SessionClosed(ClientData session, CloseReason value)
         {
-            //  Console.WriteLine(session.RemoteEndPoint.Address);
             WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
             RemoveClient(session);
-            // close Connection
         }
 
         private void AppServer_NewSessionConnected(ClientData session)
@@ -466,9 +459,6 @@ namespace EVCB_OCPP.WSServer
                             db.SaveChanges();
                         }
                     }
-
-
-                    // CheckEVSEConfigure(session.ChargeBoxId);
                 }
             }
             catch (Exception ex)
@@ -536,14 +526,6 @@ namespace EVCB_OCPP.WSServer
                 }
                 else
                 {
-
-
-
-                    //if (session.ISOCPP20 && !(analysisResult.Action != Actions.BootNotification.ToString() || analysisResult.Action != Actions.Heartbeat.ToString()))
-                    //{
-                    //    Send(session, "Backend doesn't support this message.", string.Format("{0} {1}", analysisResult.Action, "Error"));
-                    //    return;
-                    //}
                     switch (analysisResult.Id)
                     {
                         case BasicMessageHandler.TYPENUMBER_CALL:
@@ -601,8 +583,6 @@ namespace EVCB_OCPP.WSServer
                                     }
 
                                 }
-
-
                             }
                             break;
                         case BasicMessageHandler.TYPENUMBER_CALLRESULT:
@@ -726,8 +706,6 @@ namespace EVCB_OCPP.WSServer
 
         }
 
-
-
         async private void ProcessRequestMessage(MessageResult analysisResult, ClientData session, Actions action)
         {
             BasicMessageHandler msgAnalyser = new BasicMessageHandler();
@@ -754,11 +732,12 @@ namespace EVCB_OCPP.WSServer
 
                                 if (action == Actions.BootNotification && replyResult.Message is BootNotificationConfirmation)
                                 {
+                                    session.IsCheckIn = true;
                                     if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
                                     {
-                                        session.IsCheckIn = true;
+                                        
+
 
-                                      
                                         CheckVersion(session.ChargeBoxId);
                                         CheckEVSEConfigure(session.ChargeBoxId);
 
@@ -848,17 +827,11 @@ namespace EVCB_OCPP.WSServer
 
                                                 }
 
-
                                                 db.SaveChanges();
 
-
                                             }
 
                                         }
-
-
-
-
                                     }
                                     else
                                     {
@@ -880,7 +853,7 @@ namespace EVCB_OCPP.WSServer
                                     }
                                 }
 
-
+                                #region 台泥
                                 if (action == Actions.StartTransaction && session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8") && replyResult.Message is StartTransactionConfirmation)
                                 {
 
@@ -910,6 +883,44 @@ namespace EVCB_OCPP.WSServer
                                         db.SaveChanges();
                                     }
                                 }
+                                #endregion
+
+                                if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
+                                {
+                                    var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
+                                    if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
+                                    {
+                                        using (var db = new MainDBContext())
+                                        {
+                                            db.ServerMessage.Add(new ServerMessage()
+                                            {
+                                                ChargeBoxId = session.ChargeBoxId,
+                                                CreatedBy = "Server",
+                                                CreatedOn = DateTime.UtcNow,
+                                                OutAction = Actions.DataTransfer.ToString(),
+                                                OutRequest = JsonConvert.SerializeObject(
+                                                           new DataTransferRequest()
+                                                           {
+                                                               messageId = "SetUserPrice",
+                                                               vendorId = "Phihong Technology",
+                                                               data = JsonConvert.SerializeObject(
+                                                                   new
+                                                                   {
+                                                                       idToken = authorizeRequest.idTag,
+                                                                       price = session.UserDisplayPrices[authorizeRequest.idTag]
+
+                                                                   })
+                                                           },
+                                                           new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
+                                                SerialNo = Guid.NewGuid().ToString(),
+                                                InMessage = string.Empty
+
+                                            });
+
+                                            db.SaveChanges();
+                                        }
+                                    }
+                                }
 
                             }
                             else
@@ -1041,7 +1052,7 @@ namespace EVCB_OCPP.WSServer
             }
         }
 
-        private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
+        async private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
         {
 
             BasicMessageHandler msgAnalyser = new BasicMessageHandler();
@@ -1053,7 +1064,7 @@ namespace EVCB_OCPP.WSServer
                 {
                     case "Core":
                         {
-                            confirmResult = profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
+                            confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
                         }
                         break;
                     case "FirmwareManagement":
@@ -1825,7 +1836,7 @@ namespace EVCB_OCPP.WSServer
                 parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input);
                 string displayPricestrSql = "";
                 string strSql = "";
-               
+
                 if (client.IsAC)
                 {
                     displayPricestrSql = "   SELECT  [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
@@ -1851,7 +1862,7 @@ namespace EVCB_OCPP.WSServer
                     return string.Empty;
                 }
                 var stationPrice = result.First();
-              
+
                 if (stationPrice.BillingMethod == 1)
                 {
                     var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
@@ -1860,14 +1871,14 @@ namespace EVCB_OCPP.WSServer
                     {
                         client.ChargingPrices = new List<ChargingPrice>();
                     }
-                }               
+                }
 
                 displayPriceText = stationPrice.FeeName;
                 client.BillingMethod = stationPrice.BillingMethod;
                 client.Currency = stationPrice.Currency;
                 client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
                 client.ParkingFee = stationPrice.ParkingFee;
-                client.IsBilling = true;             
+                client.IsBilling = true;
             }
 
             return displayPriceText;

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

@@ -10,7 +10,7 @@ namespace EVCB_OCPP.WSServer.Service
 
     public interface IBusinessService
     {
-        Task<IdTagInfo> Authorize(string chargeBoxId, string idTag);
+        Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag);
 
         Task NotifyFaultStatus(ErrorDetails details);
 

+ 5 - 4
EVCB_OCPP.WSServer/Service/LocalBusinessService.cs

@@ -19,15 +19,16 @@ namespace EVCB_OCPP.WSServer.Service
             this.customerId = customerId;
         }
 
-        async public Task<IdTagInfo> Authorize(string chargeBoxId, string idTag)
+        async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag)
         {
             await Task.Delay(10);
-            IdTagInfo info = new IdTagInfo() { status = AuthorizationStatus.Invalid };
+            IdTokenInfo info = new IdTokenInfo() { IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Invalid } };
+
             try
             {
                 if (customerId.ToUpper() == "009E603C-79CD-4620-A2B8-D9349C0E8AD8")
                 {
-                    info = new IdTagInfo() { status = AuthorizationStatus.Accepted };
+                    info.IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Accepted };
                     return info;
                 }
 
@@ -57,7 +58,7 @@ namespace EVCB_OCPP.WSServer.Service
                     {
                         try
                         {
-                            info.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), jo["message"].ToString());
+                            info.IdTagInfo.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), jo["message"].ToString());
                         }
                         catch (Exception)
                         {

+ 29 - 11
EVCB_OCPP.WSServer/Service/OuterBusinessService.cs

@@ -57,18 +57,19 @@ namespace EVCB_OCPP.WSServer.Service
         }
 
 
-        async public Task<IdTagInfo> Authorize(string chargeBoxId, string idTag)
+        async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag)
         {
-            Console.WriteLine(string.Format("Authorize: {0}", CustomerId));
-            IdTagInfo result = new IdTagInfo() { status = AuthorizationStatus.Invalid };
+            await Task.Delay(10);
+            IdTokenInfo result = new IdTokenInfo() { IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Invalid } };
+
             try
             {
-               
+
                 string requestParams = string.Format("charging_auth?ChargeBoxId={0}&IdTag={1}", chargeBoxId, idTag);
 
                 if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
                 {
-                    logger.Error(chargeBoxId+" Charging Monitor======================================>");
+                    logger.Error(chargeBoxId + " Charging Monitor======================================>");
                     logger.Error(signMaterial.APIUrl + requestParams);
                 }
                 var response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
@@ -77,7 +78,7 @@ namespace EVCB_OCPP.WSServer.Service
 
                             }, null, signMaterial.SaltKey).ConfigureAwait(false);
                 if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
-                {                  
+                {
                     logger.Error(JsonConvert.SerializeObject(response));
                 }
                 if (response.Success)
@@ -89,21 +90,38 @@ namespace EVCB_OCPP.WSServer.Service
                     if (jo.ContainsKey("ExpiryDate"))
                     {
                         DateTime dt = jo["ExpiryDate"].Value<DateTime>();
-                        result.expiryDate = dt;
+                        result.IdTagInfo.expiryDate = dt;
                     }
 
                     if (jo.ContainsKey("ParentIdTag"))
                     {
                         string _Message = jo["ParentIdTag"].Value<string>();
-                        result.parentIdTag = _Message;
+                        result.IdTagInfo.parentIdTag = _Message;
 
                     }
 
+                    if (jo.ContainsKey("ChargePointFee"))
+                    {
+                        result.ChargePointFee = new List<ChargePointFee>();
+
+                        for(int i=0;i< jo["ChargePointFee"].Count();i++)
+                        {
+                            result.ChargePointFee.Add(jo["ChargePointFee"][i].ToObject<ChargePointFee>());
+                        }
+                     
+                    }
+
+                    if (jo.ContainsKey("AccountBalance"))
+                    {
+                        decimal accountBalance = jo["AccountBalance"].Value<decimal>();
+                        result.AccountBalance = accountBalance;
+                    }
+
 
                     if (jo.ContainsKey("Status"))
                     {
                         string _Message = jo["Status"].Value<string>();
-                        result.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), _Message);
+                        result.IdTagInfo.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), _Message);
                     }
                 }
                 else
@@ -114,11 +132,11 @@ namespace EVCB_OCPP.WSServer.Service
             }
             catch (Exception ex)
             {
-                result.status = AuthorizationStatus.Invalid;
+                result.IdTagInfo.status = AuthorizationStatus.Invalid;
 
                 logger.Error(chargeBoxId + " OuterBusinessService.Authorize Ex: " + ex.ToString());
             }
-         
+
             return result;
 
         }

+ 6 - 1
EVCB_OCPP.WSServer/SuperSocket.Protocol/ClientData.cs

@@ -34,6 +34,10 @@ namespace OCPPServer.Protocol
 
         #region Billing
 
+        public Dictionary<string,string> UserPrices { set; get; }
+
+        public Dictionary<string, string> UserDisplayPrices { set; get; }
+
         public List<ChargingPrice> ChargingPrices { set; get; }
 
         /// <summary>
@@ -88,7 +92,8 @@ namespace OCPPServer.Protocol
             IsCheckIn = false;
             ChargeBoxId = SessionID;
             MachineId = SessionID;
-
+            UserPrices = new Dictionary<string, string>();
+            UserDisplayPrices = new Dictionary<string, string>();
         }