Inheritance: IDatagramSocketMessageReceivedEventArgs
Exemple #1
0
        private void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            DataReader reader;
            try
            {
                reader = eventArguments.GetDataReader();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("MessageReceived:" + ex);
                return;
            }
            uint dataLength = reader.UnconsumedBufferLength;
            byte[] data = new byte[dataLength];
            reader.ReadBytes(data);

            var packet = new NavigationPacket
            {
                Timestamp = DateTime.UtcNow.Ticks,
                Data = data
            };
            UpdateNavigationData(packet);

            _TimeoutStopWatch.Restart();
        }
Exemple #2
0
    private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                              Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        Debug.Log("GOT MESSAGE: ");
        //Read the message that was received from the UDP echo client.
        Stream       streamIn = args.GetDataStream().AsStreamForRead();
        StreamReader reader   = new StreamReader(streamIn);
        string       message  = await reader.ReadLineAsync();

        Debug.Log("MESSAGE: " + message);
        //Debug.Log(message.Length + " " + message[message.Length - 1]);

        //Debug.Log(message[0].Equals('<'));
        //Debug.Log(message[message.Length - 1].Equals('>'));
        string[] values = message.Split(',');

        if (values.Length == 4)
        {
            rocket.SetOrientation(float.Parse(values[0]), float.Parse(values[1]), float.Parse(values[2]), float.Parse(values[3]));
        }
        else if (values.Length == 3)
        {
            rocket.SetOrientation(float.Parse(values[0]), float.Parse(values[1]), float.Parse(values[2]));
        }
    }
Exemple #3
0
        private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                                  Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            // 多重イベントを抑制
            //m_udp.MessageReceived -= Socket_MessageReceived;

            Stream       streamIn = args.GetDataStream().AsStreamForRead();
            StreamReader reader   = new StreamReader(streamIn);

            int port;

            Int32.TryParse(args.RemotePort, out port);

            ReceiveDataType r = new ReceiveDataType();

            try
            {
                r.data = await reader.ReadLineAsync();

                r.remoteIP = new IPEndPoint(IPAddress.Parse(args.RemoteAddress.ToString()), port);
                m_receivedData.Enqueue(r);
            } catch (Exception e)
            {
            }

            // イベント発生を許可
            //m_udp.MessageReceived += Socket_MessageReceived;
        }
Exemple #4
0
        private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                                  Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            // lock multi event
            socket.MessageReceived -= Socket_MessageReceived;

            //Debug.Log("OSCSERVER UWP  Socket_MessageReceived");

            //Read the message that was received from the UDP echo client.
            Stream streamIn = args.GetDataStream().AsStreamForRead();

            StreamReader reader = new StreamReader(streamIn);

            byte[] bytes = reader.CurrentEncoding.GetBytes(reader.ReadToEnd());

            streamIn.Dispose();
            reader.Dispose();

            OSCPacket packet = OSCPacket.Unpack(bytes);

            _lastReceivedPacket = packet;

            PacketReceivedEvent(this, _lastReceivedPacket);

            // unlock multi event
            socket.MessageReceived += Socket_MessageReceived;
        }
    private void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                        Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        Debug.Log("Datagram socket message received");

        //Read the message that was received from the UDP echo client.
        Stream streamIn = args.GetDataStream().AsStreamForRead();

        byte[] msg = ReadToEnd(streamIn);

        ArrayList messages = Osc.PacketToOscMessages(msg, msg.Length);

        foreach (OscMessage om in messages)
        {
            if (AllMessageHandler != null)
            {
                try
                {
                    AllMessageHandler(om);
                }
                catch (Exception e)
                {
                    Debug.Log(e.ToString());
                    return;
                }
            }
        }
    }
        async void datagramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            i++;
            DataReader dataReader = args.GetDataReader();
            uint length = dataReader.UnconsumedBufferLength;
            string content = dataReader.ReadString(length);
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            msgList.Children.Add(new TextBlock { Text = "服务器收到的消息:" + content }));

            //HostName hostName = new HostName("localhost");
            //DatagramSocket datagramSocket = new DatagramSocket();
            //IOutputStream outputStream = await datagramSocket.GetOutputStreamAsync(hostName, "22112");
            DataWriter writer = new DataWriter(sender.OutputStream);
            writer.WriteString(content + "|" + i);
            try
            {
                await writer.StoreAsync();
                msgList.Children.Add(new TextBlock { Text = "服务器发送的消息:" + content + "|" + i });
            }
            catch (Exception err)
            {
                if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
                {

                }
            }
        }
        private void SendResponse(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            var controllerSettings = _settingsService.GetSettings<ControllerSettings>();

            var response = new DiscoveryResponse(controllerSettings.Caption, controllerSettings.Description);
            SendResponseAsync(args.RemoteAddress, response).Wait();
        }
    private void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                        Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        //Debug.Log("GOT MESSAGE FROM: " + args.RemoteAddress.DisplayName);
        //Read the message that was received from the UDP  client.
        Stream       streamIn = args.GetDataStream().AsStreamForRead();
        MemoryStream ms       = ToMemoryStream(streamIn);

        byte[] msgData = ms.ToArray();

        /*
         *  if (ExecuteOnMainThread.Count == 0)
         *  {
         *      ExecuteOnMainThread.Enqueue(() =>
         *      {
         *          Debug.Log("ENQEUED ");
         *          if (udpEvent != null){
         *         Debug.Log("Call udp event.");
         *             udpEvent.Invoke(args.RemoteAddress.DisplayName, internalPort, msgData);
         *      }
         *      });
         *  }
         */

        //string dataString = System.Text.Encoding.UTF8.GetString (msgData);
        string dataString = string.Join(" ", msgData);

        //Debug.Log(dataString);
        if (textUpdater != null)
        {
            //Debug.Log("Set text");
            //textUpdater.setText(dataString);
            textUpdater.setText(msgData[0]);
        }
    }
        private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                                  Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            Stream       streamIn = args.GetDataStream().AsStreamForRead();
            StreamReader reader   = new StreamReader(streamIn);
            string       message  = await reader.ReadLineAsync();

            Debug.WriteLine("[Playback::Socket_MessageReceived] " + message);

            await Task.Run(() =>
            {
                Task.Yield();
                Logger.m_logger.addLog("Message received - " + message);
            });

            if (message == "WARNING noHits")
            {
                await txNoHitsInfo.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    Brush b = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 0, 0, 0));
                    txNoHitsInfo.Foreground = b;
                });


                // That way is not really recommended by Microsoft, but ... it seems to work.
                await Task.Delay(TimeSpan.FromSeconds(2)).ContinueWith(task =>
                {
                    txNoHitsInfo.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Brush b = new SolidColorBrush(Windows.UI.Color.FromArgb(0, 0, 0, 0));
                        txNoHitsInfo.Foreground = b;
                    });
                });
            }
        }
        void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            DataReader dr = args.GetDataReader();
            var dataLength = dr.UnconsumedBufferLength;

            string discoveryResult = dr.ReadString(dataLength);
            string[] parts = discoveryResult.Split('|');
            string name = parts[0];
            bool isPinProtected = bool.Parse(parts[1]);
            string uniqueName = parts[3];

            var existingTarget = GetShareTarget(uniqueName);

            var discoveredTarget = new ShareTarget()
            {
                Name = name,
                IPAddress = args.RemoteAddress.DisplayName,
                IsPinCodeRequired = isPinProtected,
                ShareTargetUniqueName = uniqueName
            };

            if (existingTarget != null)
            {
                discoveredTarget.ShareCount = existingTarget.ShareCount;
            }

            if (PeerDiscovered != null)
            {
                PeerDiscovered(discoveredTarget);
            }
        }
    private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                              Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        //Read the message that was received from the UDP echo client.
        Stream       streamIn = args.GetDataStream().AsStreamForRead();
        StreamReader reader   = new StreamReader(streamIn);
        string       message  = await reader.ReadLineAsync();

        m_sStatus = "Message received: " + message;

        if (message.StartsWith("NAV"))
        {
            rotateCylinder(message);
        }
        else if (message.StartsWith("POS"))
        {
            performRaycast(message);
        }
        else if (message.StartsWith("ANNOTATION"))
        {
            processAnnotation(message);
        }
        else if (message.StartsWith("DEBUG"))
        {
            processDebug(message);
        }
        else if (message.StartsWith("MESSAGE"))
        {
            processMessage(message);
        }
    }
