Esempio n. 1
0
        private void HandleConfigRequest(string ipPort, DeviceConfiguration configuration)
        {
            string name = configuration.RequestorIdentification;

            // if message is invalid - throw
            if (!ValidateMessages || configuration.IsValid(out var ex))
            {
                // notify message
                MessageReceived?.BeginInvoke(configuration, name, null, null);

                if (_marsClients.ContainsKey(name) == false)
                {
                    _marsClients.Add(name, new MrsClient
                    {
                        LastConnectionTime = DateTime.Now,
                        IPPort             = ipPort
                    });
                }
                else
                {
                    // if client is already registered - update values
                    _marsClients[name].LastConnectionTime = DateTime.Now;
                    _marsClients[name].IPPort             = ipPort;
                }

                _socket.SendAsync(_marsClients[name].IPPort, Configuration.ToXml());
            }
            else
            {
                ValidationErrorOccured?.BeginInvoke(this, new InvalidMessageException(configuration, ex), null, null);
            }
        }
        /// <summary>
        /// when Client Try to connect server
        /// </summary>
        /// <param name="o"></param>
        private void Acceptor(IAsyncResult o)
        {
            TcpListener server = o.AsyncState as TcpListener;

            try
            {
                PLCClient newClient = new PLCClient();
                newClient.NetWork = server.EndAcceptTcpClient(o);
                lstClient.Add(newClient);
                LogerHelper2.ToLog("Robot PLC " + newClient.Name + " is connected now.", 0);
                RobotPLCStatus.UpdateRobotPLCStatus("Connected");
                isPLConLine = true;
                newClient.NetWork.GetStream().BeginRead(newClient.buffer, 0, newClient.buffer.Length, new AsyncCallback(TCPCallBack), newClient);
                server.BeginAcceptTcpClient(new AsyncCallback(Acceptor), server);//continue listening

                //send F999 to active PLC QueryMessageListAndRunFirstMessage("DUTSTATUS");
                byte[] tempdata = Encoding.ASCII.GetBytes("F999");
                MessageReceived.BeginInvoke("", MainPLCMessage.ConvertByteToMessage(tempdata), null, null);//async data output
                //Server. QueryMessageListAndRunFirstMessage("DUTSTATUS");
            }
            catch (Exception ex)
            {
                LogerHelper2.ToLog("test method PLCServers.Acceptor catch exception" + ex.Message, 3);
            }
        }
Esempio n. 3
0
        internal void HandleCommandMessageRequest(CommandMessage request)
        {
            if (request == null)
            {
                return;
            }

            string deviceName = request.RequestorIdentification;

            // update last connection time
            if (_marsClients.ContainsKey(deviceName))
            {
                _marsClients[deviceName].LastConnectionTime = DateTime.Now;

                // raise the event
                MessageReceived?.BeginInvoke(request, deviceName, null, null);

                // answer with empty status report
                SendEmptyDeviceStatusReport(deviceName);
            }
            else
            {
                Console.WriteLine($"Unknown mars name ({deviceName})");
            }
        }
