|
@@ -24,29 +24,50 @@ using OCPPPackage.Profiles;
|
|
|
using System.Threading.Tasks;
|
|
|
using EVCB_OCPP.WSServer.Helper;
|
|
|
using System.Data.SqlClient;
|
|
|
+using EVCB_OCPP.Packet.Messages.FirmwareManagement;
|
|
|
+using EVCB_OCPP.Packet.Messages.RemoteTrigger;
|
|
|
+using System.Configuration;
|
|
|
+using System.Net;
|
|
|
+using System.Net.Security;
|
|
|
+using System.Security.Cryptography.X509Certificates;
|
|
|
|
|
|
namespace EVCB_OCPP.WSServer
|
|
|
{
|
|
|
internal class ProtalServer
|
|
|
{
|
|
|
-
|
|
|
- internal Dictionary<string, ClientData> ClientDic = new Dictionary<string, ClientData>();
|
|
|
static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
|
|
|
+
|
|
|
+ private Dictionary<string, ClientData> ClientDic = new Dictionary<string, ClientData>();
|
|
|
private readonly Object _lockClientDic = new object();
|
|
|
private readonly Object _lockConfirmPacketList = new object();
|
|
|
- ProfileHandler _profileHandler = new ProfileHandler();
|
|
|
+ private ProfileHandler _profileHandler = new ProfileHandler();
|
|
|
private List<NeedConfirmMessage> NeedConfirmPacketList = new List<NeedConfirmMessage>();
|
|
|
+ private DateTime checkUpdateDt = DateTime.Now;
|
|
|
private List<string> _needConfirmActions = new List<string>()
|
|
|
{
|
|
|
- "GetConfiguration",
|
|
|
- "ChangeConfiguration",
|
|
|
- "RemoteStartTransaction",
|
|
|
- "RemoteStopTransaction",
|
|
|
- "ChangeAvailability",
|
|
|
- "ClearCache",
|
|
|
- "DataTransfer",
|
|
|
- "Reset",
|
|
|
+ "GetConfiguration",
|
|
|
+ "ChangeConfiguration",
|
|
|
+ "RemoteStartTransaction",
|
|
|
+ "RemoteStopTransaction",
|
|
|
+ "ChangeAvailability",
|
|
|
+ "ClearCache",
|
|
|
+ "DataTransfer",
|
|
|
+ "Reset",
|
|
|
"UnlockConnector",
|
|
|
+ "TriggerMessage",
|
|
|
+ "GetDiagnostics",
|
|
|
+ "UpdateFirmware",
|
|
|
+ "GetLocalListVersion",
|
|
|
+ "SendLocalList",
|
|
|
+ "SetChargingProfile",
|
|
|
+ "ClearChargingProfile",
|
|
|
+ "GetCompositeSchedule",
|
|
|
+ "ReserveNow",
|
|
|
+ "CancelReservation",
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
|
|
|
|
|
|
};
|
|
@@ -62,20 +83,30 @@ namespace EVCB_OCPP.WSServer
|
|
|
private CancellationTokenSource _cts = new CancellationTokenSource();
|
|
|
private CancellationToken _ct;
|
|
|
|
|
|
+
|
|
|
internal ProtalServer()
|
|
|
{
|
|
|
_ct = _cts.Token;
|
|
|
-
|
|
|
+ WarmUpLog();
|
|
|
}
|
|
|
|
|
|
|
|
|
internal void Start()
|
|
|
{
|
|
|
+
|
|
|
+ if (!GlobalConfig.LoadAPPConfig())
|
|
|
+ {
|
|
|
+ Console.WriteLine("Please check App.Config setting .");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
OpenNetwork();
|
|
|
|
|
|
+ Task serverCommandTask = new Task(ServerMessageTrigger, _ct);
|
|
|
+ serverCommandTask.Start();
|
|
|
|
|
|
- Task taskServerCommand = new Task(ServerMessageTrigger, _ct);
|
|
|
- taskServerCommand.Start();
|
|
|
+ Task serverUpdateTask = new Task(ServerUpdateTrigger, _ct);
|
|
|
+ serverUpdateTask.Start();
|
|
|
|
|
|
while (true)
|
|
|
{
|
|
@@ -84,7 +115,8 @@ namespace EVCB_OCPP.WSServer
|
|
|
switch (input.ToLower())
|
|
|
{
|
|
|
case "stop":
|
|
|
-
|
|
|
+ logger.Info("Command stop");
|
|
|
+ Stop();
|
|
|
break;
|
|
|
|
|
|
case "gc":
|
|
@@ -93,15 +125,43 @@ namespace EVCB_OCPP.WSServer
|
|
|
break;
|
|
|
|
|
|
case "lc":
|
|
|
- logger.Info("Command List Clients");
|
|
|
+ {
|
|
|
+ logger.Info("Command List Clients");
|
|
|
+ Dictionary<string, ClientData> _copyClientDic = null;
|
|
|
+ lock (_lockClientDic)
|
|
|
+ {
|
|
|
+ _copyClientDic = new Dictionary<string, ClientData>(ClientDic);
|
|
|
|
|
|
- break;
|
|
|
+ }
|
|
|
+ var list = _copyClientDic.Select(c => c.Value).ToList();
|
|
|
+ int i = 1;
|
|
|
+ foreach (var c in list)
|
|
|
+ {
|
|
|
+ logger.Info(i + ":" + c.ChargeBoxId);
|
|
|
+ i++;
|
|
|
+ }
|
|
|
|
|
|
+ }
|
|
|
+ break;
|
|
|
case "lcn":
|
|
|
- logger.Info("Command List Customer Name");
|
|
|
+ {
|
|
|
+ logger.Info("Command List Customer Name");
|
|
|
+ Dictionary<string, ClientData> _copyClientDic = null;
|
|
|
+ lock (_lockClientDic)
|
|
|
+ {
|
|
|
+ _copyClientDic = new Dictionary<string, ClientData>(ClientDic);
|
|
|
|
|
|
- break;
|
|
|
+ }
|
|
|
+ var lcn = ClientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
|
|
|
+ int iLcn = 1;
|
|
|
+ foreach (var c in lcn)
|
|
|
+ {
|
|
|
+ logger.Info(iLcn + ":" + c + ":" + ClientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
|
|
|
+ iLcn++;
|
|
|
+ }
|
|
|
|
|
|
+ }
|
|
|
+ break;
|
|
|
case "help":
|
|
|
logger.Info("Command help!!");
|
|
|
logger.Info("lcn : List Customer Name");
|
|
@@ -110,9 +170,8 @@ namespace EVCB_OCPP.WSServer
|
|
|
logger.Info("cls : clear console");
|
|
|
logger.Info("silent : silent");
|
|
|
logger.Info("show : show log");
|
|
|
- logger.Info("rcl : show Real Connection Limit");
|
|
|
+ // logger.Info("rcl : show Real Connection Limit");
|
|
|
break;
|
|
|
-
|
|
|
case "cls":
|
|
|
logger.Info("Command clear");
|
|
|
Console.Clear();
|
|
@@ -130,7 +189,6 @@ namespace EVCB_OCPP.WSServer
|
|
|
}
|
|
|
xe.Save("NLog.config");
|
|
|
break;
|
|
|
-
|
|
|
case "show":
|
|
|
logger.Info("Command show");
|
|
|
var xe1 = XElement.Load("NLog.config");
|
|
@@ -143,31 +201,51 @@ namespace EVCB_OCPP.WSServer
|
|
|
}
|
|
|
xe1.Save("NLog.config");
|
|
|
break;
|
|
|
-
|
|
|
case "rcl":
|
|
|
-
|
|
|
-
|
|
|
break;
|
|
|
-
|
|
|
default:
|
|
|
break;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- private void InitEVSEConfigure(string sn)
|
|
|
+ internal void Stop()
|
|
|
{
|
|
|
- List<MachineConfigure> configures = new List<MachineConfigure>();
|
|
|
- configures.Add(new MachineConfigure() { ConfigureName = StandardConfiguration.AuthorizeRemoteTxRequests, ConfigureSetting = "" });
|
|
|
+ if (_cts != null)
|
|
|
+ {
|
|
|
+ _cts.Cancel();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void CheckEVSEConfigure(string chargeBoxId)
|
|
|
+ {
|
|
|
+
|
|
|
+
|
|
|
using (var db = new MainDBContext())
|
|
|
{
|
|
|
- var _sn = db.MachineConfigure.Where(x => x.ChargeBoxId == sn).Select(x => x.ChargeBoxId).FirstOrDefault();
|
|
|
+
|
|
|
+ var _sn = db.MachineConfigure.Where(x => x.ChargeBoxId == chargeBoxId).Select(x => x.ChargeBoxId).FirstOrDefault();
|
|
|
if (string.IsNullOrEmpty(_sn))
|
|
|
{
|
|
|
- db.MachineConfigure.Add(new MachineConfigure()
|
|
|
+ db.ServerMessage.Add(new ServerMessage()
|
|
|
{
|
|
|
+ ChargeBoxId = chargeBoxId,
|
|
|
+ CreatedBy = "Server",
|
|
|
+ CreatedOn = DateTime.Now,
|
|
|
+ OutAction = Actions.GetConfiguration.ToString(),
|
|
|
+ OutRequest = JsonConvert.SerializeObject(
|
|
|
+ new GetConfigurationRequest()
|
|
|
+ {
|
|
|
+ key = new List<string>()
|
|
|
+
|
|
|
+ },
|
|
|
+ new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
|
|
|
+ SerialNo = Guid.NewGuid().ToString(),
|
|
|
+ InMessage = string.Empty
|
|
|
|
|
|
});
|
|
|
+
|
|
|
+ db.SaveChanges();
|
|
|
}
|
|
|
}
|
|
|
}
|
|
@@ -175,14 +253,17 @@ namespace EVCB_OCPP.WSServer
|
|
|
|
|
|
private void OpenNetwork()
|
|
|
{
|
|
|
+
|
|
|
//載入OCPP Protocol
|
|
|
- var appServer = new OCPPWSServer(new OCPPSubProtocol());
|
|
|
+ var appServer = new OCPPWSServer(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6") });
|
|
|
|
|
|
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 = "172.17.40.13", Port = Convert.ToInt32(2012), Backlog = 100, Security = "None" });
|
|
|
-
|
|
|
+ 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 = "tls" });
|
|
|
+ var config = ConfigurationManager.GetSection("superSocket") as IConfigurationSource;
|
|
|
+ ICertificateConfig Certificate = config.Servers.ElementAt(0).Certificate;
|
|
|
IEnumerable<IListenerConfig> listeners = llistener;
|
|
|
|
|
|
//設定server config
|
|
@@ -192,8 +273,9 @@ namespace EVCB_OCPP.WSServer
|
|
|
//Ip = "172.17.40.13",
|
|
|
MaxRequestLength = 4096,
|
|
|
//Security = serverSecurity,
|
|
|
- // Certificate = Certificate,
|
|
|
- Listeners = listeners
|
|
|
+ Certificate = Certificate,
|
|
|
+ Listeners = listeners,
|
|
|
+
|
|
|
|
|
|
};
|
|
|
|
|
@@ -218,6 +300,7 @@ namespace EVCB_OCPP.WSServer
|
|
|
|
|
|
private void AppServer_SessionClosed(ClientData session, CloseReason value)
|
|
|
{
|
|
|
+ Console.WriteLine(session.RemoteEndPoint.Address);
|
|
|
WriteMachineLog(session.ChargeBoxId, string.Format("CloseReason: {0}", value), "Connection", "");
|
|
|
RemoveClient(session);
|
|
|
// close Connection
|
|
@@ -225,6 +308,7 @@ namespace EVCB_OCPP.WSServer
|
|
|
|
|
|
private void AppServer_NewSessionConnected(ClientData session)
|
|
|
{
|
|
|
+ Console.WriteLine("------------New");
|
|
|
session.m_ReceiveData += new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
|
|
|
try
|
|
|
{
|
|
@@ -238,12 +322,14 @@ namespace EVCB_OCPP.WSServer
|
|
|
RemoveClient(_removeClient);
|
|
|
}
|
|
|
ClientDic.Add(session.ChargeBoxId, session);
|
|
|
+
|
|
|
+ Console.WriteLine("------------New" + (session == null ? "Oops" : session.ChargeBoxId));
|
|
|
WriteMachineLog(session.ChargeBoxId, "", "Connection", "");
|
|
|
}
|
|
|
}
|
|
|
catch (Exception ex)
|
|
|
{
|
|
|
-
|
|
|
+ logger.Error(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
|
|
|
}
|
|
|
|
|
|
|
|
@@ -257,14 +343,14 @@ namespace EVCB_OCPP.WSServer
|
|
|
|
|
|
|
|
|
WriteMachineLog(session.ChargeBoxId, rawdata,
|
|
|
- string.Format("{0} {1}", analysisResult.Action, analysisResult.Id == 2 ? "Request" : (analysisResult.Id == 3 ? "Confirmation" : "Error")));
|
|
|
+ string.Format("{0} {1}", string.IsNullOrEmpty(analysisResult.Action) ? "unknown" : analysisResult.Action, analysisResult.Id == 2 ? "Request" : (analysisResult.Id == 3 ? "Confirmation" : "Error")));
|
|
|
|
|
|
if (analysisResult.Success == false)
|
|
|
{
|
|
|
//解析RawData就發生錯誤
|
|
|
if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
|
|
|
{
|
|
|
- Send(session, rawdata, string.Format("{0} {1}", analysisResult.Action, "Error"));
|
|
|
+ Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
|
|
|
}
|
|
|
else
|
|
|
{
|
|
@@ -334,87 +420,8 @@ namespace EVCB_OCPP.WSServer
|
|
|
{
|
|
|
case "Core":
|
|
|
{
|
|
|
- if (!session.IsCheckIn && action == Actions.BootNotification)
|
|
|
- {
|
|
|
-
|
|
|
- var requestId = Guid.NewGuid();
|
|
|
- //測試命令
|
|
|
- try
|
|
|
- {
|
|
|
-
|
|
|
-
|
|
|
- //using (var db = new MainDBContext())
|
|
|
- //{
|
|
|
- // //db.MachineOperateRecord.Add(new MachineOperateRecord()
|
|
|
- // //{
|
|
|
- // // CreatedOn = DateTime.Now,
|
|
|
- // // ChargePointSerialNumber = session.ChargePointSerialNumber,
|
|
|
- // // SerialNo = requestId.ToString(),
|
|
|
- // // RequestContent = JsonConvert.SerializeObject(new GetConfigurationRequest() { key = new List<string>() { StandardConfiguration.HeartbeatInterval } }),
|
|
|
- // // EVSE_Status = 0,
|
|
|
- // // Status = 0,
|
|
|
- // // RequestType = 1,
|
|
|
-
|
|
|
-
|
|
|
- // //});
|
|
|
- // //core 26 項 設定
|
|
|
- // GetConfigurationRequest core_getConfigReq = new GetConfigurationRequest()
|
|
|
- // {
|
|
|
-
|
|
|
- // key = new List<string>()
|
|
|
- // {
|
|
|
- // StandardConfiguration.AuthorizeRemoteTxRequests,
|
|
|
- // StandardConfiguration.ClockAlignedDataInterval,
|
|
|
- // StandardConfiguration.ConnectionTimeOut,
|
|
|
- // //StandardConfiguration.HeartbeatInterval,
|
|
|
- // //StandardConfiguration.HeartbeatInterval,
|
|
|
- // //StandardConfiguration.LocalAuthorizeOffline,
|
|
|
- // //StandardConfiguration.LocalPreAuthorize,
|
|
|
- // //StandardConfiguration.MeterValuesAlignedData,
|
|
|
- // //StandardConfiguration.MeterValuesAlignedDataMaxLength,
|
|
|
- // //StandardConfiguration.MeterValuesSampledData,
|
|
|
- // //StandardConfiguration.MeterValuesSampledDataMaxLength,
|
|
|
- // //StandardConfiguration.MeterValueSampleInterval,
|
|
|
- // //StandardConfiguration.NumberOfConnectors,
|
|
|
- // //StandardConfiguration.ResetRetries,
|
|
|
- // //StandardConfiguration.ConnectorPhaseRotation,
|
|
|
- // //StandardConfiguration.ConnectorPhaseRotationMaxLength,
|
|
|
- // //StandardConfiguration.StopTransactionOnEVSideDisconnect,
|
|
|
- // //StandardConfiguration.StopTransactionOnInvalidId,
|
|
|
- // //StandardConfiguration.StopTxnAlignedData,
|
|
|
- // //StandardConfiguration.StopTxnAlignedDataMaxLength,
|
|
|
- // //StandardConfiguration.StopTxnSampledData,
|
|
|
- // //StandardConfiguration.StopTxnSampledDataMaxLength,
|
|
|
- // //StandardConfiguration.SupportedFeatureProfiles,
|
|
|
- // //StandardConfiguration.SupportedFeatureProfilesMaxLength,
|
|
|
- // //StandardConfiguration.TransactionMessageAttempts,
|
|
|
- // //StandardConfiguration.TransactionMessageRetryInterval,
|
|
|
- // //StandardConfiguration.UnlockConnectorOnEVSideDisconnect,
|
|
|
- // //StandardConfiguration.WebSocketPingInterval
|
|
|
-
|
|
|
- // }
|
|
|
- // };
|
|
|
- // db.ServerMessage.Add(new ServerMessage()
|
|
|
- // {
|
|
|
- // ChargeBoxId = session.ChargeBoxId,
|
|
|
- // CreatedBy = "Server",
|
|
|
- // CreatedOn = DateTime.Now,
|
|
|
- // OutAction = Actions.GetConfiguration.ToString(),
|
|
|
- // OutRequest = JsonConvert.SerializeObject(core_getConfigReq),
|
|
|
- // SerialNo = Guid.Empty.ToString(),
|
|
|
- // InMessage = string.Empty
|
|
|
-
|
|
|
- // });
|
|
|
-
|
|
|
- // db.SaveChanges();
|
|
|
- //}
|
|
|
- }
|
|
|
- catch (Exception ex)
|
|
|
- {
|
|
|
-
|
|
|
- }
|
|
|
|
|
|
- }
|
|
|
+ bool oldstatus = session.IsCheckIn;
|
|
|
var replyResult = _profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message);
|
|
|
if (replyResult.Success)
|
|
|
{
|
|
@@ -425,8 +432,43 @@ namespace EVCB_OCPP.WSServer
|
|
|
if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
|
|
|
{
|
|
|
session.IsCheckIn = true;
|
|
|
+ if (!oldstatus)
|
|
|
+ {
|
|
|
+ using (var db = new MainDBContext())
|
|
|
+ {
|
|
|
+ var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
|
|
|
+ if (machine != null)
|
|
|
+ {
|
|
|
+ machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
|
|
|
+ db.SaveChanges();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ CheckEVSEConfigure(session.ChargeBoxId);
|
|
|
+ }
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ string response = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
|
|
|
+ string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
|
|
|
+
|
|
|
+ Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+ break;
|
|
|
+ case "FirmwareManagement":
|
|
|
+ {
|
|
|
+ var replyResult = _profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
|
|
|
+ if (replyResult.Success)
|
|
|
+ {
|
|
|
+ string response = msgAnalyser.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
|
|
|
+ Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"));
|
|
|
+
|
|
|
}
|
|
|
else
|
|
|
{
|
|
@@ -453,7 +495,7 @@ namespace EVCB_OCPP.WSServer
|
|
|
private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
|
|
|
{
|
|
|
BasicMessageHandler msgAnalyser = new BasicMessageHandler();
|
|
|
- if (ConfirmMessage(analysisResult))
|
|
|
+ if (ReConfirmMessage(analysisResult))
|
|
|
{
|
|
|
var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
|
|
|
MessageResult confirmResult = null;
|
|
@@ -464,6 +506,31 @@ namespace EVCB_OCPP.WSServer
|
|
|
confirmResult = _profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
|
|
|
}
|
|
|
break;
|
|
|
+ case "FirmwareManagement":
|
|
|
+ {
|
|
|
+ confirmResult = _profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
|
|
|
+ }
|
|
|
+ break;
|
|
|
+ case "RemoteTrigger":
|
|
|
+ {
|
|
|
+ confirmResult = _profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
|
|
|
+ }
|
|
|
+ break;
|
|
|
+ case "Reservation":
|
|
|
+ {
|
|
|
+ confirmResult = _profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
|
|
|
+ }
|
|
|
+ break;
|
|
|
+ case "LocalAuthListManagement":
|
|
|
+ {
|
|
|
+ confirmResult = _profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
|
|
|
+ }
|
|
|
+ break;
|
|
|
+ case "SmartCharging":
|
|
|
+ {
|
|
|
+ confirmResult = _profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
|
|
|
+ }
|
|
|
+ break;
|
|
|
default:
|
|
|
{
|
|
|
string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
|
|
@@ -491,7 +558,7 @@ namespace EVCB_OCPP.WSServer
|
|
|
private void ProcessErrorMessage(MessageResult analysisResult, ClientData session, Actions action)
|
|
|
{
|
|
|
BasicMessageHandler msgAnalyser = new BasicMessageHandler();
|
|
|
- if (ConfirmMessage(analysisResult))
|
|
|
+ if (ReConfirmMessage(analysisResult))
|
|
|
{
|
|
|
var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
|
|
|
switch (profileName)
|
|
@@ -501,6 +568,31 @@ namespace EVCB_OCPP.WSServer
|
|
|
_profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
|
|
|
}
|
|
|
break;
|
|
|
+ case "FirmwareManagement":
|
|
|
+ {
|
|
|
+ _profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
|
|
|
+ }
|
|
|
+ break;
|
|
|
+ case "RemoteTrigger":
|
|
|
+ {
|
|
|
+ _profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
|
|
|
+ }
|
|
|
+ break;
|
|
|
+ case "Reservation":
|
|
|
+ {
|
|
|
+ _profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
|
|
|
+ }
|
|
|
+ break;
|
|
|
+ case "LocalAuthListManagement":
|
|
|
+ {
|
|
|
+ _profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
|
|
|
+ }
|
|
|
+ break;
|
|
|
+ case "SmartCharging":
|
|
|
+ {
|
|
|
+ _profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
|
|
|
+ }
|
|
|
+ break;
|
|
|
default:
|
|
|
{
|
|
|
string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
|
|
@@ -529,7 +621,7 @@ namespace EVCB_OCPP.WSServer
|
|
|
|
|
|
if (session != null)
|
|
|
{
|
|
|
- WriteMachineLog(session.ChargeBoxId, msg, messageType, errorMsg);
|
|
|
+ WriteMachineLog(session.ChargeBoxId, msg, messageType, errorMsg, true);
|
|
|
session.Send(msg);
|
|
|
}
|
|
|
|
|
@@ -542,7 +634,136 @@ namespace EVCB_OCPP.WSServer
|
|
|
|
|
|
}
|
|
|
|
|
|
- private void ServerMessageTrigger()
|
|
|
+ async private void ServerUpdateTrigger()
|
|
|
+ {
|
|
|
+ for (; ; )
|
|
|
+ {
|
|
|
+ if (_ct.IsCancellationRequested)
|
|
|
+ {
|
|
|
+ break;
|
|
|
+ }
|
|
|
+
|
|
|
+ var min_Interval = (DateTime.Now - checkUpdateDt).TotalMinutes;
|
|
|
+ if (min_Interval > 3)
|
|
|
+ {
|
|
|
+ BasicMessageHandler msgAnalyser = new BasicMessageHandler();
|
|
|
+ Dictionary<string, ClientData> _copyClientDic = null;
|
|
|
+ lock (_lockClientDic)
|
|
|
+ {
|
|
|
+ _copyClientDic = new Dictionary<string, ClientData>(ClientDic);
|
|
|
+
|
|
|
+ }
|
|
|
+ checkUpdateDt = DateTime.Now;
|
|
|
+ using (var db = new MainDBContext())
|
|
|
+ {
|
|
|
+ //var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
|
|
|
+ // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
|
|
|
+ // .Select(x => new { x.Id, x.ChargeBoxId, x.FW_AssignedMachineVersionId }).ToList();
|
|
|
+
|
|
|
+ var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
|
|
|
+ x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
|
|
|
+ .Select(x => x.ChargeBoxId).ToList();
|
|
|
+
|
|
|
+ foreach (var chargeBoxId in needUpdateChargers)
|
|
|
+ {
|
|
|
+ try
|
|
|
+ {
|
|
|
+
|
|
|
+
|
|
|
+ ClientData session;
|
|
|
+ if (_copyClientDic.TryGetValue(chargeBoxId, out session))
|
|
|
+ {
|
|
|
+
|
|
|
+ string requestId = Guid.NewGuid().ToString();
|
|
|
+ // using (var db = new MainDBContext())
|
|
|
+
|
|
|
+ if (session.IsCheckIn)
|
|
|
+ {
|
|
|
+
|
|
|
+ var _request = new TriggerMessageRequest()
|
|
|
+ {
|
|
|
+ requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
|
|
|
+ };
|
|
|
+
|
|
|
+ var uuid = session.queue.store(_request);
|
|
|
+ string rawRequest = msgAnalyser.GenerateRequest(uuid, _request.Action, _request);
|
|
|
+ Send(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
|
|
|
+
|
|
|
+ #region OCTT ,測試韌體更新方式
|
|
|
+ //--------------------> OCTT ,測試韌體更新方式
|
|
|
+ //{
|
|
|
+ // var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
|
|
|
+ // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
|
|
|
+ // .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
|
|
|
+
|
|
|
+ // if (machine != null)
|
|
|
+ // {
|
|
|
+ // var mv = db.MachineVersion.Include(c => c.PublishVersion)
|
|
|
+ // .Include(c => c.PublishVersion.PublishVersionFiles)
|
|
|
+ // .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
|
|
|
+ // .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
|
|
|
+
|
|
|
+ // string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
|
|
|
+
|
|
|
+ // var _updateFWrequest = new UpdateFirmwareRequest()
|
|
|
+ // {
|
|
|
+ // location = new Uri(downloadUrl),
|
|
|
+ // retries = 3,
|
|
|
+ // retrieveDate = DateTime.Now,
|
|
|
+ // retryInterval = 10
|
|
|
+ // };
|
|
|
+ // db.MachineOperateRecord.Add(new MachineOperateRecord()
|
|
|
+ // {
|
|
|
+ // CreatedOn = DateTime.Now,
|
|
|
+ // ChargeBoxId = session.ChargeBoxId,
|
|
|
+ // SerialNo = requestId,
|
|
|
+ // RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
|
|
|
+ // EVSE_Status = 0,
|
|
|
+ // EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
|
|
|
+ // Status = 0,
|
|
|
+ // RequestType = 0,
|
|
|
+
|
|
|
+ // });
|
|
|
+
|
|
|
+ // db.ServerMessage.Add(new ServerMessage()
|
|
|
+ // {
|
|
|
+ // ChargeBoxId = session.ChargeBoxId,
|
|
|
+ // CreatedBy = "Server",
|
|
|
+ // CreatedOn = DateTime.Now,
|
|
|
+ // OutAction = _updateFWrequest.Action.ToString(),
|
|
|
+ // OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
|
|
|
+ // SerialNo = requestId,
|
|
|
+ // InMessage = string.Empty
|
|
|
+
|
|
|
+ // });
|
|
|
+
|
|
|
+ // db.SaveChanges();
|
|
|
+
|
|
|
+ // }
|
|
|
+
|
|
|
+ //}
|
|
|
+ #endregion
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ }
|
|
|
+ catch (Exception ex)
|
|
|
+ {
|
|
|
+ logger.Error(string.Format("serverUpdateTrigger ChargeBoxId:{0} Ex:{1}", chargeBoxId, ex.ToString()));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ await Task.Delay(1000);
|
|
|
+ // Thread.CurrentThread.Join(1000);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async private void ServerMessageTrigger()
|
|
|
{
|
|
|
for (; ; )
|
|
|
{
|
|
@@ -560,13 +781,17 @@ namespace EVCB_OCPP.WSServer
|
|
|
{
|
|
|
DateTime startDt = DateTime.Now.AddSeconds(-30);
|
|
|
DateTime dt = new DateTime(1991, 1, 1);
|
|
|
- Console.WriteLine(string.Format("{0} IN", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
|
|
|
- var commandList = db.ServerMessage.Where(c => c.ReceivedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= DateTime.Now).AsNoTracking().ToList();
|
|
|
+ //Console.WriteLine(string.Format("{0} IN", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
|
|
|
+ var commandList = db.ServerMessage.Where(c => c.ReceivedOn == dt && c.UpdatedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= DateTime.Now).AsNoTracking().ToList();
|
|
|
//處理主機傳送的有指令
|
|
|
var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
|
|
|
+ if (commandList.Count > 0)
|
|
|
+ {
|
|
|
+ Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
|
|
|
+ }
|
|
|
+
|
|
|
foreach (var charger_SN in cmdMachineList)
|
|
|
{
|
|
|
-
|
|
|
ClientData session;
|
|
|
string uuid = string.Empty;
|
|
|
if (ClientDic.TryGetValue(charger_SN, out session))
|
|
@@ -602,23 +827,36 @@ namespace EVCB_OCPP.WSServer
|
|
|
Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
|
|
|
}
|
|
|
|
|
|
-
|
|
|
AddConfirmMessage(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid);
|
|
|
|
|
|
+ #region 更新資料表單一欄位
|
|
|
+ var _UpdatedItem = new ServerMessage() { Id = item.Id, UpdatedOn = DateTime.Now };
|
|
|
+ db.Configuration.AutoDetectChangesEnabled = false;//自動呼叫DetectChanges()比對所有的entry集合的每一個屬性Properties的新舊值
|
|
|
+ db.Configuration.ValidateOnSaveEnabled = false;// 因為Entity有些欄位必填,若不避開會有Validate錯誤
|
|
|
+ // var _UpdatedItem = db.ServerMessage.Where(x => x.Id == item.Id).FirstOrDefault();
|
|
|
+ db.ServerMessage.Attach(_UpdatedItem);
|
|
|
+ _UpdatedItem.UpdatedOn = DateTime.Now;
|
|
|
+ db.Entry(_UpdatedItem).Property(x => x.UpdatedOn).IsModified = true;// 可以直接使用這方式強制某欄位要更新,只是查詢集合耗效能而己
|
|
|
+
|
|
|
+ db.SaveChanges();
|
|
|
+
|
|
|
+ #endregion
|
|
|
|
|
|
|
|
|
}
|
|
|
+
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
+ db.ChangeTracker.DetectChanges();
|
|
|
}
|
|
|
|
|
|
- Task.Delay(2000);
|
|
|
+ await Task.Delay(1000);
|
|
|
+ // Thread.CurrentThread.Join(1000);
|
|
|
}
|
|
|
catch (Exception ex)
|
|
|
{
|
|
|
- logger.Error("ServerMessageTrigger stop");
|
|
|
- logger.Error(ex);
|
|
|
+ logger.Error(string.Format("ServerMessageTrigger Ex:{0}", ex.ToString()));
|
|
|
}
|
|
|
}
|
|
|
}
|
|
@@ -641,6 +879,10 @@ namespace EVCB_OCPP.WSServer
|
|
|
lock (_lockConfirmPacketList)
|
|
|
{
|
|
|
NeedConfirmPacketList.Add(_needConfirmMsg);
|
|
|
+ if (action == "GetConfiguration")
|
|
|
+ {
|
|
|
+ Console.WriteLine("AddConfirmMessage: " + msg_id);
|
|
|
+ }
|
|
|
}
|
|
|
}
|
|
|
}
|
|
@@ -659,18 +901,22 @@ namespace EVCB_OCPP.WSServer
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- private bool ConfirmMessage(MessageResult analysisResult)
|
|
|
+ private bool ReConfirmMessage(MessageResult analysisResult)
|
|
|
{
|
|
|
bool confirmed = false;
|
|
|
if (_needConfirmActions.Contains(analysisResult.Action))
|
|
|
{
|
|
|
+ if (analysisResult.Action == "GetConfiguration")
|
|
|
+ {
|
|
|
+ Console.WriteLine("ReConfirmMessage: " + analysisResult.UUID);
|
|
|
+ }
|
|
|
NeedConfirmMessage foundRequest = null;
|
|
|
lock (_lockConfirmPacketList)
|
|
|
{
|
|
|
foundRequest = NeedConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
|
|
|
}
|
|
|
|
|
|
- if (foundRequest.Id > 0)
|
|
|
+ if (foundRequest != null && foundRequest.Id > 0)
|
|
|
{
|
|
|
foundRequest.SentTimes = 0;
|
|
|
foundRequest.SentInterval = 0;
|
|
@@ -679,15 +925,20 @@ namespace EVCB_OCPP.WSServer
|
|
|
using (var db = new MainDBContext())
|
|
|
{
|
|
|
var sc = db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefault();
|
|
|
- sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.Indented);
|
|
|
+ sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
|
|
|
sc.ReceivedOn = DateTime.Now;
|
|
|
db.SaveChanges();
|
|
|
+ Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
|
|
|
|
|
|
}
|
|
|
confirmed = true;
|
|
|
|
|
|
|
|
|
|
|
|
+ }
|
|
|
+ else if (analysisResult.Action == Actions.TriggerMessage.ToString())
|
|
|
+ {
|
|
|
+ confirmed = true;
|
|
|
}
|
|
|
else
|
|
|
{
|
|
@@ -703,10 +954,13 @@ namespace EVCB_OCPP.WSServer
|
|
|
|
|
|
private void RemoveClient(ClientData session)
|
|
|
{
|
|
|
- logger.Trace("RemoveClient" + session.ChargeBoxId);
|
|
|
- RemoveClientDic(session);
|
|
|
+ Console.WriteLine("*********");
|
|
|
+
|
|
|
if (session != null)
|
|
|
{
|
|
|
+
|
|
|
+ logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
|
|
|
+ RemoveClientDic(session);
|
|
|
try
|
|
|
{
|
|
|
session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
|
|
@@ -728,35 +982,59 @@ namespace EVCB_OCPP.WSServer
|
|
|
|
|
|
private void RemoveClientDic(ClientData session)
|
|
|
{
|
|
|
- lock (_lockClientDic)
|
|
|
+ if (!string.IsNullOrEmpty(session.ChargeBoxId))
|
|
|
{
|
|
|
- if (ClientDic.ContainsKey(session.ChargeBoxId))
|
|
|
+ lock (_lockClientDic)
|
|
|
{
|
|
|
- ClientDic.Remove(session.ChargeBoxId);
|
|
|
- logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
|
|
|
+
|
|
|
+ if (ClientDic.ContainsKey(session.ChargeBoxId))
|
|
|
+ {
|
|
|
+ ClientDic.Remove(session.ChargeBoxId);
|
|
|
+ logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
|
|
|
+ }
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
}
|
|
|
|
|
|
- private void WriteMachineLog(string sn, string data, string messageType, string errorMsg = "")
|
|
|
+ private void WarmUpLog()
|
|
|
{
|
|
|
|
|
|
- using (var db = new ConnectionLogDBContext())
|
|
|
+ using (var log = new ConnectionLogDBContext())
|
|
|
{
|
|
|
- string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
|
|
|
- "@ChargeBoxId,@MessageType,@Data,@Msg";
|
|
|
- var dd = DateTime.Now.AddDays(-1);
|
|
|
- SqlParameter[] parameter =
|
|
|
+ log.MachineConnectionLog.ToList();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void WriteMachineLog(string sn, string data, string messageType, string errorMsg = "", bool isSent = false)
|
|
|
+ {
|
|
|
+ try
|
|
|
+ {
|
|
|
+ if (string.IsNullOrEmpty(sn) || string.IsNullOrEmpty(data)) return;
|
|
|
+ using (var db = new ConnectionLogDBContext())
|
|
|
{
|
|
|
+ string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
|
|
|
+ "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent";
|
|
|
+ var dd = DateTime.Now;
|
|
|
+ SqlParameter[] parameter =
|
|
|
+ {
|
|
|
new SqlParameter("CreatedOn",dd),
|
|
|
new SqlParameter("ChargeBoxId",sn.Replace("'","''")),
|
|
|
new SqlParameter("MessageType",messageType.Replace("'","''")),
|
|
|
new SqlParameter("Data",data.Replace("'","''")),
|
|
|
- new SqlParameter("Msg",errorMsg.Replace("'","''"))
|
|
|
+ new SqlParameter("Msg",errorMsg.Replace("'","''")),
|
|
|
+ new SqlParameter("IsSent",isSent)
|
|
|
};
|
|
|
|
|
|
- db.Database.ExecuteSqlCommand(sp, parameter);
|
|
|
+ db.Database.ExecuteSqlCommand(sp, parameter);
|
|
|
+ }
|
|
|
}
|
|
|
+ catch (Exception ex)
|
|
|
+ {
|
|
|
+ Console.WriteLine(ex.ToString());
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
}
|
|
|
}
|
|
|
}
|