Exemple #12
0
        private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                                  Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            //Read the message that was received from the UDP echo client.
            Stream       streamIn = args.GetDataStream().AsStreamForRead();
            StreamReader reader   = new StreamReader(streamIn);
            string       message  = await reader.ReadLineAsync();

            Debug.Log("MESSAGE: " + message);

            if (ExecuteOnMainThread.Count == 0)
            {
                ExecuteOnMainThread.Enqueue(() =>
                {
                    Debug.Log("Enqueue MESSAGE: " + message);
                    try
                    {
                    }
                    catch (FormatException e)
                    {
                        Debug.Log(e.Message);
                    }
                });
            }
        }
 private void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
 {
     var dataReader = args.GetDataReader();
     var length = dataReader.UnconsumedBufferLength;
     var message = dataReader.ReadString(length);
     var guidAsString = message.Replace("TT_DEVICE_IDENTIFIER:", "").Trim();
     _deviceFoundCallback?.Invoke(new TickTackHub { Id = guidAsString });
 }
Exemple #14
0
    private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                              Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        //Read the message that was received from the UDP echo client.
        Stream       streamIn = args.GetDataStream().AsStreamForRead();
        StreamReader reader   = new StreamReader(streamIn);

        message = await reader.ReadLineAsync();
    }
 void datagramSocket_MessageReceived2(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
 {
     i++;
     DataReader dataReader = args.GetDataReader();
     uint length = dataReader.UnconsumedBufferLength;
     string content = dataReader.ReadString(length);
     Deployment.Current.Dispatcher.BeginInvoke(() =>
    msgList.Children.Add(new TextBlock { Text = "客户端收到的消息:" + content }));
 }
Exemple #16
0
    // ===================================================== Code that only runs on UWP  =====================================================================//

#if NETFX_CORE
    private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                              Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        Stream       streamIn = args.GetDataStream().AsStreamForRead();
        StreamReader reader   = new StreamReader(streamIn);
        string       message  = await reader.ReadToEndAsync(); // this is a UDP message, so we can safely read all the lines

        messageQueue.Enqueue(message);
    }
Exemple #17
0
 private void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
 {
     uint stringLength = args.GetDataReader().UnconsumedBufferLength;
     byte[] result = new byte[args.GetDataReader().UnconsumedBufferLength];
     args.GetDataReader().ReadBytes(result);
     
     OSCPacket message = OSCPacket.Unpack(result);
     if (OnReceive != null)
         OnReceive(message);
 }
        private static void DatagramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            using (DataReader reader = args.GetDataReader())
            {
                byte[] b = new byte[48];

                reader.ReadBytes(b);

                App.NtpTimeOffset = GetNetworkTime(b) - DateTime.UtcNow;
            }
        }
Exemple #19
0
    private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                              Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        //Read the message that was received from the UDP echo client.
        Stream       streamIn = args.GetDataStream().AsStreamForRead();
        StreamReader reader   = new StreamReader(streamIn);
        string       message  = reader.ReadToEnd();

        Debug.Log("MESSAGE: " + message);
        text = message;
    }
Exemple #20
0
        static void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            using (DataReader reader = args.GetDataReader())
            {
                byte[] b = new byte[48];

                reader.ReadBytes(b);

                DateTime time = Util.GetNetworkTime(b);
                utcOffset = DateTime.UtcNow.Subtract(time);
            }
        }