Esempio n. 4
0
        private void HandleSubscriptionRequest(DeviceSubscriptionConfiguration subscription)
        {
            string name = subscription.RequestorIdentification;

            // if message is invalid - throw
            if (!ValidateMessages || subscription.IsValid(out var ex))
            {
                // notify message
                MessageReceived?.BeginInvoke(subscription, name, null, null);

                // if client is registered
                if (!ValidateClients || _marsClients.ContainsKey(name))
                {
                    // if subscription has any values
                    if (subscription.SubscriptionType != null && subscription.SubscriptionType.Length > 0)
                    {
                        _marsClients[name].LastConnectionTime = DateTime.Now;
                        _marsClients[name].SubscriptionTypes  = subscription.SubscriptionType;
                        SendFullDeviceStatusReport(name);
                    }
                    else
                    {
                        // unsubscribe
                        _marsClients.Remove(name);
                    }
                }
            }
            else
            {
                ValidationErrorOccured?.BeginInvoke(this, new InvalidMessageException(subscription, ex), null, null);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// callback method
        /// </summary>
        /// <param name="ar"></param>
        private void TCPCallBack(IAsyncResult ar)
        {
            TCPIPClient client = (TCPIPClient)ar.AsyncState;

            if (client.NetWork.Connected)
            {
                try
                {
                    NetworkStream ns             = client.NetWork.GetStream();
                    byte[]        recdata        = new byte[ns.EndRead(ar)];
                    string        receivedstring = (new ASCIIEncoding().GetString(client.buffer));
                    receivedstring = receivedstring.Substring(0, recdata.Length);
                    if (recdata.Length > 0)
                    {
                        if (receivedstring.Contains("\r\n"))
                        {
                            string[] recdataArray = receivedstring.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                            for (int i = 0; i < recdataArray.Length; i++)
                            {
                                if (MessageReceived != null)
                                {
                                    MessageReceived.BeginInvoke(client.Name, Message.ConvertStringToMessage(recdataArray[i]), null, null);//async output data
                                }
                            }
                            ns.BeginRead(client.buffer, 0, client.buffer.Length, new AsyncCallback(TCPCallBack), client);
                        }
                        else
                        {
                            Array.Copy(client.buffer, recdata, recdata.Length);
                            if (MessageReceived != null)
                            {
                                MessageReceived.BeginInvoke(client.Name, Message.ConvertByteToMessage(recdata), null, null);//async output data
                            }
                            ns.BeginRead(client.buffer, 0, client.buffer.Length, new AsyncCallback(TCPCallBack), client);
                        }
                    }
                    else
                    {
                        client.Disconnect();
                        LogerHelper2.ToLog("client :" + client.Name + " is disconnect from server", 2);
                        client.isClientOnline = false;
                        CommonMethod.ShowClientOffLine(client.Name);
                        lstClient.Remove(client);
                    }
                }
                catch (Exception ex)
                {
                    client.Disconnect();
                    LogerHelper2.ToLog(ex.Message + "client :" + client.Name + " is disconnect from server", 3);
                    client.isClientOnline = false;
                    CommonMethod.ShowClientOffLine(client.Name);
                    lstClient.Remove(client);
                }
            }
        }
Esempio n. 6
0
        internal void HandleConfigRequest(DeviceConfiguration request)
        {
            if (request == null)
            {
                return;
            }

            // if this is not config request
            if (request.MessageTypeSpecified == false ||
                request.MessageType != MessageType.Request)
            {
                return;
            }

            // get mars details
            string marsIp   = request.NotificationServiceIPAddress;
            string marsPort = request.NotificationServicePort;
            string marsName = request.RequestorIdentification;

            // save this client under the mars name for future use
            if (_marsClients.ContainsKey(marsName))
            {
                _marsClients[marsName].LastConnectionTime = DateTime.Now;
            }
            else
            {
                // open sensor client for this mars
                EndpointAddress        address    = new EndpointAddress($"http://{marsIp}:{marsPort}/SNSR_STD-SOAP");
                SNSR_STDSOAPPortClient soapClient = new SNSR_STDSOAPPortClient(CreateBindingConfig(), address);
                MarsClient             client     = new MarsClient
                {
                    IP   = marsIp,
                    Port = int.Parse(marsPort),
                    LastConnectionTime = DateTime.Now,
                    SoapClient         = soapClient,
                };

                lock (_syncToken)
                {
                    _marsClients.Add(marsName, client);
                }

                // open the client
                soapClient.Open();
            }

            MessageReceived?.BeginInvoke(request, request.RequestorIdentification, null, null);

            // send device config
            SendDeviceConfig(marsName);
        }
Esempio n. 7
0
 private static void ListenMessage()
 {
     // 백그라운드에서 서버로부터 데이터를 받아 전달
     using (var pipe = new NamedPipeClientStream(".", "osu!Lyrics", PipeDirection.In, PipeOptions.None))
         using (var sr = new StreamReader(pipe, Encoding.Unicode))
         {
             pipe.Connect();
             while (pipe.IsConnected && !sr.EndOfStream)
             {
                 var e = new MessageReceivedEventArgs(sr.ReadLine());
                 MessageReceived?.BeginInvoke(null, e, null, null);
             }
         }
 }
Esempio n. 8
0
 private void ReadWorker()
 {
     while (!_cancellation.IsCancellationRequested)
     {
         lock (_locker)
         {
             var data = TryReceiveCommand(1);
             if (data != null)
             {
                 MessageReceived?.BeginInvoke(this, data, null, null);
             }
         }
     }
 }
Esempio n. 9
0
        internal void HandleSubscriptionRequest(DeviceSubscriptionConfiguration request)
        {
            if (request == null)
            {
                return;
            }

            // get requestor name
            string name = request.RequestorIdentification;

            SubscriptionTypeType[] subscribeTypes = request.SubscriptionType;

            // add mars name to subscribed list
            if (_marsClients.ContainsKey(name))
            {
                // update connection watch to this mars
                _marsClients[name].LastConnectionTime = DateTime.Now;

                // if unsubscribe request
                if (subscribeTypes == null || subscribeTypes.Length == 0)
                {
                    lock (_syncToken)
                    {
                        _marsClients.Remove(name);
                    }
                }
                else
                {
                    _marsClients[name].SubscriptionTypes = subscribeTypes;
                }

                // raise the event
                MessageReceived?.BeginInvoke(request, name, null, null);

                // send full status report for the first time
                SendFullDeviceStatusReport(name);
            }
            else
            {
                Console.WriteLine($"Unknown Mars name ({name})");
            }
        }
Esempio n. 10
0
        private void SocketRead(IAsyncResult r)
        {
            var srs = r.AsyncState as SocketReadState;

            if (r.IsCompleted)
            {
                var bytes = srs.Socket.EndReceive(r);
                if (bytes > 0)
                {
                    var data = new byte[bytes];
                    Array.Copy(srs.Data, data, bytes);
                    MessageReceived?.BeginInvoke(this, new PipeMessageReceivedEventArgs(new SocketWriter(srs.Socket), data), null, null);
                }
                else if (bytes == 0)
                {
                    srs.Active = false;
                }
            }
            srs.WaitHandle.Set();
        }
Esempio n. 11
0
        private void ReadLoop(Socket s)
        {
            var buffer = new byte[1024 * 16];
            var read   = true;

            while (_active && s.Connected && read)
            {
                var bytes = s.Receive(buffer);
                if (bytes > 0)
                {
                    var data = new byte[bytes];
                    Array.Copy(buffer, data, bytes);
                    MessageReceived?.BeginInvoke(this, new PipeMessageReceivedEventArgs(new SocketWriter(s), data), null, null);
                }
                else if (bytes == 0)
                {
                    read = false;
                }
            }
        }
Esempio n. 12
0
        /// <summary>
        /// 异步接收数据回调方法
        /// </summary>
        /// <param name="ar"></param>
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                int real_received = _socket.EndReceive(ar);
                if (real_received != 0)
                {
                    ZDataBuffer databuffer = GetDataBuffer();
                    byte[]      uncomplete = ar.AsyncState as byte[]; //上次未处理完的数据
                    if (uncomplete != null)
                    {
                        databuffer.WriteBytes(uncomplete, 0, uncomplete.Length); //将上次未处理完的数据重新写入缓冲区
                    }
                    databuffer.WriteBytes(_buffer_received, 0, real_received);   //将本次接收到的数据写入缓冲区

                    ZMessage message = null;
                    while ((message = databuffer.TryReadMessage()) != null)  //尝试从缓冲区中读取一条完整消息
                    {
                        if (MessageReceived != null)
                        {
                            MessageReceived.BeginInvoke(this, message, null, null);  //异步激发事件
                        }
                    }
                    _socket.BeginReceive(_buffer_received, 0, 1024, SocketFlags.None, new AsyncCallback(OnReceive), databuffer.UnCompelete);  //将未处理完的数据存放在state参数中,并开始下一次异步接收数据
                }
                else
                {
                    if (DisConnected != null)
                    {
                        DisConnected(this);
                    }
                }
            }
            catch
            {
                if (DisConnected != null)
                {
                    DisConnected(this);
                }
            }
        }
