Exemplo n.º 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);
        }
Exemplo n.º 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);
        }
Exemplo n.º 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));
        }
Exemplo n.º 4
0
 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);
            }
        }
Exemplo n.º 6
0
 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);
         }
     }
 }
Exemplo n.º 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);
 }
Exemplo n.º 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);
 }
Exemplo n.º 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;
 }
Exemplo n.º 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;
 }
Exemplo n.º 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);
                }
            }
        }
Exemplo n.º 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);
        }
Exemplo n.º 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));
            }
        }
Exemplo n.º 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
            {
            }
        }
Exemplo n.º 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);
                }
            }
        }
Exemplo n.º 17
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;
        }
Exemplo n.º 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();
 }
Exemplo n.º 19
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;
        }
Exemplo n.º 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;
 }
Exemplo n.º 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);
        }
Exemplo n.º 22
0
 public object GetRequest(IoSession session)
 {
     return(DuplexMessage.CreateHeartbeat());
 }
Exemplo n.º 23
0
 void BlockCommand_Callback(object sender, CommandEventArgs<DuplexMessage> e)
 {
     result = e.Message;
     semaphore.Release();
 }
Exemplo n.º 24
0
 static CheckInQueryCommand()
 {
     message = DuplexMessage.CreateCommandMessage(string.Empty, MessageVersion.V1, CommandCode.Test);
 }
Exemplo n.º 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);
            }
        }
Exemplo n.º 26
0
 void SendToService(DuplexMessage message)
 {
     m_duplexClient.SendToServiceAsync(message);
 }
Exemplo n.º 27
0
 protected abstract IInstruction BuildInstruction(DuplexMessage commandMessage);
Exemplo n.º 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);
            }
        }
Exemplo n.º 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)
 {
 }
Exemplo n.º 30
0
 static CheckInQueryCommand()
 {
     message = DuplexMessage.CreateCommandMessage(string.Empty, MessageVersion.V1, CommandCode.Test);
 }
Exemplo n.º 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)
 {
 }
Exemplo n.º 32
0
 protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
 {
     commandMessage.Header.MessageType = MessageType.Heartbeat;
     return(commandMessage);
 }
Exemplo n.º 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);
 }
Exemplo n.º 34
0
 void SendToService(DuplexMessage message)
 {
     m_duplexClient.SendToServiceAsync(message);
 }
Exemplo n.º 35
0
 protected override DuplexMessage DoExecute(DuplexMessage commandMessage)
 {
     commandMessage.Header.MessageType = MessageType.Heartbeat;
     return commandMessage;
 }
Exemplo n.º 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);
            }
        }
Exemplo n.º 37
0
 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)));
         }
     }
 }
Exemplo n.º 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
            {
            }
        }
Exemplo n.º 39
0
 protected abstract IInstruction BuildInstruction(DuplexMessage commandMessage);
Exemplo n.º 40
0
 void BlockCommand_Callback(object sender, CommandEventArgs <DuplexMessage> e)
 {
     result = e.Message;
     semaphore.Release();
 }