Exemple #21
0
    private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                              Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        Debug.Log("Triggering new message!");
        //Read the message that was received from the UDP echo client.
        Stream       streamIn = args.GetDataStream().AsStreamForRead();
        StreamReader reader   = new StreamReader(streamIn);
        string       message  = await reader.ReadLineAsync();

        messages.Add(message);
        Debug.Log("MESSAGE: " + message);
    }
        private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                                  Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            Stream       streamIn = args.GetDataStream().AsStreamForRead();
            StreamReader reader   = new StreamReader(streamIn);
            string       message  = await reader.ReadLineAsync();

            Debug.WriteLine("[Playback::Socket_MessageReceived] " + message);

            if (message == "CALL start")
            {
                if (m_bIsConnected == false)
                {
                    ushort usPortRemotVideo;
                    ushort.TryParse(m_sPortRemoteVideo, out usPortRemotVideo);
                    bool statusConnection = await connect(m_sIPRemoteVideo, usPortRemotVideo);

                    if (statusConnection)
                    {
                        await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            StartPlayback(m_sIPRemoteVideo, m_sPortRemoteVideo);
                        });

                        await videoPlayer.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            videoPlayer.Visibility = Visibility.Visible;
                        });

                        m_bIsConnected = true;
                    }
                }
            }
            else if (message == "WARNING noHits")
            {
                await txNoHitsInfo.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    Brush b = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 0, 0, 0));
                    txNoHitsInfo.Foreground = b;
                });


                // That way is not really recommended by Microsoft, but ... it seems to work.
                await Task.Delay(TimeSpan.FromSeconds(2)).ContinueWith(task =>
                {
                    txNoHitsInfo.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Brush b = new SolidColorBrush(Windows.UI.Color.FromArgb(0, 0, 0, 0));
                        txNoHitsInfo.Foreground = b;
                    });
                });
            }
        }
 private static bool IsRemoteEndpoint(DatagramSocketMessageReceivedEventArgs args, IPEndpoint endpoint)
 {
     try
     {
         var result = args.RemoteAddress.IsEqual(endpoint.Address.HostName) && args.RemotePort.Equals(endpoint.ServiceName);
         return result;
     }
     catch
     {
         return false;
     }
 }
Exemple #24
0
        private async void OnMessageReceived(
            DatagramSocket sender,
            DatagramSocketMessageReceivedEventArgs args)
        {
            var senderHostname = new HostName(args.RemoteAddress.RawName);

            var writer = new DataWriter(await sender.GetOutputStreamAsync(senderHostname, args.RemotePort));

            var stream = new NetworkStream(args.GetDataReader(), writer);

            this.clients.ForEach(x => x.MessageReceived(this, stream));
        }
        private async void MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                          async () =>
                          {
                              String msg = await readMessage(args.GetDataStream());
                              this.OutputString("Received from" + args.RemoteAddress.RawName + ": " + msg);
                          }

                );


        }
Exemple #26
0
    private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                              Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        //Debug.Log("Received message: ");
        //Read the message that was received from the UDP echo client.
        Stream       streamIn = args.GetDataStream().AsStreamForRead();
        StreamReader reader   = new StreamReader(streamIn);
        string       message  = await reader.ReadLineAsync();

        Debug.Log("Message: " + message);

        lastReceivedUDPPacket = message;
        receivedUDPPacketQueue.Enqueue(message);
    }
        private async void _socket_OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs e)
        {
            var reader = e.GetDataReader();
            string message = reader.ReadString(reader.UnconsumedBufferLength);

            Logger.Trace("Message from {0}:{1}:\n{2}", e.RemoteAddress.RawName, e.RemotePort, message);

            IOutputStream outputStream = await sender.GetOutputStreamAsync(e.RemoteAddress, e.RemotePort);
            Received(this, new PeerCommandEventArgs
                               {
                                   Data = message,
                                   Peer = new RemotePeer(_serializer, this, outputStream, e.RemoteAddress, e.RemotePort),
                               });
        }
Exemple #28
0
 private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
 {
     try
     {
         using (var reader = args.GetDataReader())
         {
             byte[] response = new byte[48];
             reader.ReadBytes(response);
             _resultCompletionSource.TrySetResult(ParseNetworkTime(response));
         }
     }
     catch (Exception ex)
     {
         _resultCompletionSource.TrySetException(ex);
     }
 }
Exemple #29
0
    async void OnMessage
        (Windows.Networking.Sockets.DatagramSocket sender,
        Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        using (System.IO.Stream stream = args.GetDataStream().AsStreamForRead())
        {
            // 受信データを取得
            byte[] receiveBytes = new byte[MAX_BUFFER_SIZE];
            await stream.ReadAsync(receiveBytes, 0, MAX_BUFFER_SIZE);

            lock (p_LockObject)
            {
                // 受信データを処理に引き渡す
                UDPReceiveEvent(receiveBytes);
            }
        }
    }
        private void DatagramSocketOnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                var dataReader = args.GetDataReader();
                var receiveBytes = new byte[dataReader.UnconsumedBufferLength];
                dataReader.ReadBytes(receiveBytes);
                var receiveString = Encoding.ASCII.GetString(receiveBytes);
                var exp = new Regex(
                    "BT-SEARCH \\* HTTP/1.1\\r\\nHost: 239.192.152.143:6771\\r\\nPort: (?<port>[^@]+)\\r\\nInfohash: (?<hash>[^@]+)\\r\\n\\r\\n\\r\\n");
                var match = exp.Match(receiveString);

                if (!match.Success)
                    return;

                var portcheck = Convert.ToInt32(match.Groups["port"].Value);
                if (portcheck < 0 || portcheck > 65535)
                    return;

                TorrentManager manager = null;
                var matchHash = InfoHash.FromHex(match.Groups["hash"].Value);
                for (var i = 0; manager == null && i < _engine.Torrents.Count; i++)
                    if (_engine.Torrents[i].InfoHash == matchHash)
                        manager = _engine.Torrents[i];

                if (manager == null)
                    return;

                var uri = new Uri("tcp://" + args.RemoteAddress.RawName + ':' + match.Groups["port"].Value);
                var peer = new Peer("", uri, EncryptionTypes.All);

                // Add new peer to matched Torrent
                if (manager.HasMetadata && manager.Torrent.IsPrivate)
                    return;
                ClientEngine.MainLoop.Queue(delegate
                {
                    var count = manager.AddPeersCore(peer);
                    manager.RaisePeersFound(new LocalPeersAdded(manager, count, 1));
                });
            }
            catch
            {
                // ignored
            }
        }
    private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                              Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        //Read the message that was received from the UDP echo client.

        try
        {
            Stream       streamIn = args.GetDataStream().AsStreamForRead();
            StreamReader reader   = new StreamReader(streamIn);
            returnData = await reader.ReadLineAsync();
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
            Debug.Log(Windows.Networking.Sockets.SocketError.GetStatus(e.HResult).ToString());
            return;
        }
    }
 private void TrackerOnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
 {
     if (_taskCompletionSource == null || _taskCompletionSource.Task.IsCompleted)
         return;
     try
     {
         var dataReader = args.GetDataReader();
         var result = new byte[dataReader.UnconsumedBufferLength];
         dataReader.ReadBytes(result);
         _taskCompletionSource.SetResult(result);
     }
     catch (Exception ex)
     {
         lock (_lock)
             _timeout = 0;
         _taskCompletionSource.TrySetException(ex);
     }
 }
        private void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            uint stringLength = args.GetDataReader().UnconsumedBufferLength;
            byte[] result = new byte[args.GetDataReader().UnconsumedBufferLength];
            args.GetDataReader().ReadBytes(result);

            OSCPacket message = OSCPacket.Unpack(result);

            //var result = args.GetDataStream();
            //var resultStream = result.AsStreamForRead(1024);

            //using (var reader = new StreamReader(resultStream))
            //{
            //    var text = await reader.ReadToEndAsync();
                
                //CoreWindow.GetForCurrentThread().Dispatcher
            //}
        }
