用C#读取GPS数据的基类,适用于wince操作系统。 适合自带GPS模块的PDA或智能手机的设备

这是一个C#基类,用于在Windows CE操作系统下读取带有GPS模块的PDA或智能手机的GPS数据。类中包含了串口设置、通信超时配置以及读写方法,还提供了从GPS数据中提取特定信息的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在多普达p800 , windows Mobile 5.0 操作系统下测试通过. 


 

  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Text;
  4. namespace BaseStationPDA 
  5. {
  6.  class GPS 
  7.  {
  8.   public string PortNum; 
  9.   public int BaudRate;
  10.   public byte ByteSize;
  11.   public byte Parity; // 0-4=no,odd,even,mark,space 
  12.   public byte StopBits; // 0,1,2 = 1, 1.5, 2 
  13.   public int ReadTimeout;
  14.   
  15.   //comm port win32 file handle
  16.   private int hComm = -1;
  17.   
  18.   public bool Opened = false;
  19.    
  20.   //win32 api constants
  21.   private const uint GENERIC_READ = 0x80000000;
  22.   private const uint GENERIC_WRITE = 0x40000000;
  23.   private const int OPEN_EXISTING = 3;  
  24.   private const int INVALID_HANDLE_VALUE = -1;
  25.   
  26.   [StructLayout(LayoutKind.Sequential)]
  27.    public struct DCB 
  28.   {
  29.    //taken from c struct in platform sdk 
  30.    public int DCBlength;           // sizeof(DCB) 
  31.    public int BaudRate;            // 指定当前波特率 current baud rate
  32.    // these are the c struct bit fields, bit twiddle flag to set
  33.    public int fBinary;          // 指定是否允许二进制模式,在windows95中必须主TRUE binary mode, no EOF check 
  34.    public int fParity;          // 指定是否允许奇偶校验 enable parity checking 
  35.    public int fOutxCtsFlow;      // 指定CTS是否用于检测发送控制,当为TRUE是CTS为OFF,发送将被挂起。 CTS output flow control 
  36.    public int fOutxDsrFlow;      // 指定CTS是否用于检测发送控制 DSR output flow control 
  37.    public int fDtrControl;       // DTR_CONTROL_DISABLE值将DTR置为OFF, DTR_CONTROL_ENABLE值将DTR置为ON, DTR_CONTROL_HANDSHAKE允许DTR"握手" DTR flow control type 
  38.    public int fDsrSensitivity;   // 当该值为TRUE时DSR为OFF时接收的字节被忽略 DSR sensitivity 
  39.    public int fTXContinueOnXoff; // 指定当接收缓冲区已满,并且驱动程序已经发送出XoffChar字符时发送是否停止。TRUE时,在接收缓冲区接收到缓冲区已满的字节XoffLim且驱动程序已经发送出XoffChar字符中止接收字节之后,发送继续进行。 FALSE时,在接收缓冲区接收到代表缓冲区已空的字节XonChar且驱动程序已经发送出恢复发送的XonChar之后,发送继续进行。XOFF continues Tx 
  40.    public int fOutX;          // TRUE时,接收到XoffChar之后便停止发送接收到XonChar之后将重新开始 XON/XOFF out flow control 
  41.    public int fInX;           // TRUE时,接收缓冲区接收到代表缓冲区满的XoffLim之后,XoffChar发送出去接收缓冲区接收到代表缓冲区空的XonLim之后,XonChar发送出去 XON/XOFF in flow control 
  42.    public int fErrorChar;     // 该值为TRUE且fParity为TRUE时,用ErrorChar 成员指定的字符代替奇偶校验错误的接收字符 enable error replacement 
  43.    public int fNull;          // eTRUE时,接收时去掉空(0值)字节 enable null stripping 
  44.    public int fRtsControl;     // RTS flow control 
  45.    /*RTS_CONTROL_DISABLE时,RTS置为OFF
  46.             RTS_CONTROL_ENABLE时, RTS置为ON
  47.             RTS_CONTROL_HANDSHAKE时,
  48.             当接收缓冲区小于半满时RTS为ON
  49.              当接收缓冲区超过四分之三满时RTS为OFF
  50.             RTS_CONTROL_TOGGLE时,
  51.             当接收缓冲区仍有剩余字节时RTS为ON ,否则缺省为OFF*/
  52.    public int fAbortOnError;   // TRUE时,有错误发生时中止读和写操作 abort on error 
  53.    public int fDummy2;        // 未使用 reserved 
  54.    
  55.    public uint flags;
  56.    public ushort wReserved;          // 未使用,必须为0 not currently used 
  57.    public ushort XonLim;             // 指定在XON字符发送这前接收缓冲区中可允许的最小字节数 transmit XON threshold 
  58.    public ushort XoffLim;            // 指定在XOFF字符发送这前接收缓冲区中可允许的最小字节数 transmit XOFF threshold 
  59.    public byte ByteSize;           // 指定端口当前使用的数据位 number of bits/byte, 4-8 
  60.    public byte Parity;             // 指定端口当前使用的奇偶校验方法,可能为:EVENPARITY,MARKPARITY,NOPARITY,ODDPARITY  0-4=no,odd,even,mark,space 
  61.    public byte StopBits;           // 指定端口当前使用的停止位数,可能为:ONESTOPBIT,ONE5STOPBITS,TWOSTOPBITS  0,1,2 = 1, 1.5, 2 
  62.    public char XonChar;            // 指定用于发送和接收字符XON的值 Tx and Rx XON character 
  63.    public char XoffChar;           // 指定用于发送和接收字符XOFF值 Tx and Rx XOFF character 
  64.    public char ErrorChar;          // 本字符用来代替接收到的奇偶校验发生错误时的值 error replacement character 
  65.    public char EofChar;            // 当没有使用二进制模式时,本字符可用来指示数据的结束 end of input character 
  66.    public char EvtChar;            // 当接收到此字符时,会产生一个事件 received event character 
  67.    public ushort wReserved1;         // 未使用 reserved; do not use 
  68.   }
  69.   [StructLayout(LayoutKind.Sequential)]
  70.    private struct COMMTIMEOUTS 
  71.   {  
  72.    public int ReadIntervalTimeout; 
  73.    public int ReadTotalTimeoutMultiplier; 
  74.    public int ReadTotalTimeoutConstant; 
  75.    public int WriteTotalTimeoutMultiplier; 
  76.    public int WriteTotalTimeoutConstant; 
  77.   }  
  78.   [StructLayout(LayoutKind.Sequential)] 
  79.    private struct OVERLAPPED 
  80.   { 
  81.    public int  Internal; 
  82.    public int  InternalHigh; 
  83.    public int  Offset; 
  84.    public int  OffsetHigh; 
  85.    public int hEvent; 
  86.   }  
  87.   
  88.   [DllImport("coredll.dll")]
  89.   private static extern int CreateFile(
  90.    string lpFileName,                         // 要打开的串口名称
  91.    uint dwDesiredAccess,                      // 指定串口的访问方式,一般设置为可读可写方式
  92.    int dwShareMode,                          // 指定串口的共享模式,串口不能共享,所以设置为0
  93.    int lpSecurityAttributes, // 设置串口的安全属性,WIN9X下不支持,应设为NULL
  94.    int dwCreationDisposition,                // 对于串口通信,创建方式只能为OPEN_EXISTING
  95.    int dwFlagsAndAttributes,                 // 指定串口属性与标志,设置为FILE_FLAG_OVERLAPPED(重叠I/O操作),指定串口以异步方式通信
  96.    int hTemplateFile                        // 对于串口通信必须设置为NULL
  97.    );
  98.   [DllImport("coredll.dll")]
  99.   private static extern bool GetCommState(
  100.    int hFile,  //通信设备句柄
  101.    ref DCB lpDCB    // 设备控制块DCB
  102.    ); 
  103.   [DllImport("coredll.dll")]
  104.   private static extern bool BuildCommDCB(
  105.    string lpDef,  // 设备控制字符串
  106.    ref DCB lpDCB     // 设备控制块
  107.    );
  108.   [DllImport("coredll.dll")]
  109.   private static extern bool SetCommState(
  110.    int hFile,  // 通信设备句柄
  111.    ref DCB lpDCB    // 设备控制块
  112.    );
  113.   [DllImport("coredll.dll")]
  114.   private static extern bool GetCommTimeouts(
  115.    int hFile,                  // 通信设备句柄 handle to comm device
  116.    ref COMMTIMEOUTS lpCommTimeouts  // 超时时间 time-out values
  117.    ); 
  118.   [DllImport("coredll.dll")] 
  119.   private static extern bool SetCommTimeouts(
  120.    int hFile,                  // 通信设备句柄 handle to comm device
  121.    ref COMMTIMEOUTS lpCommTimeouts  // 超时时间 time-out values
  122.    );
  123.   [DllImport("coredll.dll")]
  124.   private static extern bool ReadFile(
  125.    int hFile,                // 通信设备句柄 handle to file
  126.    byte[] lpBuffer,             // 数据缓冲区 data buffer
  127.    int nNumberOfBytesToRead,  // 多少字节等待读取 number of bytes to read
  128.    ref int lpNumberOfBytesRead, // 读取多少字节 number of bytes read
  129.    ref OVERLAPPED lpOverlapped    // 溢出缓冲区 overlapped buffer
  130.    );
  131.   [DllImport("coredll.dll")] 
  132.   private static extern bool WriteFile(
  133.    int hFile,                    // 通信设备句柄 handle to file
  134.    byte[] lpBuffer,                // 数据缓冲区 data buffer
  135.    int nNumberOfBytesToWrite,     // 多少字节等待写入 number of bytes to write
  136.    ref int lpNumberOfBytesWritten,  // 已经写入多少字节 number of bytes written
  137.    ref OVERLAPPED lpOverlapped        // 溢出缓冲区 overlapped buffer
  138.    );
  139.   [DllImport("coredll.dll")]
  140.   private static extern bool CloseHandle(
  141.    int hObject   // handle to object
  142.    );
  143.   [DllImport("coredll.dll")]
  144.   private static extern uint GetLastError();
  145.   
  146.   public void Open()
  147.   {
  148.   
  149.    DCB dcbCommPort = new DCB();
  150.    COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); 
  151.      
  152.    // 打开串口 OPEN THE COMM PORT.
  153.    hComm = CreateFile(PortNum ,GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);
  154.    // 如果串口没有打开,就打开 IF THE PORT CANNOT BE OPENED, BAIL OUT.
  155.    if(hComm == INVALID_HANDLE_VALUE) 
  156.    {
  157.     throw(new ApplicationException("非法操作,不能打开串口!"));
  158.    }
  159.   
  160.    // 设置通信超时时间 SET THE COMM TIMEOUTS.
  161.    GetCommTimeouts(hComm,ref ctoCommPort);
  162.    ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
  163.    ctoCommPort.ReadTotalTimeoutMultiplier = 0;
  164.    ctoCommPort.WriteTotalTimeoutMultiplier = 0;
  165.    ctoCommPort.WriteTotalTimeoutConstant = 0;  
  166.    SetCommTimeouts(hComm,ref ctoCommPort);
  167.   
  168.    // 设置串口 SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
  169.    GetCommState(hComm, ref dcbCommPort);
  170.    dcbCommPort.BaudRate=BaudRate;
  171.    dcbCommPort.flags=0;
  172.    //dcb.fBinary=1;
  173.    dcbCommPort.flags|=1;
  174.    if (Parity>0)
  175.    {
  176.     //dcb.fParity=1
  177.     dcbCommPort.flags|=2;
  178.    }
  179.    dcbCommPort.Parity=Parity;
  180.    dcbCommPort.ByteSize=ByteSize;
  181.    dcbCommPort.StopBits=StopBits;
  182.    if (!SetCommState(hComm, ref dcbCommPort))
  183.    {
  184.     //uint ErrorNum=GetLastError();
  185.     throw(new ApplicationException("非法操作,不能打开串口!"));
  186.    }
  187.    //unremark to see if setting took correctly
  188.    //DCB dcbCommPort2 = new DCB();
  189.    //GetCommState(hComm, ref dcbCommPort2);
  190.    Opened = true;
  191.   }
  192.   
  193.   public void Close() 
  194.   {
  195.    if (hComm!=INVALID_HANDLE_VALUE) 
  196.    {
  197.     CloseHandle(hComm);
  198.    }
  199.   }
  200.   
  201.   public byte[] Read(int NumBytes) 
  202.   {
  203.    byte[] BufBytes;
  204.    byte[] OutBytes;
  205.    BufBytes = new byte[NumBytes];
  206.    if (hComm!=INVALID_HANDLE_VALUE) 
  207.    {
  208.     OVERLAPPED ovlCommPort = new OVERLAPPED();
  209.     int BytesRead=0;
  210.     ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
  211.     try
  212.     {
  213.      OutBytes = new byte[BytesRead];
  214.      Array.Copy(BufBytes,0,OutBytes,0,BytesRead);
  215.     }
  216.     catch
  217.     {
  218.      return BufBytes;
  219.     }
  220.     
  221.    } 
  222.    else 
  223.    {
  224.     throw(new ApplicationException("串口未打开!"));
  225.    }
  226.    return OutBytes;
  227.    //   return BufBytes;
  228.   }
  229.   
  230.   public void Write(byte[] WriteBytes) 
  231.   {
  232.    if (hComm!=INVALID_HANDLE_VALUE) 
  233.    {
  234.     OVERLAPPED ovlCommPort = new OVERLAPPED();
  235.     int BytesWritten = 0;
  236.     WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);
  237.    }
  238.    else 
  239.    {
  240.     throw(new ApplicationException("串口未打开!"));
  241.    }  
  242.   }
  243.   public string GetGPS(string strGPS,string strFind)
  244.   {
  245.    ///从GPS中读取的数据中,找出想要的数据
  246.    ///GPSstring原始字符串,
  247.    ///strFind要查找的内容,X:经度,Y:纬度,T:时间,V:速度,是数字从1开始,即以“,”分隔的位置
  248.    ///返回查找到指定位置的字符串
  249.    string handerStr="$GPRMC";//GPS串头
  250.    int findHander=strGPS.IndexOf(handerStr);//看是否含有GPS串头
  251.    if (findHander<0)
  252.    {
  253.     return "-1";
  254.    }
  255.    else
  256.    {
  257.     strGPS=strGPS.Substring(findHander,strGPS.Length-findHander);
  258.     string[] ArryTmp=strGPS.Split(",".ToCharArray());
  259.     try
  260.     {
  261.      if(ArryTmp[2]=="V")
  262.      {
  263.       return "V";//没有信号
  264.      }
  265.      else
  266.      {
  267.       switch(strFind)
  268.       {
  269.        case "X":
  270.         return DM2DD(ArryTmp[5]);
  271.         
  272.        case "Y":
  273.         return DM2DD(ArryTmp[3]);
  274.         
  275.        case "T":
  276.         return T2Time(ArryTmp[9],ArryTmp[1]);
  277.         
  278.        case "V":
  279.         return Convert.ToString(Convert.ToDouble(ArryTmp[7])* 1.852);
  280.         
  281.        default:
  282.         return "V";
  283.         
  284.       }
  285.      }
  286.     }
  287.     catch
  288.     {
  289.      return "V";
  290.     }
  291.    }
  292.   }
  293.   public string T2Time(string strDate,string strTime)
  294.   {
  295.    string dT="20"+strDate.Substring(4,2)+"-"+strDate.Substring(2,2)+"-"+strDate.Substring(0,2);
  296.    string TT=Convert.ToString(Convert.ToInt32(strTime.Substring(0,2)))+":"+strTime.Substring(2,2)+":"+strTime.Substring(4,2);
  297.    DateTime T=Convert.ToDateTime(dT+" "+TT);
  298.    T=T.AddHours(8);
  299.    return T.ToString();
  300.   }
  301.   public string DM2DD(string DegreeMinutes)
  302.   {
  303.    //转换NMEA协议的“度分”格式为十进制“度度”格式
  304.    string sDegree;
  305.    string sMinute;
  306.    string sReturn="";
  307.    if(DegreeMinutes.IndexOf(".")==4)
  308.    {
  309.     //DegreeMinutes = Replace(DegreeMinutes, ".", "")
  310.     //DM2DD = CDbl(Left(DegreeMinutes, 2)) + CDbl(Left(CStr(CDbl(Right(DegreeMinutes, Len(DegreeMinutes) - 2)) / 60), 8)) / 10000
  311.     DegreeMinutes=DegreeMinutes.Replace(".","");
  312.     double sDegree1=Convert.ToDouble(DegreeMinutes.Substring(0,2));
  313.     double sDegree2=Convert.ToDouble(DegreeMinutes.Substring(2,DegreeMinutes.Length-2));
  314.     string sTmp=Convert.ToString(sDegree2/60);
  315.     sDegree2=Convert.ToDouble(sTmp.Substring(0,sTmp.Length));
  316.     sDegree2=sDegree2/10000;
  317.     sDegree=Convert.ToString(sDegree1+sDegree2);
  318.     if(sDegree.Length>11)
  319.      sDegree=sDegree.Substring(0,11);
  320.     sReturn=sDegree;
  321.    }
  322.    else if(DegreeMinutes.IndexOf(".")==5)
  323.    {
  324.     //DegreeMinutes = Replace(DegreeMinutes, ".", "")
  325.     //DM2DD = CDbl(Left(DegreeMinutes, 2)) + CDbl(Left(CStr(CDbl(Right(DegreeMinutes, Len(DegreeMinutes) - 2)) / 60), 8)) / 10000
  326.     DegreeMinutes=DegreeMinutes.Replace(".","");
  327.     double sMinute1=Convert.ToDouble(DegreeMinutes.Substring(0,3));
  328.     double sMinute2=Convert.ToDouble(DegreeMinutes.Substring(3,DegreeMinutes.Length-3));
  329.     string sTmp=Convert.ToString(sMinute2/60);
  330.     sMinute2=Convert.ToDouble(sTmp.Substring(0,sTmp.Length));
  331.     sMinute2=sMinute2/10000;
  332.     sMinute=Convert.ToString(sMinute1+sMinute2);
  333.     if(sMinute.Length>10)
  334.      sMinute=sMinute.Substring(0,10);
  335.     sReturn=sMinute;
  336.    }
  337.    return sReturn;
  338.   }
  339.   public bool ScanPort()
  340.   {
  341.    
  342.    try
  343.    {
  344.     if (Opened)
  345.     {
  346.      Close();
  347.      Open();
  348.     }
  349.     else
  350.     {
  351.      Open();//打开串口
  352.      
  353.     }
  354.     byte[] bytRead=Read(512);
  355.     Close();
  356.     if(Encoding.ASCII.GetString(bytRead,0,bytRead.Length).IndexOf("$GP")>=0)
  357.      return true;
  358.     else
  359.      return false;
  360.    }
  361.    catch
  362.    {
  363.     return false;
  364.    }
  365.   }
  366.  }
  367.  class HexCon 
  368.  {
  369.   // 把十六进制字符串转换成字节型和把字节型转换成十六进制字符串 converter hex string to byte and byte to hex string
  370.   public static string ByteToString(byte[] InBytes) 
  371.   {
  372.    string StringOut="";
  373.    foreach (byte InByte in InBytes) 
  374.    {
  375.     StringOut=StringOut + String.Format("{0:X2} ",InByte);
  376.    }
  377.    return StringOut; 
  378.   }
  379.   public static byte[] StringToByte(string InString) 
  380.   {
  381.    string[] ByteStrings;
  382.    ByteStrings = InString.Split(" ".ToCharArray());
  383.    byte[] ByteOut;
  384.    ByteOut = new byte[ByteStrings.Length-1];
  385.    for (int i = 0;i==ByteStrings.Length-1;i++) 
  386.    {
  387.     ByteOut[i] = Convert.ToByte(("0x" + ByteStrings[i]));
  388.    } 
  389.    return ByteOut;
  390.   }
  391.  }
  392. }
  393. 在别的class中调用时如Frmlogoin(是通过一个时间控件来循环的)
  394. public class Frmlogin : System.Windows.Forms.Form
  395.  {
  396. private GPS ss_port=new GPS();
  397. }
  398. #region 读取GPS
  399.   private void opengps(string ComPoint)
  400.   {
  401.    ss_port.PortNum = ComPoint;
  402.    ss_port.BaudRate = 4800;
  403.    ss_port.ByteSize = 8;
  404.    ss_port.Parity = 0;
  405.    ss_port.StopBits = 1;
  406.    ss_port.ReadTimeout = 1000;
  407.    try
  408.    {
  409.     if (ss_port.Opened)
  410.     {
  411.      ss_port.Close();
  412.      ss_port.Open();
  413.      timer1.Enabled=true;
  414.     }
  415.     else
  416.     {
  417.      ss_port.Open();//打开串口
  418.      timer1.Enabled=true;
  419.     }
  420.     
  421.    }
  422.    catch
  423.     
  424.    {
  425. //    MessageBox.Show("读取GPS错误!" ,"系统提示");
  426.     
  427.    }
  428.   }
  429.   private void timer1_Tick(object sender, System.EventArgs e)
  430.   {
  431.    
  432.    if (ss_port.Opened)
  433.     gpsread();
  434.    else
  435.     ss_port.Open();//打开串口
  436.   }
  437.   
  438.   private void gpsread()
  439.   {
  440.    byte[] aa=ss_port.Read(512);
  441.    string gpsinfo =System.Text.Encoding.ASCII.GetString(aa,0,aa.Length);
  442.    GetParam.GpsLongitude=ss_port.GetGPS(gpsinfo,"X");
  443.    GetParam.GpsLatitude=ss_port.GetGPS(gpsinfo,"Y");
  444.    GetParam.GpsSpeed=ss_port.GetGPS(gpsinfo,"V");
  445.    GetParam.GpsTime=ss_port.GetGPS(gpsinfo,"T");
  446.    if(GetParam.GpsLongitude=="-1"
  447.     GetParam.GpsState="0";
  448.    if(GetParam.GpsLongitude=="V" && GetParam.GpsLatitude=="V")
  449.     GetParam.GpsState="0";
  450.    if(GetParam.GpsLongitude!="-1" && GetParam.GpsLongitude!="V")
  451.     GetParam.GpsState="1";
  452.     GetParam.GpsLongitude=(GetParam.GpsLongitude=="V") ? "0" : GetParam.GpsLongitude;
  453.     GetParam.GpsLatitude=(GetParam.GpsLatitude=="V") ? "0" : GetParam.GpsLatitude;
  454.     GetParam.GpsSpeed=(GetParam.GpsSpeed=="V") ? "0" : GetParam.GpsSpeed;
  455.     GetParam.GpsTime=(GetParam.GpsTime=="V") ? "0" :GetParam.GpsTime;
  456.    
  457.   }
  458.   private void GpsClose()
  459.   {
  460.    timer1.Enabled=false;
  461.    if (ss_port.Opened)
  462.     ss_port.Close();
  463.   }


 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值