예제 #1
0
        bool UpdateRegisterInfo(School school, DuplexMessage commandMessage)
        {
            var registerOk   = false;
            var registerInfo = commandMessage.GetContent <RegisterInfo>();

            if (registerInfo != null)
            {
                school.ClientPubKey = registerInfo.ClientPubKey;
                school.UniqueToken  = registerInfo.ClientMacAddr;
                metaRepository.AddOrUpdateSchool(school, (updateOk) =>
                {
                    DuplexMessage resultMessage;
                    if (updateOk)
                    {
                        resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage);
                    }
                    else
                    {
                        resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage, ErrorCode.RegisterFailed);
                    }

                    Return(resultMessage);
                });
                registerOk = true;
            }
            return(registerOk);
        }
예제 #2
0
        protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
        {
            DuplexMessage resultMessage = null;
            var           school        = metaRepository
                                          .GetAllSchools()
                                          .ByIdentifier(commandMessage.Header.Identifier);

            if (school != null)
            {
                if (UpdateRegisterInfo(school, commandMessage))
                {
                    resultMessage = DuplexMessage.CreateAckMessage(commandMessage);
                }
                else
                {
                    resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage, ErrorCode.RegisterFailed);
                }
            }
            else
            {
                resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage, ErrorCode.RegisterFailed);
            }

            return(resultMessage);
        }
예제 #3
0
        protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
        {
            Log.Error(ErrorCode.BadProtocalVersion, new Exception("error"));
            var content = commandMessage.GetContent <Customer>();

            return(DuplexMessage.CreateCallbackMessage(commandMessage, content));
        }
예제 #4
0
파일: BadRequest.cs 프로젝트: zesus19/c5.v1
 protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
 {
     return(DuplexMessage.CreateAckMessage(commandMessage,
                                           commandMessage.Header.ErrorCode == ErrorCode.NoError
         ? ErrorCode.BadRequest
         : commandMessage.Header.ErrorCode));
 }
        void IUniversalDuplexContract.SendToService(DuplexMessage msg)
        {
            //We get here when we receive a message from a client

            IUniversalDuplexCallbackContract ch = OperationContext.Current.GetCallbackChannel <IUniversalDuplexCallbackContract>();
            string session = OperationContext.Current.Channel.SessionId;

            //Any message from a client we haven't seen before causes the new client to be added to our list
            //(Basically, treated as a "Connect" message)
            lock (syncRoot)
            {
                if (!clients.ContainsKey(session))
                {
                    clients.Add(session, ch);
                    OperationContext.Current.Channel.Closing += new EventHandler(Channel_Closing);
                    OperationContext.Current.Channel.Faulted += new EventHandler(Channel_Faulted);
                    OnConnected(session);
                }
            }

            //If it's a Disconnect message, treat as disconnection
            if (msg is DisconnectMessage)
            {
                ClientDisconnected(session);
            }
            //Otherwise, if it's a payload-carrying message (and not just a simple "Connect"), process it
            else if (!(msg is ConnectMessage))
            {
                OnMessage(session, msg);
            }
        }
예제 #6
0
파일: BadRequest.cs 프로젝트: zesus19/c5.v1
 protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
 {
     return DuplexMessage.CreateAckMessage(commandMessage, 
         commandMessage.Header.ErrorCode == ErrorCode.NoError 
         ? ErrorCode.BadRequest 
         : commandMessage.Header.ErrorCode);
 }
 /// <summary>
 /// Pushes a message to all connected clients
 /// </summary>
 /// <param name="message">The message to push</param>
 protected void PushToAllClients(DuplexMessage message)
 {
     lock (syncRoot)
     {
         foreach (string session in clients.Keys)
         {
             PushMessageToClient(session, message);
         }
     }
 }
예제 #8
0
 protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
 {
     var instruction = BuildInstruction(commandMessage);
     if (instruction != null)
     {
         instructionProducer.Produce(instruction);
         return DuplexMessage.CreateAckMessage(commandMessage);
     }
     else return DuplexMessage.CreateAckMessage(commandMessage, ErrorCode.InstructionBuildFailed);
 }
예제 #9
0
 public override DuplexMessage Run(int timeout = AbstractAsyncCommand.BLOCK_UNTIL_TIMEOUT_AFTER_SECONDS * 1000)
 {
     DisableRetry();
     RunAsync();
     if (!semaphore.Wait(timeout))
     {
         result = DuplexMessage.CreateAckMessage(ID, Version, CommandCode, ErrorCode.CommandRunTimeout);
         semaphore.Dispose();
     }
     return(result);
 }
예제 #10
0
 public override DuplexMessage Run(int timeout = AbstractAsyncCommand.BLOCK_UNTIL_TIMEOUT_AFTER_SECONDS * 1000)
 {
     DisableRetry();
     RunAsync();
     if (!semaphore.Wait(timeout))
     {
         result = DuplexMessage.CreateAckMessage(ID, Version, CommandCode, ErrorCode.CommandRunTimeout);
         semaphore.Dispose();
     }
     return result;
 }
예제 #11
0
 protected override IInstruction BuildInstruction(DuplexMessage commandMessage)
 {
     var instrSet = new InstructionSet(this);
     using (var scope = ObjectHost.Host.BeginLifetimeScope())
     {
         instrSet.AddInstruction(scope.Resolve<CheckInQueryInstruction>(
             new NamedParameter("command", this),
             new NamedParameter("parameter", commandMessage.GetContent<object>())));
         instrSet.AddInstruction(scope.Resolve<CheckInReplyInstruction>(
             new NamedParameter("parameter", commandMessage.GetContent<object>())));
     }
     return instrSet;
 }
예제 #12
0
        /// <summary>
        /// Pushes a message to one specific client
        /// </summary>
        /// <param name="clientSessionId">Session ID of the client that should receive the message</param>
        /// <param name="message">The message to push</param>
        protected void PushMessageToClient(string clientSessionId, DuplexMessage message)
        {
            if (clients != null && clients.ContainsKey(clientSessionId))
            {
                IUniversalDuplexCallbackContract ch = clients[clientSessionId];

                IAsyncResult iar = ch.BeginSendToClient(message, new AsyncCallback(OnPushMessageComplete), new PushMessageState(ch, clientSessionId));
                if (iar.CompletedSynchronously)
                {
                    CompletePushMessage(iar);
                }
            }
        }
예제 #13
0
        protected override IInstruction BuildInstruction(DuplexMessage commandMessage)
        {
            var instrSet = new InstructionSet(this);

            using (var scope = ObjectHost.Host.BeginLifetimeScope())
            {
                instrSet.AddInstruction(scope.Resolve <CheckInQueryInstruction>(
                                            new NamedParameter("command", this),
                                            new NamedParameter("parameter", commandMessage.GetContent <object>())));
                instrSet.AddInstruction(scope.Resolve <CheckInReplyInstruction>(
                                            new NamedParameter("parameter", commandMessage.GetContent <object>())));
            }
            return(instrSet);
        }
예제 #14
0
        protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
        {
            var instruction = BuildInstruction(commandMessage);

            if (instruction != null)
            {
                instructionProducer.Produce(instruction);
                return(DuplexMessage.CreateAckMessage(commandMessage));
            }
            else
            {
                return(DuplexMessage.CreateAckMessage(commandMessage, ErrorCode.InstructionBuildFailed));
            }
        }
예제 #15
0
        /// <summary>
        /// Pushes a message to one specific client
        /// </summary>
        /// <param name="clientSessionId">Session ID of the client that should receive the message</param>
        /// <param name="message">The message to push</param>
        protected void PushMessageToClient(string clientSessionId, DuplexMessage message)
        {
            try         //try to send message to client if it is still connected. Otherwise dont worry about it.
            {
                IUniversalDuplexCallbackContract ch = (clients[clientSessionId]).Channel;

                IAsyncResult iar = ch.BeginSendToClient(message, new AsyncCallback(OnPushMessageComplete), new PushMessageState(ch, clientSessionId));
                if (iar.CompletedSynchronously)
                {
                    CompletePushMessage(iar);
                }
            }
            catch
            {
            }
        }