Esempio n. 13
0
 /// <summary>
 /// Callback
 /// </summary>
 /// <param name="ar"></param>
 private void TCPCallBack(IAsyncResult ar)
 {
     try
     {
         TCPIPClient client = (TCPIPClient)ar.AsyncState;
         if (client.NetWork.Connected)
         {
             NetworkStream ns      = client.NetWork.GetStream();
             byte[]        recdata = new byte[ns.EndRead(ar)];
             Array.Copy(client.buffer, recdata, recdata.Length);
             if (recdata.Length > 0)
             {
                 if (MessageReceived != null)
                 {
                     string[] temp = Encoding.ASCII.GetString(recdata).Split('\n');
                     foreach (string item in temp)
                     {
                         if (item != "")
                         {
                             MessageReceived.BeginInvoke(client.Name, Message.ConvertStringToMessage(item), null, null);//Async call back
                         }
                     }
                 }
                 ns.BeginRead(client.buffer, 0, client.buffer.Length, new AsyncCallback(TCPCallBack), client);
             }
             else
             {
                 IsConnected = false;
                 client.Disconnect();
                 //ServerConnected(client, false);
                 //    lstClient.Remove(client);
                 //    BindLstClient();
             }
         }
     }
     catch (Exception e)
     {
         LogerHelper2.ToLog("Exception in Connection TCPCallBack:\r\n" + e.Message, 3);
     }
 }
        /// <summary>
        /// PLC Client send message to server
        /// </summary>
        /// <param name="ar"></param>
        private void TCPCallBack(IAsyncResult ar)
        {
            PLCClient client = (PLCClient)ar.AsyncState;

            try
            {
                if (client.NetWork.Connected)
                {
                    NetworkStream ns      = client.NetWork.GetStream();
                    byte[]        recdata = new byte[ns.EndRead(ar)];
                    if (recdata.Length > 0)
                    {
                        Array.Copy(client.buffer, recdata, recdata.Length);
                        if (MessageReceived != null)
                        {
                            MessageReceived.BeginInvoke(client.Name, MainPLCMessage.ConvertByteToMessage(recdata), null, null);//async data output
                        }
                        ns.BeginRead(client.buffer, 0, client.buffer.Length, new AsyncCallback(TCPCallBack), client);
                    }
                    else
                    {
                        client.DisConnect();
                        LogerHelper2.ToLog("plc is disconnected now", 2);
                        plcHeartBeatTimer.Stop();
                        RobotPLCStatus.UpdateRobotPLCStatus("Disconnected");
                        isPLConLine = false;
                        lstClient.Remove(client);
                    }
                }
            }
            catch (Exception ex)
            {
                LogerHelper2.ToLog("testmothod TCPCallBack catch exception " + ex.Message, 3);
                RobotPLCStatus.UpdateRobotPLCStatus("Disconnected");
                plcHeartBeatTimer.Stop();
                client.DisConnect();
                isPLConLine = false;
                lstClient.Remove(client);
            }
        }