Exemple #34
0
        void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                DataReader rd = args.GetDataReader();
                uint length = rd.UnconsumedBufferLength;
                byte[] buffer = new byte[length];
                rd.ReadBytes(buffer);
                processData(buffer);
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
                Debug.Log(SocketError.GetStatus(e.HResult).ToString());
                return;
            }

        }
Exemple #35
0
        internal async void DatagramMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            var remoteAddress = args.RemoteAddress.CanonicalName;
            var remotePort = args.RemotePort;
            byte[] allBytes;

            var stream = args.GetDataStream().AsStreamForRead();
            using (var mem = new MemoryStream())
            {
                await stream.CopyToAsync(mem);
                allBytes = mem.ToArray();
            }

            var wrapperArgs = new UdpSocketMessageReceivedEventArgs(remoteAddress, remotePort, allBytes);

            if (MessageReceived != null)
                MessageReceived(this, wrapperArgs);
        }
Exemple #36
0
        private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                                  Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            //Debug.Log("GOT MESSAGE: ");
            //Read the message that was received from the UDP echo client.
            Stream       streamIn = args.GetDataStream().AsStreamForRead();
            StreamReader reader   = new StreamReader(streamIn);
            string       message  = await reader.ReadLineAsync();

            //Debug.Log("MESSAGE: " + message);

            if (ExecuteOnMainThread.Count == 0)
            {
                ExecuteOnMainThread.Enqueue(() =>
                {
                    Debug.Log("Enqueue MESSAGE: " + message);
                    try
                    {
                        if (message == "restart")
                        {
                            ExperimentManager.Instance.ResetScene();
                        }
                        else if (message == "cube")
                        {
                            ExperimentManager.Instance.SetItem("cube");
                        }
                        else if (message == "sphere")
                        {
                            ExperimentManager.Instance.SetItem("sphere");
                        }
                        else // scale
                        {
                            string[] tokens = message.Split(' ');
                            ExperimentManager.Instance.SetItemScale(tokens[1]);
                            ExperimentManager.Instance.SetTargetScale(tokens[2]);
                        }
                    }
                    catch (FormatException e)
                    {
                        Debug.Log(e.Message);
                    }
                });
            }
        }
    private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                              Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        Debug.Log("GOT MESSAGE: ");
        //Read the message that was received from the UDP echo client.
        Stream       streamIn = args.GetDataStream().AsStreamForRead();
        StreamReader reader   = new StreamReader(streamIn);
        string       message  = await reader.ReadLineAsync();

        Debug.Log("MESSAGE: " + message);

        if (ExecuteOnMainThread.Count == 0)
        {
            ExecuteOnMainThread.Enqueue(() =>
            {
                Thermostat.Temperature = float.Parse(message);
            });
        }
    }
        private async void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            if (!IsRunning)
                return;

            MemoryStream stream = new MemoryStream();
            await args.GetDataStream().AsStreamForRead().CopyToAsync(stream);
            byte[] data = stream.ToArray();

            if (DataReceived != null)
            {
                OnDataReceived(new DataReceivedEventArgs()
                {
                    Data = data,
                    Length = data.Length,
                    SenderAddress = args.RemoteAddress.RawName
                });
            }
        }
        private void MessageReceivedCallback(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            try
            {
                // Save message received from server.
                DataReader dataReader = eventArguments.GetDataReader();
                uint length = dataReader.UnconsumedBufferLength;
                m_message = dataReader.ReadString(length);
            }
            catch (Exception exception)
            {

            }
            
            if (m_callbackFunction != null)
            {
                m_callbackFunction(m_message);
            }
        }
Exemple #40
0
    private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                              Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        // Read the message that was received from the UDP echo client.
        // Initialize the streaming
        Stream       streamIn = args.GetDataStream().AsStreamForRead();
        StreamReader reader   = new StreamReader(streamIn);
        string       message  = await reader.ReadLineAsync();

        // parse the input string
        char[]   delimiterChars = { ' ' };
        string[] words          = message.Split(delimiterChars);

        // the first 3 numbers received is the start position
        StartPosition.x = float.Parse(words[0]);
        StartPosition.y = float.Parse(words[1]);
        StartPosition.z = float.Parse(words[2]);

        // the second 3 numbers received is the end position
        EndPosition.x = float.Parse(words[3]);
        EndPosition.y = float.Parse(words[4]);
        EndPosition.z = float.Parse(words[5]);

        // the rest of numbers are transformation matrix from marker to RGBD Camera
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                MarkerToCamera[i, j] = float.Parse(words[i * 4 + j + 6]);
            }
        }

        // convert the Vectors to string for verify
        string startPos = StartPosition.ToString();
        string endPos   = EndPosition.ToString();
        string T        = MarkerToCamera.ToString();

        // show the received message on log
        // Debug.Log("Received: \n" + message);
        // Debug.Log("Processed Start Position: \n" + startPos);
        // Debug.Log("Processed End Position: \n" + endPos);
        // Debug.Log("Processed Matrix: \n" + T);
    }
Exemple #41
0
	private void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
	Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
	{
	Debug.Log("GOT MESSAGE FROM: " + args.RemoteAddress.DisplayName);
	//Read the message that was received from the UDP  client.
	Stream streamIn = args.GetDataStream().AsStreamForRead();
	MemoryStream ms = ToMemoryStream(streamIn);
	byte[] msgData = ms.ToArray();


	if (ExecuteOnMainThread.Count == 0)
	{
	ExecuteOnMainThread.Enqueue(() =>
	{
	Debug.Log("ENQEUED ");
	if (udpEvent != null)
	udpEvent.Invoke(args.RemoteAddress.DisplayName, internalPort, msgData);
	});
	}
	}
Exemple #42
0
        private void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                DataReader reader = args.GetDataReader();
                reader.InputStreamOptions = InputStreamOptions.Partial;
                uint bytesRead = reader.UnconsumedBufferLength;
                String message = reader.ReadString(bytesRead);

                playPage.DisplayMessages(name + " :Message received [" +
                    args.RemoteAddress.DisplayName.ToString() + "]:" + args.RemotePort + ": " + message);

                SendMessage(IPAdress.LocalIPAddress() + " " + name, args.RemoteAddress.DisplayName.ToString(), portSender);
                reader.Dispose();
            }
            catch (Exception ex)
            {
                playPage.DisplayMessages(name + " :ERROR: Message received from:\n" + ex.ToString());
            }
        }
Exemple #43
0
    private async void Listener_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                                Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        Debug.Log("DATA!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!: ");
        try {
            //Read the message that was received from the UDP echo client.
            Stream       streamIn = args.GetDataStream().AsStreamForRead();
            StreamReader reader   = new StreamReader(streamIn);
            string       message  = await reader.ReadToEndAsync();

            lock (_receiveQueueLock) {
                Debug.Log("REC: " + message);
                _receiveQueue.Enqueue(message);
            }
        } catch (Exception e) {
            Debug.Log("DATA LISTENER EXCEPTION: " + e.ToString());
            Debug.Log(SocketError.GetStatus(e.HResult).ToString());
            return;
        }
    }
        private void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
        {
            playPage.DisplayMessages(name + " :MessageReceived");
            try
            {
                DataReader reader = args.GetDataReader();
                reader.InputStreamOptions = InputStreamOptions.Partial;
                uint bytesRead = reader.UnconsumedBufferLength;
                string message = reader.ReadString(bytesRead);
                string msg = message.Replace("\0", string.Empty);
                playPage.DisplayMessages(name + " :Message received from [" +
                    args.RemoteAddress.DisplayName.ToString() + "]:" + args.RemotePort + ": " + message);

                reader.Dispose();
                playPage.AddServer(msg);
            }
            catch (Exception ex)
            {
                playPage.DisplayMessages(name + " :ERROR: Message received from:" + ex.ToString());
            }
        }
        private async void SocketOnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                var result = args.GetDataStream();
                var resultStream = result.AsStreamForRead(1024);

                using (var reader = new StreamReader(resultStream))
                {
                    var text = await reader.ReadToEndAsync();
                    discoverResponce = text;
                    if (autoEvent != null)
                    {
                        autoEvent.Set();
                    }
                    dataReceived(text);
                }
            }
            catch (Exception e)
            { }
        }
Exemple #46
0
        private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                                  Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            // lock multi event
            socket.MessageReceived -= Socket_MessageReceived;

            //Debug.Log("OSCSERVER UWP  Socket_MessageReceived");

            //Read the message that was received from the UDP echo client.
            //Stream streamIn = args.GetDataStream().AsStreamForRead();
            DataReader reader = args.GetDataReader();

            //StreamReader reader = new StreamReader(streamIn);
            try
            {
                uint   stringLength = reader.UnconsumedBufferLength;
                byte[] bytes        = new byte[stringLength];
                reader.ReadBytes(bytes);

                //string message = await reader.ReadToEndAsync()
                //                 .ConfigureAwait(continueOnCapturedContext: false);
                //byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);

                OSCPacket packet = OSCPacket.Unpack(bytes);
                _lastReceivedPacket = packet;

                PacketReceivedEvent(this, _lastReceivedPacket);
            }
            catch (System.Exception e)
            {
                WorldErrors.Print(e.Message);
            }
            finally
            {
                //streamIn.Dispose();
                reader.Dispose();
                // unlock multi event
                socket.MessageReceived += Socket_MessageReceived;
            }
        }
Exemple #47
0
		static async void multicastSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs eventArguments) {
			try {
				HostName remoteHostAddress = eventArguments.RemoteAddress;
				uint len = eventArguments.GetDataReader().UnconsumedBufferLength;
				string message = eventArguments.GetDataReader().ReadString(len).Trim();
				int p = message.IndexOf(':');
				if (p != -1) {
					string serverLogToken = message.Substring(0, p);
					int port = Int32.Parse(message.Substring(p + 1));

					if (serverLogToken == logToken && port > 0 && port < 65535) {
						Debug.WriteLine("[LOGGER] Found a Titanium log server: " + remoteHostAddress.DisplayName + ":" + port);

						try {
							tcpSocket = new StreamSocket();
							tcpSocket.Control.KeepAlive = true;
							await tcpSocket.ConnectAsync(remoteHostAddress, port.ToString());
							tcpWriter = new DataWriter(tcpSocket.OutputStream);

							// shutdown the multicast socket and start the tcp connection
							multicastSocket.Dispose();
						} catch {
							if (tcpWriter != null) {
								tcpWriter.Dispose();
								tcpWriter = null;
							}
							if (tcpSocket != null) {
								tcpSocket.Dispose();
								tcpSocket = null;
							}
						}
					}
				}
			} catch (Exception ex) {
				if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) {
					throw;
				}
				Debug.WriteLine(ex.ToString());
			}
		}
        /// <summary>
        /// MessageReceived event
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="eventArguments"></param>
          void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            try
            {
                //get string length
                uint stringLength = eventArguments.GetDataReader().UnconsumedBufferLength;
                 
                    //read string from the stream
                    string receivedMessage = eventArguments.GetDataReader().ReadString(stringLength);

                    //it is not possible to access controls from here
                    var ignore = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    do_job(eventArguments.RemoteAddress.ToString(), receivedMessage, eventArguments.RemotePort.ToString(),
                    eventArguments.LocalAddress.ToString()));
                
            }
            catch (Exception ex)
            {
                //show exception on the Network Log textbox
                bytes_s.Content = ex.ToString(); 
            }
        }
        private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
            Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {

        try
        {
            //Read the message that was received from the UDP echo client.
            Stream streamIn = args.GetDataStream().AsStreamForRead();
            StreamReader reader = new StreamReader(streamIn);
            string jsonData = await reader.ReadToEndAsync();
            //Debug.Log("MESSAGE: " + jsonData);
            //UnityEngine.Debug.LogError(jsonData);

              DataStruct newData = Newtonsoft.Json.JsonConvert.DeserializeObject<DataStruct>(jsonData);
              UdpEvent.onDataRecieved(newData);
        }

        catch (Exception e)
        {
            Exception mye = e;
            String tst = mye.Message;
            string sts = "";
        }
        }
		private async void datagramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
		{
			if (args.LocalAddress == args.RemoteAddress)
				return;

			byte[] payload;
			using (var dataReader = new DataReader(args.GetDataStream()))
			{
				var count = await dataReader.LoadAsync(26);
				if (count != 26)
					return;

				payload = new byte[dataReader.UnconsumedBufferLength];
				dataReader.ReadBytes(payload);
			}

			var cubeDiscoveredEventArgs = new CubeDiscoveredEventArgs
			{
				RemoteAddress = args.RemoteAddress,
				CubeInfo = ParsePayload(payload)
			};

			CubeDiscovered?.Invoke(this, cubeDiscoveredEventArgs);
		}
Exemple #51
0
        private void ServerDatagramSocket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            Debug.WriteLine("received packet");
            Stream       streamIn = args.GetDataStream().AsStreamForRead();
            MemoryStream image    = ToMemoryStream(streamIn);

            Save_Image(image);
        }
        /// <summary>
        /// Message received handler
        /// </summary>
        /// <param name="socket">The socket object</param>
        /// <param name="eventArguments">The datagram event information</param>
        void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            try
            {
                // Interpret the incoming datagram's entire contents as a string.
                uint stringLength = eventArguments.GetDataReader().UnconsumedBufferLength;
                string receivedMessage = eventArguments.GetDataReader().ReadString(stringLength);

                NotifyUserFromAsyncThread(
                    "Received data from remote peer (Remote Address: " +
                    eventArguments.RemoteAddress.CanonicalName +
                    ", Remote Port: " +
                    eventArguments.RemotePort + "): \"" +
                     receivedMessage + "\"",
                    NotifyType.StatusMessage);
            }
            catch (Exception exception)
            {
                SocketErrorStatus socketError = SocketError.GetStatus(exception.HResult);

                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                rootPage.NotifyUser(
                    "Error happened when receiving a datagram:" + exception.Message,
                    NotifyType.ErrorMessage);
            }
        }
            private void OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
            {
                //Logger.Trace("OnMessageReceived: endpoint = {0}, port = {1}", args.RemoteAddress, args.RemotePort);

                var reader = args.GetDataReader();
                var count = reader.UnconsumedBufferLength;
                var data = new byte[count];
                reader.ReadBytes(data);
                lock (m_messages)
                {
                    m_messages.Add(new Message { Data = data });
                }
                m_messageReceivedEvent.Set();
            }
        /// <summary>
        /// When a new message is received, the participant is added to the list of Participants.
        /// </summary>
        private async void MessageToConnectReceivedFromParticipantAsync(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            var participant = new UdpParticipantInformation { Host = args.RemoteAddress };

            // Read the subscriber's message.
            using (var reader = new StreamReader(args.GetDataStream().AsStreamForRead()))
            {
                string message = await reader.ReadLineAsync();
                
                // Add the participant.
                base.AddParticipant(participant, message);
            }
        }