예제 #16
0
        protected void PushServiceStatusToClients(string nodeID, DuplexMessage message)
        {
            Dictionary <string, Client> clientsList;

            lock (clients)
            {
                clientsList = new Dictionary <string, Client>(clients);  // we will take a copy of the global collection locally to avoid locking of the resource.
            }

            foreach (string session in clientsList.Keys)
            {
                if (clientsList[session].CurrentDisplayType == DisplayType.ServiceClient && clientsList[session].NodeID == nodeID)
                {
                    PushMessageToClient(session, message);
                }
            }
        }
예제 #17
0
파일: Register.cs 프로젝트: zesus19/c5.v1
        protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
        {
            DuplexMessage resultMessage = null;
            var school = metaRepository
                .GetAllSchools()
                .ByIdentifier(commandMessage.Header.Identifier);

            if (school != null)
            {
                if (UpdateRegisterInfo(school, commandMessage))
                    resultMessage = DuplexMessage.CreateAckMessage(commandMessage);
                else
                   resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage, ErrorCode.RegisterFailed);
            }
            else
                resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage, ErrorCode.RegisterFailed);

            return resultMessage;
        }
예제 #18
0
 public void Execute()
 {
     new Task(() =>
     {
         while (true)
         {
             foreach (var hardware in hardwareRepository
                      .GetHardwares(LOCAL_SCHOOL_ID))
             {
                 base.Execute(null, DuplexMessage.CreateCommandMessage(
                                  string.Empty,
                                  MessageVersion.V1,
                                  CommandCode.Test,
                                  Rpc.Net.Message.Filter.MessageFilterType.None,
                                  new byte[0],
                                  Rpc.Net.Message.Serializer.SerializeMode.None,
                                  new { DestinationAddr = hardware.Address }));
                 are.WaitOne(500);
             }
         }
     }).Start();
 }
예제 #19
0
파일: Register.cs 프로젝트: zesus19/c5.v1
        bool UpdateRegisterInfo(School school, DuplexMessage commandMessage)
        {
            var registerOk = false;
            var registerInfo = commandMessage.GetContent<RegisterInfo>();
            if (registerInfo != null)
            {
                school.ClientPubKey = registerInfo.ClientPubKey;
                school.UniqueToken = registerInfo.ClientMacAddr;
                metaRepository.AddOrUpdateSchool(school, (updateOk) =>
                {
                    DuplexMessage resultMessage;
                    if (updateOk)
                        resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage);
                    else
                        resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage, ErrorCode.RegisterFailed);

                    Return(resultMessage);
                });
                registerOk = true;
            }
            return registerOk;
        }
예제 #20
0
 protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
 {
     IoSession session = null;
     DuplexMessage resultMessage = null;
     if (identifierManager.TryGetSessonIdByIdentifier(commandMessage.Header.Identifier, out session))
     {
         var connectors = session.Service
             .ManagedSessions
             .Values
             .Where(s => s.Id != session.Id)
             .Select(s => s.GetAttribute<string>(KeyName.SESSION_IDENTIFIER))
             .ToList();
         resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage, connectors);
         resultMessage.Header.FilterType |= MessageFilterType.Crypto;
         resultMessage.Header.SerializeMode = Rpc.Net.Message.Serializer.SerializeMode.Json;
     }
     else
     {
         resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage);
     }
     return resultMessage;
 }
예제 #21
0
        protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
        {
            IoSession     session       = null;
            DuplexMessage resultMessage = null;

            if (identifierManager.TryGetSessonIdByIdentifier(commandMessage.Header.Identifier, out session))
            {
                var connectors = session.Service
                                 .ManagedSessions
                                 .Values
                                 .Where(s => s.Id != session.Id)
                                 .Select(s => s.GetAttribute <string>(KeyName.SESSION_IDENTIFIER))
                                 .ToList();
                resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage, connectors);
                resultMessage.Header.FilterType   |= MessageFilterType.Crypto;
                resultMessage.Header.SerializeMode = Rpc.Net.Message.Serializer.SerializeMode.Json;
            }
            else
            {
                resultMessage = DuplexMessage.CreateCallbackMessage(commandMessage);
            }
            return(resultMessage);
        }
