如何从udp数据包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(读取little-endian格式(将其转换为GPSMessage结构。为了纠正错误的endianes,示例代码使用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;
}

这似乎正是这个问题的作者所期望的。

最新更新