Exemple #55
0
        //private void DataReceived(object o)
        private void DataSocket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                var reader = args.GetDataReader();

                byte[] data = new byte[reader.UnconsumedBufferLength];
                args.GetDataReader().ReadBytes(data);

                this.socket = sender;

                var dhcpRequest = new DHCPRequest(data, socket, this);
                //ccDHCP = new clsDHCP();


                //data is now in the structure
                //get the msg type
                OnDataReceived(this, dhcpRequest);
                var msgType = dhcpRequest.GetMsgType();
                switch (msgType)
                {
                case DHCPMsgType.DHCPDISCOVER:
                    OnDiscover(this, dhcpRequest);
                    break;

                case DHCPMsgType.DHCPREQUEST:
                    OnRequest(this, dhcpRequest);
                    break;

                case DHCPMsgType.DHCPDECLINE:
                    OnDecline(this, dhcpRequest);
                    break;

                case DHCPMsgType.DHCPRELEASE:
                    OnReleased(this, dhcpRequest);
                    break;

                case DHCPMsgType.DHCPINFORM:
                    OnInform(this, dhcpRequest);
                    break;
                    //default:
                    //    Console.WriteLine("Unknown DHCP message: " + (int)MsgTyp + " (" + MsgTyp.ToString() + ")");
                    //    break;
                }
            }
            catch (Exception ex)
            {
                if (UnhandledException != null)
                {
                    UnhandledException(this, ex);
                }
            }
        }
    private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
                                              Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        //Read the message that was received from the UDP echo client.
        Stream streamIn = args.GetDataStream().AsStreamForRead();

        Byte[] header = new Byte[2];

        await streamIn.ReadAsync(header, 0, 2);

        string hearderStr = BitConverter.ToString(header);

        // 遥测数据头 AA 55
        Debug.Log("header:" + hearderStr);
        // 验证同步码
        if ("AA-55" == hearderStr)
        {
            Byte[] data = new Byte[80];
            await streamIn.ReadAsync(data, 0, 80);

            // 类型为数据
            DroneData droneData = new DroneData(data);

            int sum = 0;
            for (int i = 0; i < 80; i++)
            {
                sum += data[i];
            }
            string str  = Convert.ToString(sum, 2);
            string real = str;
            if (real.Length >= 8)
            {
                real = str.Substring(str.Length - 8);
            }
            面的代码是校验和对比,测试时可以注释掉
            Byte verification = Convert.ToByte(real, 2);
            if (verification != droneData.Verification)
            {
                Debug.Log("Verification byte is wrong");
                return;
            }

            Debug.Log("Data: " + BitConverter.ToString(data));
            if (anchor != null && videoManager.Captured)
            {
                float leftTopX     = Convert.ToSingle(droneData.LeftTopX);
                float leftTopY     = Convert.ToSingle(droneData.LeftTopY);
                float rightBottomX = Convert.ToSingle(droneData.RightBottomX);
                float rightBottomY = Convert.ToSingle(droneData.RightBottomY);

                if (leftTopX < 0)
                {
                    leftTopX = 0;
                }
                else if (leftTopX > 1920)
                {
                    leftTopX = 1920;
                }
                if (leftTopY < 0)
                {
                    leftTopY = 0;
                }
                else if (leftTopY > 1080)
                {
                    leftTopY = 1080;
                }
                if (rightBottomX < 0)
                {
                    rightBottomX = 0;
                }
                else if (rightBottomX > 1920)
                {
                    rightBottomX = 1920;
                }
                if (rightBottomY < 0)
                {
                    rightBottomY = 0;
                }
                else if (rightBottomY > 1080)
                {
                    rightBottomY = 1080;
                }
                vectors    = new Vector3[2];
                vectors[0] = new Vector3(leftTopX, -leftTopY, 0);
                vectors[1] = new Vector3(rightBottomX, -rightBottomY, 0);
                prepared   = true;
            }

            UnityEngine.WSA.Application.InvokeOnAppThread(() =>
            {
                for (int i = 0; i < infos.Length; i++)
                {
                    //Modify 4/13/2017
                    string name = infos[i].name;
                    switch (name)
                    {
                    case "time":
                        int year       = Convert.ToInt16(droneData.Fly.Year);
                        int min        = Convert.ToInt16(droneData.Fly.Min);
                        int month      = Convert.ToInt16(droneData.Fly.Month);
                        int date       = Convert.ToInt16(droneData.Fly.Date);
                        int hour       = Convert.ToInt16(droneData.Fly.Hour);
                        int sec        = Convert.ToInt16(droneData.Fly.Sec);
                        int percentSec = Convert.ToInt16(droneData.Fly.PercentSec);
                        if (year < 0 || year > 99)
                        {
                            year = 0;
                        }
                        if (month < 0 || month > 12)
                        {
                            month = 0;
                        }
                        if (date < 0 || date > 31)
                        {
                            date = 0;
                        }
                        if (hour < 0 || hour > 23)
                        {
                            hour = 0;
                        }
                        if (min < 0 || min > 59)
                        {
                            min = 0;
                        }
                        if (sec < 0 || sec > 59)
                        {
                            sec = 0;
                        }
                        if (percentSec < 0 || percentSec > 99)
                        {
                            percentSec = 0;
                        }
                        texts[i].text = originalTexts[i] + (" " + year + "年 " + month + "月 " + date + "日 " + hour + "时 " + min + "分 " + sec + "秒 " + percentSec + "百分秒").ToString();
                        break;

                    case "flytime":
                        int v8 = droneData.Fly.Stars;
                        if (v8 < 0)
                        {
                            v8 = 0;
                        }
                        else if (v8 > 24)
                        {
                            v8 = 24;
                        }
                        texts[i].text = originalTexts[i] + (v8).ToString() + "颗";
                        break;

                    case "flyangle2":
                        int v5 = (int)(droneData.Fly.MovingAngle * 0.01);
                        if (v5 < 0)
                        {
                            v5 = 0;
                        }
                        else if (v5 > 360)
                        {
                            v5 = 360;
                        }
                        texts[i].text = originalTexts[i] + (v5).ToString() + "°";
                        break;

                    case "updownangle2":
                        int v6 = (int)(droneData.Fly.UpdownAngle * 0.01);
                        if (v6 < -90)
                        {
                            v6 = -90;
                        }
                        else if (v6 > 90)
                        {
                            v6 = 90;
                        }
                        texts[i].text = originalTexts[i] + (v6).ToString() + "°";
                        break;

                    case "rotateangle":
                        int v7 = (int)(droneData.Fly.UpdownAngle * 0.01);
                        if (v7 < -90)
                        {
                            v7 = 90;
                        }
                        else if (v7 > 90)
                        {
                            v7 = 90;
                        }
                        texts[i].text = originalTexts[i] + (droneData.Fly.RotateAngle * 0.01f).ToString() + "°";
                        break;

                    case "attitude":
                        int v9 = droneData.Fly.Height;
                        if (v9 < -500)
                        {
                            v9 = -500;
                        }
                        else if (v9 > 6000)
                        {
                            v9 = 6000;
                        }
                        texts[i].text = originalTexts[i] + (v9).ToString() + "M";
                        break;

                    case "speed":
                        int v10 = droneData.Fly.Speed;
                        if (v10 < 0)
                        {
                            v10 = 0;
                        }
                        else if (v10 > 1200)
                        {
                            v10 = 1200;
                        }
                        texts[i].text = originalTexts[i] + (v10).ToString() + "Km\\h";
                        break;

                    case "longitude":
                        float f = droneData.Fly.Longtitude * 0.0000001f;

                        if (f < -180)
                        {
                            f = -180;
                        }
                        else if (f > 180)
                        {
                            f = 180;
                        }
                        texts[i].text = originalTexts[i] + (f).ToString() + "°";
                        //经度
                        position        = new PositionInfo();
                        position.Longti = f;
                        gps.text        = texts[i].text;
                        break;

                    case "latitude":
                        //纬度

                        float f2 = droneData.Fly.Latitude * 0.0000001f;

                        if (f2 < -90)
                        {
                            f2 = -90;
                        }
                        else if (f2 > 90)
                        {
                            f2 = 90;
                        }

                        texts[i].text = originalTexts[i] + (f2).ToString() + "°";
                        gps.text     += texts[i].text;
                        position.Lati = f2;
                        //下面这行代码会在地图上画点,但是之前做的都不符合要求,现在被我注释掉了
                        MapController.GetMapController().AddPoints(position.Longti, position.Lati);

                        break;

                    case "status":
                        string state = Convert.ToString(droneData.State2, 2).PadLeft(8, '0');
                        string s     = "";
                        if (state[0] == '0')
                        {
                            s    = "未跟踪好";
                            good = false;
                        }
                        else if (state[0] == '1')
                        {
                            s    = "已跟踪好";
                            good = true;
                        }
                        texts[i].text = originalTexts[i] + s;
                        break;

                    case "hangji":
                        int v11 = (int)(droneData.Fly.TrackAngle * 0.1);
                        if (v11 < 0)
                        {
                            v11 = 0;
                        }
                        else if (v11 > 360)
                        {
                            v11 = 360;
                        }
                        texts[i].text = originalTexts[i] + (v11).ToString() + "°";
                        break;

                    case "flyangle":
                        int value1 = (int)(droneData.PtUpDown * 0.01);
                        if (value1 > 90)
                        {
                            value1 = 90;
                        }
                        else if (value1 < -90)
                        {
                            value1 = -90;
                        }
                        texts[i].text = originalTexts[i] + value1.ToString() + "°";
                        break;

                    case "updownangle":
                        int value = (int)(droneData.PtUpDown * 0.01);
                        if (value > 2)
                        {
                            value = 2;
                        }
                        else if (value < -90)
                        {
                            value = -90;
                        }
                        texts[i].text = originalTexts[i] + value.ToString() + "°";
                        break;

                    case "gyro":
                        Byte mode   = droneData.WorkMode;
                        string str1 = "";
                        switch (mode)
                        {
                        case 0x20:
                            str1 = "目标指向";
                            break;

                        case 0x40:
                            str1 = "手动搜索";
                            break;

                        case 0x80:
                            str1 = "目标跟踪";
                            break;
                        }
                        texts[i].text = originalTexts[i] + str1;
                        break;

                    case "locationdrive":
                        int v1 = droneData.UpDownOffset;
                        if (v1 < -540)
                        {
                            v1 = -540;
                        }
                        else if (v1 > 540)
                        {
                            v1 = 540;
                        }
                        texts[i].text = originalTexts[i] + v1.ToString() + "像素";
                        break;

                    case "directanglespeed":
                        int v3        = droneData.DirectAngle;
                        v3            = (int)(v3 * 0.01);
                        texts[i].text = originalTexts[i] + v3.ToString() + "°/s";
                        break;

                    case "updownanglespeed":
                        int v4        = droneData.UpDownAngle;
                        v4            = (int)(v4 * 0.01);
                        texts[i].text = originalTexts[i] + v4.ToString() + "°/s";
                        break;

                    case "updowndrive":
                        int v2 = droneData.DirectOffset;
                        if (v2 < -960)
                        {
                            v2 = -960;
                        }
                        else if (v2 > 960)
                        {
                            v2 = 960;
                        }
                        texts[i].text = originalTexts[i] + v2.ToString() + "像素";
                        break;

                    case "ptzstatus":
                        UInt32 seq = droneData.Sequence;
                        if (seq < 0x00000000)
                        {
                            seq = 0x00000000;
                        }
                        else if (seq > 0xffffffff)
                        {
                            seq = 0xffffffff;
                        }
                        texts[i].text = originalTexts[i] + seq.ToString();
                        break;

                    case "battery":
                        var aggBattery = Battery.AggregateBattery;
                        var report     = aggBattery.GetReport();
                        double full    = Convert.ToDouble(report.FullChargeCapacityInMilliwattHours.ToString());
                        double cur     = Convert.ToDouble(report.RemainingCapacityInMilliwattHours.ToString());
                        double percent = (cur / full) * 100;
                        texts[i].text  = originalTexts[i] + (int)percent + "%";
                        break;

                    case "wifistatus":
                        string wifi   = (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true ? "已连接" : "未连接");
                        texts[i].text = originalTexts[i] + wifi;
                        break;

                    case "controllerstatus":
                        string controllerStatus = (controllerConnection == true ? "手柄已连接" : "手柄未连接");
                        texts[i].text           = originalTexts[i] + controllerStatus;
                        break;

                    case "rheight":
                        float v13 = droneData.Fly.RHeight * 0.1f;
                        if (v13 < -1000)
                        {
                            v13 = -1000f;
                        }
                        else if (v13 > 3000)
                        {
                            v13 = 3000f;
                        }
                        texts[i].text = originalTexts[i] + v13 + "m";
                        break;
                    }
                }
            }, false);
        }

        if (ExecuteOnMainThread.Count == 0)
        {
            ExecuteOnMainThread.Enqueue(() =>
            {
                //Thermostat.Temperature = float.Parse(message);
            });
        }
    }