예제 #22
0
 public object GetRequest(IoSession session)
 {
     return(DuplexMessage.CreateHeartbeat());
 }
예제 #23
0
 void BlockCommand_Callback(object sender, CommandEventArgs<DuplexMessage> e)
 {
     result = e.Message;
     semaphore.Release();
 }
예제 #24
0
 static CheckInQueryCommand()
 {
     message = DuplexMessage.CreateCommandMessage(string.Empty, MessageVersion.V1, CommandCode.Test);
 }
예제 #25
0
        protected void PushServiceStatusToClients(string nodeID, DuplexMessage message)
        {
            Dictionary<string, Client> clientsList;
            lock (clients)
            {
                clientsList = new Dictionary<string, Client>(clients);	// we will take a copy of the global collection locally to avoid locking of the resource.
            }

            foreach (string session in clientsList.Keys)
            {
                if (clientsList[session].CurrentDisplayType == DisplayType.ServiceClient && clientsList[session].NodeID == nodeID)
                    PushMessageToClient(session, message);
            }
        }
예제 #26
0
 void SendToService(DuplexMessage message)
 {
     m_duplexClient.SendToServiceAsync(message);
 }
예제 #27
0
 protected abstract IInstruction BuildInstruction(DuplexMessage commandMessage);
예제 #28
0
        public void SendToService(DuplexMessage msg)
        {
            //We get here when we receive a message from a client
            IUniversalDuplexCallbackContract ch = OperationContext.Current.GetCallbackChannel<IUniversalDuplexCallbackContract>();
            string session = OperationContext.Current.Channel.SessionId;

            if (msg is ConnectMessage)
            {
                //lock (syncRoot)
                lock (clients)
                {
                    if (!clients.ContainsKey(session))	// new client
                    {
                        System.Diagnostics.Debug.WriteLine("New client connected: ");
                        System.Diagnostics.Debug.WriteLine("          " + (msg as ConnectMessage).NodeID);
                        System.Diagnostics.Debug.WriteLine("          " + (msg as ConnectMessage).TimeSeriesDataRootUrl);
                        System.Diagnostics.Debug.WriteLine("          " + (msg as ConnectMessage).CurrentDisplayType.ToString());
                        Client client = new Client();
                        client.Channel = ch;
                        client.NodeID = (msg as ConnectMessage).NodeID;
                        client.TimeSeriesDataRootUrl = (msg as ConnectMessage).TimeSeriesDataRootUrl;
                        client.RealTimeStatisticRootUrl = (msg as ConnectMessage).RealTimeStatisticRootUrl;
                        client.DataPointID = (msg as ConnectMessage).DataPointID;
                        client.CurrentDisplayType = (msg as ConnectMessage).CurrentDisplayType;
                        clients.Add(session, client);
                        OperationContext.Current.Channel.Closing += Channel_Closing;
                        OperationContext.Current.Channel.Faulted += Channel_Faulted;
                        OnConnected(session);
                    }
                    else	//existing connected client. Just trying to update its settings.
                    {
                        clients[session] = new Client()
                        {
                            Channel = ch,
                            NodeID = (msg as ConnectMessage).NodeID,
                            DataPointID = (msg as ConnectMessage).DataPointID,
                            TimeSeriesDataRootUrl = (msg as ConnectMessage).TimeSeriesDataRootUrl,
                            RealTimeStatisticRootUrl = (msg as ConnectMessage).RealTimeStatisticRootUrl,
                            CurrentDisplayType = (msg as ConnectMessage).CurrentDisplayType
                        };
                    }
                }

                Client currentClient = clients[session];
                // Initially when client is connected, we will send them data only if client is connected from home page of the openPDCManager.
                if (currentClient.CurrentDisplayType == DisplayType.Home)
                {
                    PushMessageToClient(session, new LivePhasorDataMessage()
                                            {
                                                //PmuDistributionList = CommonFunctions.GetPmuDistribution(),
                                                DeviceDistributionList = CommonFunctions.GetVendorDeviceDistribution(null, currentClient.NodeID),
                                                InterconnectionStatusList = CommonFunctions.GetInterconnectionStatus(null, currentClient.NodeID)
                                            }
                                        );

                    PushMessageToClient(session, new TimeSeriesDataMessage()
                                                {
                                                    TimeSeriesData = CommonFunctions.GetTimeSeriesData(currentClient.TimeSeriesDataRootUrl + "/timeseriesdata/read/historic/" + currentClient.DataPointID.ToString() + "/*-30S/*/XML")
                                                    //TimeSeriesData = CommonFunctions.GetTimeSeriesData(currentClient.TimeSeriesDataRootUrl + "current/" + currentClient.DataPointID.ToString() + "/XML")
                                                }
                                            );
                }
                else if (currentClient.CurrentDisplayType == DisplayType.ServiceClient)
                {
                    if (serviceClientList.ContainsKey(currentClient.NodeID))
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Cached Status to Client Connected on System Monitor Page.");
                        PushMessageToClient(session, new ServiceUpdateMessage()
                                                {
                                                    ServiceUpdateType = UpdateType.Information,
                                                    ServiceUpdate = serviceClientList[currentClient.NodeID].CachedStatus
                                                });
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Empty Message to Client Connected on System Monitor Page.");
                        PushMessageToClient(session, new ServiceUpdateMessage());
                    }
                }
                else if (currentClient.CurrentDisplayType == DisplayType.DeviceMeasurements)
                {
                    KeyValuePair<int, int> minMaxPointID = minMaxPointIDsPerNode[currentClient.NodeID];
                    if (!string.IsNullOrEmpty(currentClient.TimeSeriesDataRootUrl))	// if TimeSeriesDataRootUrl is defined for the node, then only try to send data to client upon connection.
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Measurements to Client Connected on Device Measurements Page.");
                        PushMessageToClient(session, new TimeTaggedDataMessage()
                                                {
                                                    TimeTaggedMeasurements = CommonFunctions.GetTimeTaggedMeasurements(currentClient.TimeSeriesDataRootUrl + "/timeseriesdata/read/current/" + minMaxPointID.Key.ToString() + "-" + minMaxPointID.Value.ToString() + "/XML")
                                                });
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Empty Message to Client Connected on Device Measurements Page.");
                        PushMessageToClient(session, new TimeTaggedDataMessage());
                    }
                }
                else if (currentClient.CurrentDisplayType == DisplayType.RealTimeStatistics)
                {
                    KeyValuePair<int, int> minMaxPointID = minMaxPointIDsPerNode[currentClient.NodeID];
                    if (!string.IsNullOrEmpty(currentClient.TimeSeriesDataRootUrl))	// if TimeSeriesDataRootUrl is defined for the node, then only try to send data to client upon connection.
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Measurements to Client Connected on Device Measurements Page.");
                        PushMessageToClient(session, new TimeTaggedDataMessage()
                        {
                            TimeTaggedMeasurements = CommonFunctions.GetStatisticMeasurements(currentClient.RealTimeStatisticRootUrl + "/timeseriesdata/read/current/" + minMaxPointID.Key.ToString() + "-" + minMaxPointID.Value.ToString() + "/XML", currentClient.NodeID)
                        });
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Empty Message to Client Connected on Device Measurements Page.");
                        PushMessageToClient(session, new TimeTaggedDataMessage());
                    }
                }
            }
            else if (msg is ServiceRequestMessage)
            {
                SendServiceRequest(clients[session].NodeID, (msg as ServiceRequestMessage).Request);
            }
            else if (msg is DisconnectMessage) //If it's a Disconnect message, treat as disconnection
            {
                ClientDisconnected(session);

            }
            else		//if (!(msg is ConnectMessage)) //Otherwise, if it's a payload-carrying message (and not just a simple "Connect"), process it
            {
                OnMessage(session, msg);
            }
        }
예제 #29
0
 /// <summary>
 /// This will be called when a message is received from a client
 /// </summary>
 /// <param name="sessionId">Session ID of the client sending the message</param>
 /// <param name="message">The message that was received</param>
 protected virtual void OnMessage(string sessionId, DuplexMessage message)
 {
 }
예제 #30
0
 static CheckInQueryCommand()
 {
     message = DuplexMessage.CreateCommandMessage(string.Empty, MessageVersion.V1, CommandCode.Test);
 }
예제 #31
0
 /// <summary>
 /// This will be called when a message is received from a client
 /// </summary>
 /// <param name="sessionId">Session ID of the client sending the message</param>
 /// <param name="message">The message that was received</param>
 protected virtual void OnMessage(string sessionId, DuplexMessage message)
 {
 }
예제 #32
0
파일: Heartbeat.cs 프로젝트: zesus19/c5.v1
 protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
 {
     commandMessage.Header.MessageType = MessageType.Heartbeat;
     return(commandMessage);
 }
예제 #33
0
 protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
 {
     Log.Error(ErrorCode.BadProtocalVersion, new Exception("error"));
     var content = commandMessage.GetContent<Customer>();
     return DuplexMessage.CreateCallbackMessage(commandMessage, content);
 }
예제 #34
0
 void SendToService(DuplexMessage message)
 {
     m_duplexClient.SendToServiceAsync(message);
 }