Esempio n. 15
0
        private void Run(object args)
        {
            var read = true;
            var pts  = (PipeThreadState)args;
            NamedPipeServerStream server;

            server = new NamedPipeServerStream(_name, PipeDirection.InOut, Threads, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

            pts.Server = server;

            try
            {
                server.WaitForConnection();

                while (_active && server.IsConnected && read)
                {
                    var buffer = new byte[BufferSize];
                    var bytes  = server.Read(buffer, 0, buffer.Length);

                    if (bytes > 0)
                    {
                        var data = new byte[bytes];
                        Array.Copy(buffer, data, bytes);
                        if (MessageReceived != null)
                        {
                            MessageReceived.BeginInvoke(this, new PipeMessageReceivedEventArgs(new PipeWriter(server), data), null, null);
                        }
                    }
                    else if (bytes == 0)
                    {
                        read = false;
                    }
                }
            }
            catch (IOException)
            {
            }

            ThreadClosed(pts);
        }
Esempio n. 16
0
        private void HandleCommandMessage(CommandMessage commandMessage)
        {
            string name = commandMessage.RequestorIdentification;

            // if message is invalid - throw
            if (!ValidateMessages || commandMessage.IsValid(out var ex))
            {
                // notify message
                MessageReceived?.BeginInvoke(commandMessage, name, null, null);

                // if client is registered
                if (!ValidateClients || _marsClients.ContainsKey(name))
                {
                    _marsClients[name].LastConnectionTime = DateTime.Now;
                    SendEmptyDeviceStatusReport(name);
                }
            }
            else
            {
                ValidationErrorOccured?.BeginInvoke(this, new InvalidMessageException(commandMessage, ex), null, null);
            }
        }
Esempio n. 17
0
 void DoRead()
 {
     using (var pipeReader = new StreamReader(_readPipeServerStream))
     {
         while (!_stop)
         {
             try
             {
                 var msg = pipeReader.ReadLine();
                 if (!string.IsNullOrWhiteSpace(msg))
                 {
                     MessageReceived?.BeginInvoke(msg, null, null);
                 }
                 Thread.Sleep(10);
             }
             catch (Exception exception)
             {
                 Trace.TraceError("[[MSP-SERVER-R]]" + exception);
             }
         }
     }
 }
Esempio n. 18
0
 protected void OnMessageReceived(SensorEventArgs args)
 {
     MessageReceived?.BeginInvoke(this, args, null, null);
 }