Exemple #57
0
        /// <summary>
        /// Event handler that gets called when a message is received on the socket
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        private static void MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            Stream streamIn = args.GetDataStream().AsStreamForRead();

            byte[] byteArray;

            // Use the memory stream to convert the stream to a byte array
            using (var memoryStream = new MemoryStream())
            {
                streamIn.CopyTo(memoryStream);
                byteArray = memoryStream.ToArray();
            }

            // Data received, create a new NetworkMessage
            byte messageId = byteArray[0];

            // Remove the message ID from the data
            byte[] message = new byte[byteArray.Length - 1];

            for (int i = 1; i < byteArray.Length; ++i)
            {
                message[i - 1] = byteArray[i];
            }

            // Build network message
            NetworkMessage nm = new NetworkMessage(messageId, message);

            // Call the correct callback method
            if (SocketClientManager.callbackMethods.ContainsKey(messageId))
            {
                // Catch any exceptions and rethrow them,
                // so a user gets a good exception instead of a
                // object disposed exception
                try
                {
                    SocketClientManager.callbackMethods[messageId](nm);
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
            {
                PrintDebug("No known callback for message ID " + messageId.ToString());
            }
        }
        private async void ServerDatagramSocket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            string request;

            using (DataReader dataReader = args.GetDataReader())
            {
                request = dataReader.ReadString(dataReader.UnconsumedBufferLength).Trim();
            }

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add(string.Format("server received the request: \"{0}\"", request)));
        }
        private void Socket_Completed_Receive(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                ExecuteWithSuppressedExceptions(() => sender.MessageReceived -= this.Socket_Completed_Receive);

                byte[] buffer = null;
                using (var reader = args.GetDataReader())
                {
                    buffer = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(buffer);
                }

                ConvertBufferToCurrentTime(buffer);
            }
            catch (Exception ex)
            {
                OnErrorOccurred(ExceptionToNtpNetworkException(ex));
            }
        }
    private void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        //Read the message that was received from the UDP  client.
        Stream       streamIn = args.GetDataStream().AsStreamForRead();
        MemoryStream ms       = ToMemoryStream(streamIn);

        byte[] msgData = ms.ToArray();


        if (ExecuteOnMainThread.Count == 0)
        {
            ExecuteOnMainThread.Enqueue(() => { InterpreteUDPData(msgData); });
        }
    }