예제 #35
0
파일: Heartbeat.cs 프로젝트: zesus19/c5.v1
 protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
 {
     commandMessage.Header.MessageType = MessageType.Heartbeat;
     return commandMessage;
 }
예제 #36
0
        public void SendToService(DuplexMessage msg)
        {
            //We get here when we receive a message from a client
            IUniversalDuplexCallbackContract ch = OperationContext.Current.GetCallbackChannel <IUniversalDuplexCallbackContract>();
            string session = OperationContext.Current.Channel.SessionId;

            if (msg is ConnectMessage)
            {
                //lock (syncRoot)
                lock (clients)
                {
                    if (!clients.ContainsKey(session))  // new client
                    {
                        System.Diagnostics.Debug.WriteLine("New client connected: ");
                        System.Diagnostics.Debug.WriteLine("          " + (msg as ConnectMessage).NodeID);
                        System.Diagnostics.Debug.WriteLine("          " + (msg as ConnectMessage).TimeSeriesDataRootUrl);
                        System.Diagnostics.Debug.WriteLine("          " + (msg as ConnectMessage).CurrentDisplayType.ToString());
                        Client client = new Client();
                        client.Channel = ch;
                        client.NodeID  = (msg as ConnectMessage).NodeID;
                        client.TimeSeriesDataRootUrl    = (msg as ConnectMessage).TimeSeriesDataRootUrl;
                        client.RealTimeStatisticRootUrl = (msg as ConnectMessage).RealTimeStatisticRootUrl;
                        client.DataPointID        = (msg as ConnectMessage).DataPointID;
                        client.CurrentDisplayType = (msg as ConnectMessage).CurrentDisplayType;
                        clients.Add(session, client);
                        OperationContext.Current.Channel.Closing += Channel_Closing;
                        OperationContext.Current.Channel.Faulted += Channel_Faulted;
                        OnConnected(session);
                    }
                    else        //existing connected client. Just trying to update its settings.
                    {
                        clients[session] = new Client()
                        {
                            Channel                  = ch,
                            NodeID                   = (msg as ConnectMessage).NodeID,
                            DataPointID              = (msg as ConnectMessage).DataPointID,
                            TimeSeriesDataRootUrl    = (msg as ConnectMessage).TimeSeriesDataRootUrl,
                            RealTimeStatisticRootUrl = (msg as ConnectMessage).RealTimeStatisticRootUrl,
                            CurrentDisplayType       = (msg as ConnectMessage).CurrentDisplayType
                        };
                    }
                }

                Client currentClient = clients[session];
                // Initially when client is connected, we will send them data only if client is connected from home page of the openPDCManager.
                if (currentClient.CurrentDisplayType == DisplayType.Home)
                {
                    PushMessageToClient(session, new LivePhasorDataMessage()
                    {
                        //PmuDistributionList = CommonFunctions.GetPmuDistribution(),
                        DeviceDistributionList    = CommonFunctions.GetVendorDeviceDistribution(null, currentClient.NodeID),
                        InterconnectionStatusList = CommonFunctions.GetInterconnectionStatus(null, currentClient.NodeID)
                    }
                                        );

                    PushMessageToClient(session, new TimeSeriesDataMessage()
                    {
                        TimeSeriesData = CommonFunctions.GetTimeSeriesData(currentClient.TimeSeriesDataRootUrl + "/timeseriesdata/read/historic/" + currentClient.DataPointID.ToString() + "/*-30S/*/XML")
                                         //TimeSeriesData = CommonFunctions.GetTimeSeriesData(currentClient.TimeSeriesDataRootUrl + "current/" + currentClient.DataPointID.ToString() + "/XML")
                    }
                                        );
                }
                else if (currentClient.CurrentDisplayType == DisplayType.ServiceClient)
                {
                    if (serviceClientList.ContainsKey(currentClient.NodeID))
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Cached Status to Client Connected on System Monitor Page.");
                        PushMessageToClient(session, new ServiceUpdateMessage()
                        {
                            ServiceUpdateType = UpdateType.Information,
                            ServiceUpdate     = serviceClientList[currentClient.NodeID].CachedStatus
                        });
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Empty Message to Client Connected on System Monitor Page.");
                        PushMessageToClient(session, new ServiceUpdateMessage());
                    }
                }
                else if (currentClient.CurrentDisplayType == DisplayType.DeviceMeasurements)
                {
                    KeyValuePair <int, int> minMaxPointID = minMaxPointIDsPerNode[currentClient.NodeID];
                    if (!string.IsNullOrEmpty(currentClient.TimeSeriesDataRootUrl))     // if TimeSeriesDataRootUrl is defined for the node, then only try to send data to client upon connection.
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Measurements to Client Connected on Device Measurements Page.");
                        PushMessageToClient(session, new TimeTaggedDataMessage()
                        {
                            TimeTaggedMeasurements = CommonFunctions.GetTimeTaggedMeasurements(currentClient.TimeSeriesDataRootUrl + "/timeseriesdata/read/current/" + minMaxPointID.Key.ToString() + "-" + minMaxPointID.Value.ToString() + "/XML")
                        });
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Empty Message to Client Connected on Device Measurements Page.");
                        PushMessageToClient(session, new TimeTaggedDataMessage());
                    }
                }
                else if (currentClient.CurrentDisplayType == DisplayType.RealTimeStatistics)
                {
                    KeyValuePair <int, int> minMaxPointID = minMaxPointIDsPerNode[currentClient.NodeID];
                    if (!string.IsNullOrEmpty(currentClient.TimeSeriesDataRootUrl))     // if TimeSeriesDataRootUrl is defined for the node, then only try to send data to client upon connection.
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Measurements to Client Connected on Device Measurements Page.");
                        PushMessageToClient(session, new TimeTaggedDataMessage()
                        {
                            TimeTaggedMeasurements = CommonFunctions.GetStatisticMeasurements(currentClient.RealTimeStatisticRootUrl + "/timeseriesdata/read/current/" + minMaxPointID.Key.ToString() + "-" + minMaxPointID.Value.ToString() + "/XML", currentClient.NodeID)
                        });
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Sending Empty Message to Client Connected on Device Measurements Page.");
                        PushMessageToClient(session, new TimeTaggedDataMessage());
                    }
                }
            }
            else if (msg is ServiceRequestMessage)
            {
                SendServiceRequest(clients[session].NodeID, (msg as ServiceRequestMessage).Request);
            }
            else if (msg is DisconnectMessage) //If it's a Disconnect message, treat as disconnection
            {
                ClientDisconnected(session);
            }
            else                //if (!(msg is ConnectMessage)) //Otherwise, if it's a payload-carrying message (and not just a simple "Connect"), process it
            {
                OnMessage(session, msg);
            }
        }
 public override void MessageReceived(INextFilter nextFilter, IoSession session, object message)
 {
     using (var scope = ObjectHost.Host.BeginLifetimeScope())
     {
         var commandMessage = message as DuplexMessage;
         if (commandMessage != null)
         {
             if (commandMessage.Header.CommandCode == CommandCode.Authentication)
             {
                 var school = metaRepository
                              .GetAllSchools()
                              .ByIdentifier(commandMessage.Header.Identifier);
                 if (school != null && school.UniqueToken.Equals(
                         commandMessage.GetContent <AuthInfo>().Mac, StringComparison.OrdinalIgnoreCase))
                 {
                     session.SetAttributeIfAbsent(KeyName.SESSION_IDENTIFIER, commandMessage.Header.Identifier);
                     identifierManager.SetSessonIdentifier(commandMessage.Header.Identifier, session);
                     nextFilter.FilterWrite(session,
                                            new DefaultWriteRequest(
                                                DuplexMessage.CreateCallbackMessage(commandMessage)));
                 }
                 else
                 {
                     nextFilter.FilterWrite(session,
                                            new DefaultWriteRequest(
                                                DuplexMessage.CreateAckMessage(commandMessage, ErrorCode.AuthenticationFailed)));
                 }
             }
             else if (
                 commandMessage.Header.CommandCode == CommandCode.Register ||
                 commandMessage.Header.CommandCode == CommandCode.Heartbeat)
             {
                 nextFilter.MessageReceived(session, message);
             }
             else
             {
                 if (!session.ContainsAttribute(KeyName.SESSION_IDENTIFIER))
                 {
                     nextFilter.FilterWrite(session, new DefaultWriteRequest(
                                                DuplexMessage.CreateAckMessage(commandMessage, ErrorCode.UnauthorizedCommand)));
                 }
                 else
                 {
                     var identifier = session.GetAttribute <string>(KeyName.SESSION_IDENTIFIER);
                     if (identifier.Equals(commandMessage.Header.Identifier))
                     {
                         nextFilter.MessageReceived(session, message);
                     }
                     else
                     {
                         nextFilter.FilterWrite(session, new DefaultWriteRequest(
                                                    DuplexMessage.CreateAckMessage(commandMessage, ErrorCode.UnauthorizedCommand)));
                     }
                 }
             }
         }
         else
         {
             nextFilter.FilterWrite(session, new DefaultWriteRequest(
                                        DuplexMessage.CreateAckMessage(
                                            Guid.NewGuid().ToByteArray().ToBase64(),
                                            MessageVersion.V1,
                                            CommandCode.UnAssigned,
                                            ErrorCode.IllegalCommandRequest)));
         }
     }
 }
예제 #38
0
        /// <summary>
        /// Pushes a message to one specific client
        /// </summary>
        /// <param name="clientSessionId">Session ID of the client that should receive the message</param>
        /// <param name="message">The message to push</param>
        protected void PushMessageToClient(string clientSessionId, DuplexMessage message)
        {
            try		//try to send message to client if it is still connected. Otherwise dont worry about it.
            {
                IUniversalDuplexCallbackContract ch = (clients[clientSessionId]).Channel;

                IAsyncResult iar = ch.BeginSendToClient(message, new AsyncCallback(OnPushMessageComplete), new PushMessageState(ch, clientSessionId));
                if (iar.CompletedSynchronously)
                {
                    CompletePushMessage(iar);
                }
            }
            catch
            {
            }
        }
예제 #39
0
 protected abstract IInstruction BuildInstruction(DuplexMessage commandMessage);
예제 #40
0
 void BlockCommand_Callback(object sender, CommandEventArgs <DuplexMessage> e)
 {
     result = e.Message;
     semaphore.Release();
 }