簡體   English   中英

我如何從udp數據包中獲取經度和緯度值C#

[英]How can i get latitude and longitude values from udp packets c#

[![Header] [1]] [1]我正在做一個小項目,從中獲取經度和緯度

您能否告訴我如何從數據中提取真實的緯度和經度值。

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Linq;


namespace SimpleUdpReciever
{
    class pProgram
    {
        static void Main(string[] args)
        {
            int localPort = 18006;
            IPEndPoint remoteSender = new IPEndPoint(IPAddress.Any, 0);
            bool flag = false;

            for (int i = 0; i < args.Length; i++)
            {
                string cmd = args[i];
                string value;
                int tempInt;
                IPAddress tempAddress;

                switch (cmd)
                {
                    case "-lp":
                        value = GetValue(args, ref i);
                        if (int.TryParse(value, out tempInt))
                            localPort = tempInt;
                        break;
                    case "-rp":
                        value = GetValue(args, ref i);
                        if (int.TryParse(value, out tempInt))
                            remoteSender.Port = tempInt;
                        break;
                    case "-rh":
                        value = GetValue(args, ref i);
                        if (IPAddress.TryParse(value, out tempAddress))
                            remoteSender.Address = tempAddress;
                        else if (int.TryParse(value, out tempInt) && tempInt == 0)
                            remoteSender.Address = IPAddress.Any;
                        break;
                    case "-?":
                    default:
                        PrintHelpText();
                        flag = true;
                        break;
                }
            }

            // Exit application after help text is displayed
            if (flag)
                return;



            // Create UDP client
            UdpClient client = new UdpClient(localPort);
            UdpState state = new UdpState(client, remoteSender);
            // Start async receiving
            client.BeginReceive(new AsyncCallback(DataReceived), state);

            // Wait for any key to terminate application
            Console.ReadKey();
            client.Close();
        }

        public static  string ByteArrayToString(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
                hex.AppendFormat("{0:x2}", b);
            return hex.ToString();
        }

        private static void DataReceived(IAsyncResult ar)
        {
            UdpClient c = (UdpClient)((UdpState)ar.AsyncState).c;
            IPEndPoint wantedIpEndPoint = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
            IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            Byte[] receiveBytes = c.EndReceive(ar, ref receivedIpEndPoint);          

            bool isRightHost = (wantedIpEndPoint.Address.Equals(receivedIpEndPoint.Address)) || wantedIpEndPoint.Address.Equals(IPAddress.Any);
            bool isRightPort = (wantedIpEndPoint.Port == receivedIpEndPoint.Port) || wantedIpEndPoint.Port == 0;
            if (isRightHost && isRightPort)

            {
                // Console.WriteLine(ByteArrayToString(receiveBytes));
                if (receiveBytes[3] == 187 && receiveBytes[4] == 1)
                {


                    //Printing output 

                    Console.WriteLine("4 bytes starting with 5 yields: {0} {1} {2} {3} {4}",
                                     receiveBytes[5],
                                     receiveBytes[6],
                                     receiveBytes[7],
                                     receiveBytes[8],

                     BitConverter.ToInt32(receiveBytes, 4));
                    Console.WriteLine("4 bytes starting with 9 yields: {0} {1} {2} {3} {4}",
                                  receiveBytes[9],
                                  receiveBytes[10],
                                  receiveBytes[11],
                                  receiveBytes[11],

                  BitConverter.ToInt32(receiveBytes, 9));


                }



            } 




            // Restart listening for udp data packages
            c.BeginReceive(new AsyncCallback(DataReceived), ar.AsyncState);

        }


        private static string GetValue(string[] args, ref int i)
        {
            string value = String.Empty;
            if (args.Length >= i + 2)
            {
                i++;
                value = args[i];
            }
            return value;
        }



        private static void PrintHelpText()
        {
            Console.WriteLine("Simple Udp Receiver is an application that prints incoming data to screen.");
            Console.WriteLine("Data is converted to ASCII before printing.");
            Console.WriteLine("*** Amund Gjersoe 2010 ***\n");
            Console.WriteLine("Command switches:");
            Console.WriteLine("-? : Displays this text.");
            Console.WriteLine("-lp : Set local receiving port. \"-lp 4001\" Default: 11000");
            Console.WriteLine("-rp : Set remote sender port. \"-rp 4001\" Default: 0 (Any port)");
            Console.WriteLine("-rh : Set remote sender ip. \"-rh 192.168.1.10\" Default: 0 (Any ip)");
            Console.WriteLine("\n Example of usage:\nSimpleUdpReciver.exe -lp 11000 -rh 192.168.10.10 -rp 4001");
        }

    }
}

數據包結構[![packet] [4]] [4]

[![1d 187數據包的整個數據] [5]] [5]

GPS消息使用Big Endian整數。 以下代碼僅關注有效負載以及如何使用System.IO.MemoryStreamSystem.IO.BinaryReader (讀取小端格式)將其轉換為GPSMessage結構。 要糾正錯誤的字節序,示例代碼使用System.Net.IPAddress.NetworkToHostOrder()

using System;

namespace ConsoleWindowPos
{
    struct GPSMessage
    {
        public byte ValidityFlags { get; set; }
        public Int32 TargetLatRaw { get; set; }
        public float TargetLat { get { return 90.0f / (Int32.MaxValue-1) * (float)TargetLatRaw ; } }
        public Int32 TargetLongRaw { get; set; }
        public float TargetLong { get { return 180.0f / (Int32.MaxValue-1) * (float)TargetLongRaw; } }

        public static GPSMessage FromBinary(byte[] payload)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream(payload);
            System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
            GPSMessage result = new GPSMessage();
            result.ValidityFlags = reader.ReadByte();
            result.TargetLatRaw = System.Net.IPAddress.NetworkToHostOrder(reader.ReadInt32());
            result.TargetLongRaw = System.Net.IPAddress.NetworkToHostOrder(reader.ReadInt32());
            return result;
        }

        public override string ToString()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.AppendLine("GPSMessage: {");
            sb.AppendFormat("    ValidityFlags = 0x{0:X2};", ValidityFlags);
            sb.AppendLine();
            sb.Append("    TargetLatRaw = ");
            sb.Append(TargetLatRaw);
            sb.AppendLine(";");
            sb.Append("    TargetLat = ");
            sb.Append(TargetLat);
            sb.AppendLine(";");
            sb.Append("    TargetLongRaw = ");
            sb.Append(TargetLongRaw);
            sb.AppendLine(";");
            sb.Append("    TargetLong = ");
            sb.Append(TargetLong);
            sb.AppendLine(";");
            sb.Append("}");
            return sb.ToString();
        }
    }


    class Program
    {

        static void Main(string[] args)
        {
            byte[] payload = { 1,204,99,37,86,103,105,241,16,0,107,0,16,242,151,0,0,190 };
            var message = GPSMessage.FromBinary(payload);
            System.Console.WriteLine(message.ToString());
            System.Console.ReadLine();
        }
    }
}

此代碼的輸出是:

GPSMessage: {
    ValidityFlags = 0x01;
    TargetLatRaw = -865917610;
    TargetLat = -36.29019;
    TargetLongRaw = 1734996240;
    TargetLong = 145.4257;
}

這似乎與問題作者所期望的差不多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM