GPS接收机(五)基于C#的GPS软件上位机

前面已经搭建了一个可以接受GPS数据的简易接收机,接下来将要编写一个上位机处理接收到的数据,并进行处理显示。

效果示意图

接收文本数据,并进行表格显示
在这里插入图片描述
接受文本数据,并进行图表显示
在这里插入图片描述

前台代码如下

    <Grid>
        <TextBox x:Name="Tip" HorizontalAlignment="Left" Height="24" Margin="8,176,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="40" BorderBrush="{x:Null}" Background="{x:Null}" FontSize="16" IsReadOnly="True" Foreground="Black" HorizontalContentAlignment="Center" Text="提示"/>
        <ComboBox x:Name="Port_Select" RenderTransformOrigin="1.436,2.058" BorderBrush="Black" Foreground="Black" FontFamily="Microsoft YaHei" Background="{x:Null}" Height="32" VerticalAlignment="Top" HorizontalAlignment="Left" Width="76" MouseEnter="PortSelect_MouseEnter" Margin="75,30,0,0" FontSize="13.333" VerticalContentAlignment="Center"/>
        <Button x:Name="Port_Open" Content="打开串口" Margin="75,170,0,0" RenderTransformOrigin="-0.833,1.211" Click="PortOpen_Click" Background="{x:Null}" BorderBrush="Black" FontFamily="Microsoft YaHei" FontSize="16" HorizontalAlignment="Left" Width="76" Height="32" VerticalAlignment="Top"/>
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="300" Margin="186,36,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="396"/>
        <GroupBox Header="接收数据" Height="326" HorizontalAlignment="Left" Margin="186,10,0,0" x:Name="GroupBox" VerticalAlignment="Top" Width="396"/>
        <ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="75,103,0,0" VerticalAlignment="Top" Width="76" Background="{x:Null}" Height="32" FontSize="13.333" VerticalContentAlignment="Center" >
            <ComboBoxItem Content="9600"/>
            <ComboBoxItem Content="14400"/>
            <ComboBoxItem Content="19200"/>
            <ComboBoxItem Content="38400"/>
            <ComboBoxItem Content="57600"/>
            <ComboBoxItem Content="115200"/>
        </ComboBox>
        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="8,36,0,0" VerticalAlignment="Top" RenderTransformOrigin="-0.673,-3.125" Height="24" Width="40" Text="端口" FontSize="16" LineHeight="8" TextWrapping="Wrap" TextAlignment="Center"/>
        <TextBlock x:Name="textBlock1" HorizontalAlignment="Left" Margin="8,108,0,0" TextWrapping="Wrap" Text="波特率" VerticalAlignment="Top" Width="60" Height="28" FontSize="16"/>
        <Button x:Name="clr" Content="clear" HorizontalAlignment="Left" Margin="8,240,0,0" VerticalAlignment="Top" Width="50" Click="Clr_Click" Height="28" FontSize="16" Background="{x:Null}"/>
        <Button x:Name="chart" Content="chart" HorizontalAlignment="Left" Margin="100,240,0,0" VerticalAlignment="Top" Width="50" Click="Chart_Click" Height="28" Background="{x:Null}" FontSize="16"/>
        <Button x:Name="table" Content="table" HorizontalAlignment="Left" Margin="100,300,0,0" VerticalAlignment="Top" Width="50" RenderTransformOrigin="0.037,-0.94" Height="28" Background="{x:Null}" FontSize="16" Click="Table_Click"/>
        <Button x:Name="save" Content="save" HorizontalAlignment="Left" Margin="8,300,0,0" VerticalAlignment="Top" Width="50" Height="28" Background="{x:Null}" FontSize="16" Click="Save_Click"/>
    </Grid>

后台代码如下

public  partial class MainWindow : Window
    {
        string getstring = "";
        string putoutstring = "";
        //声明串口
        SerialPort ComPort = new SerialPort();
        public delegate void Display(byte[] buffer);
        public Display Dis_UI;
        public   MainWindow()
        {     
            InitializeComponent();
            ComPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
            Dis_UI = new Display(display);
        }
        //接收数据事件
        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int count = ComPort.BytesToRead;
            byte[] buffer = new byte[count];
            ComPort.Read(buffer, 0, count);
            //多线程操作UI
            this.Dispatcher.Invoke(Dis_UI, buffer);
        }
        public  void display(byte[] buf)
        {
            for (int i = 0; i < buf.Length; i++)
                {
                    getstring += Char.ConvertFromUtf32(buf[i]);
                }
            
            if  (getstring .Contains(@"$GNVTG") )
                {
                    App.wxid.Clear();
                    App.wxxzb.Clear();
                    string pattern = @"\$BDGSA,(?<GPS>[\s\S]+)\$BDGSV";
                    Match mc = Regex .Match(getstring, pattern);
                    string tempStr = mc.Groups["GPS"].ToString ();
                    string[] Gpsarray = Regex.Split(tempStr, "\r\n", RegexOptions.IgnoreCase);
                    foreach (string istring in Gpsarray)
                    {
                        try
                        {
                            if (istring.Contains(@"$GPGSV"))
                            {
                                string[] sArray = Regex.Split(istring, ",", RegexOptions.IgnoreCase);
                                try
                                {
                                    App.wxid.Add(sArray[4]);
                                    App.wxxzb.Add(Convert.ToDouble(sArray[7]));
                                }
                                catch
                                {
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                    textBox.Text =getstring+ "\n" + System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\n";
                    putoutstring = getstring + "\n" + System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\n";
                    getstring = "";
                }
        }
        //串口集
        public string[] portNames { get; set; }
        //打开标志
        bool openFlag = false;
        //得到当前可用串口
        private void GetPort()
        {
            portNames = SerialPort.GetPortNames();         //得到可用串口
            if (portNames.Length > 0)
            {
                Tip.Text = "检测到" + portNames.Length + "个可用串口";
            }
            else
            {
                Tip.Text = "未检测到串口";
                Port_Select.ItemsSource = null;
                return;
            }
            Port_Select.ItemsSource = portNames;           //添加可用串口
            Port_Select.SelectedValue = portNames[0];      //默认选中
        }
        //打开事件
        private void PortOpen_Click(object sender, RoutedEventArgs e)
        {
            OpenPort();
        }
        //鼠标进入事件
        private void PortSelect_MouseEnter(object sender, MouseEventArgs e)
        {
            if (openFlag == false)
            {
                GetPort();
            }
        }
        //打开串口方法
        private void OpenPort()
        {
            if (Port_Select.SelectedValue == null)
            {
                GetPort();
            }
            if (openFlag == false)
            {
                try
                {
                    //设置
                    ComPort.PortName = Port_Select.SelectedValue.ToString();
                    ComPort.BaudRate = Convert.ToInt32(comboBox.SelectionBoxItem.ToString ());
                    ComPort.Parity = Parity.None;
                    ComPort.StopBits = StopBits.One;
                    ComPort.DataBits = 8;
                    ComPort.Handshake = Handshake.None;
                    // ComPort.RtsEnable = true;
                    ComPort.Open();
                    Tip.Text = "打开成功";
                    openFlag = true;
                    Port_Open.Content = "关闭串口";
                }
                catch
                {
                    Tip.Text = "打开失败";
                }
            }
            else
            {
                try
                {
                    ComPort.DiscardInBuffer();
                    ComPort.DiscardOutBuffer();
                    ComPort.Close();
                    openFlag = false;
                    Port_Open.Content = "打开串口";
                    Tip.Text = "关闭成功";
                }
                catch
                {
                    Tip.Text = "关闭失败";
                }
            }
        }
        //清除显示文本
        private void Clr_Click(object sender, RoutedEventArgs e)
        {
            this.textBox .Text ="";
        }
        //打开图表窗口
        private void Chart_Click(object sender, RoutedEventArgs e)
        {
            chartwindow Chartwindow = new chartwindow();
            Chartwindow.Show();
        }
        //打开表格窗口
        private void Table_Click(object sender, RoutedEventArgs e)
        {
            table Table = new ck.table();
            Table.Show();
        }
        //保存数据文本
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "文本(*.txt)|*.txt;|Excle(*.xls)|*.xls";
            if (saveDlg.ShowDialog() == true)
            {
                using (FileStream fs = new FileStream(saveDlg.FileName, FileMode.Create))
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                    {
                        sw.WriteLine(putoutstring);
                    }
                }
            }
        }
    }
全套源代码,请咨询 ny_mrzhang@hotmail.com QQ:97302751 以前的协议是这样的。。。车载设备发往网络中心位置数据-80[功能] 车载设备向网络中心发送当前位置信息[去向] 网络中心[数据入库] 网络中心收到数据后将数据保存到动态位置数据表中 (DynData)[格式] 29 29 80 len1 len2 d3d2d1d0 yymmddhhmmss jjjj wwww ssff st lichen1 lichen2 lichen3 st1st2st3 st4 v1v2v3v4v5v6v7v8 len1 len2: 包长d3d2d1d0: 伪IP,终端ID号yymmddhhmmss:年月日时分秒日期表示范围:年份,后两位 ;月份,1-12;日期,1-31时间表示范围:小时,00——23;分钟,00——59;秒,00——59时、分、秒均采用压缩BCD编码。[例如]: 10点23分15秒表示为: 10H,23H,15Hjjjj:经度经度表示范围:000度00.000分——179度59.999分;采用压缩BCD编码,但最高位是符号位。“正”表示“东经”,“负”表示“西经”;“分”的单位是:千分之一分。[例如]: 西经130度45.608分表示为:(注意:1度=60分) 13H,04H,56H,08Hwwww:纬度纬度表示范围:00度00.000分——89度59.999分;采用压缩BCD编码,但最高位是符号位。“正”表示“北纬”,“负”表示“南纬”;“分”的单位是:千分之一分。[例如]: 南纬30度37.901分表示为: 3H,03H,79H,01Hssff:速度方向速度表示方法:表示范围:0——9999公里/小时采用压缩BCD编码。[例如]: 120公里/小时表示为: 01H,20H方位表示方法:表示范围:000——359度采用压缩BCD编码,正北为0度,顺时针方向计数。单位为:度。[例如]: 154度表示为: 01H,54Hst:定位,天线,电源状态定位状态由单字节组成,各位含义如下: D7 D6 D5 D4 D3 D2 D1 D0D7 定位标志0 GPS未定位1 GPS已定位D6 D5 1 1 GPS正常1 0 GPS天线短路0 1 GPS天线开路0 0 GPS天线故障D4 D3 电源状态1 1 正常1 0 主电源掉电0 1 主电源过高或过低 D2 D1 D0 保留 lichen1 lichen2 lichen3:里程数 HEX 格式:0——0XFFFFFF (0——16777215)米st1st2st3 st4:车辆状态现在协议格式:*HQ,000,S12,130305,60# 上传短信*HQ,000,S4,121212,0F,FF# 速度显示*HQ,000,S4,121212,9F,FF# 断油断电
要改协议,,高手帮下忙。。在线等。<br>using System;<br>using System.Drawing;<br>using System.Collections;<br>using System.ComponentModel;<br>using System.Windows.Forms;<br>using System.Data;<br>using System.Messaging;<br>using System.Net.Sockets;<br>using System.Text;<br>using System.Runtime.InteropServices;<br>using System.IO;<br>using System.Threading ;<br>using System.Net;<br><br>namespace GprsServer<br>{<br> /// <summary><br> /// Form1 的摘要说明。<br> /// </summary><br> public class GprsServer : System.Windows.Forms.Form<br> {<br> /// <summary><br> /// 必需的设计器变量。<br> /// </summary><br> <br> [DllImport("User32.dll",EntryPoint="SendMessage")]<br> private static extern int <br> SendMessage(<br> int hWnd, // handle to destination window<br> int Msg, // message<br> int wParam, // first message parameter<br> string lParam // second message parameter<br> );<br> [DllImport("User32.dll",EntryPoint="FindWindow")]<br> private static extern int FindWindow(string lpClassName,string lpWindowName);<br><br> [DllImport("kernel32.dll")]<br> public static extern int GetPrivateProfileString ( string section ,string key , string def , StringBuilder retVal ,int size , string filePath ) ;<br> [DllImport("kernel32")] <br> public static extern long WritePrivateProfileString ( string section,string key,string val,string filePath ) ;<br><br> private System.ComponentModel.IContainer components;<br><br> public static int LocaPort;//本地端口<br> public static string RemoteIp;<br> public static int RemotePort;//远程端口<br> public static string sCompanyName;//公司名称<br><br> private Icon m_Icon1; <br> private Icon m_Icon2;<br> private Icon m_Icon3;<br><br> private NotifyIcon notifyIcon;<br><br> MenuItem menuItem1;<br> MenuItem menuItem2;<br><br> private Hashtable CarID_RemoteIP_Hash;<br><br> private Thread thGprs ;<br> private Thread thTcpMsg ;<br> private Socket socket;<br> private Socket TcpSocket;<br><br> private System.Windows.Forms.Timer TimerIcon;<br> private System.Windows.Forms.Label lblInfo;<br> private System.Windows.Forms.Timer TimerConn;<br> private byte[] TempBuff;<br> private System.Windows.Forms.CheckBox checkBox1;<br> private System.Windows.Forms.ImageList imgList;// = new byte[1024];<br> private byte[] TcpBuff;<br> private System.Windows.Forms.ListView lvwMsg;<br> private System.Windows.Forms.ColumnHeader sId;<br> private System.Windows.Forms.ColumnHeader sNote;<br> private System.Windows.Forms.Button cmdExit;<br> private System.Windows.Forms.Button cmdSet;// = new byte[2048];<br><br> private bool bTsFlag=false;<br> public GprsServer()<br> {<br><br> InitializeComponent();<br> //检测配置文件目录是否存在<br> GetSysPra();<br><br> TempBuff= new byte[1];<br> TcpBuff=new byte[1];<br><br> m_Icon1 = new Icon("SysFile\\Icon1.ico");<br> m_Icon2 = new Icon("SysFile\\Icon2.ico"); <br> m_Icon3 = new Icon("SysFile\\Icon3.ico"); <br><br> notifyIcon = new NotifyIcon(); <br> notifyIcon.Icon = m_Icon1; <br> notifyIcon.Text = sCompanyName; <br> notifyIcon.Visible = true; <br><br> menuItem1=new MenuItem("设置"); <br> menuItem2=new MenuItem("退出"); <br><br> menuItem1.Click+=new EventHandler(this.menuItem1_Click); <br> menuItem2.Click+=new EventHandler(this.menuItem2_Click); <br><br> notifyIcon.ContextMenu=new ContextMenu(new MenuItem[]{menuItem1,menuItem2}); <br> notifyIcon.DoubleClick+=new System.EventHandler(this.notifyIcon_DBClick); <br><br> CarID_RemoteIP_Hash=new Hashtable();<br><br> thGprs = new Thread(new ThreadStart(ReadUdp)) ;<br> //启动线程<br> thGprs.IsBackground =true;//将线程作为后台线程处理,用途,当主线程关闭,子线程随着关闭<br> thGprs.Start( );<br><br> try<br> {<br> IPHostEntry IPHost = Dns.Resolve(RemoteIp);<br> string []aliases = IPHost.Aliases; <br> IPAddress []addr = IPHost.AddressList;<br> EndPoint ep = new IPEndPoint(addr[0],RemotePort); <br> TcpSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);<br> TcpSocket.Connect(ep);<br><br> thTcpMsg = new Thread (new ThreadStart(ReadTcpMsg)) ;<br> //启动线程<br> thTcpMsg.IsBackground =true;<br> thTcpMsg.Start( ) ;<br> lblInfo.Text ="系统运行正常,正在中转GPRS数据...";<br> }<br> catch<br> {}<br> }<br><br> private void GetSysPra()<br> {<br> StringBuilder temp = new StringBuilder(255);<br> if (Directory.Exists("SysIni"))<br> {<br> if (File.Exists("SysIni\\SysIni.ini"))<br> {<br> int i;<br> i= GetPrivateProfileString("PortIni","UdpPort","",temp,255,"SysIni\\SysIni.ini");<br> if (i==0)<br> {<br> LocaPort=8888;<br> WritePrivateProfileString("PortIni","UdpPort","8888","SysIni\\SysIni.ini");<br> }<br> else<br> {<br> LocaPort=int.Parse(temp.ToString( ));<br> }<br> i = GetPrivateProfileString("Company","Name","",temp,255,"SysIni\\SysIni.ini");<br> if (i==0)<br> {<br> sCompanyName="龙翰科技";<br> WritePrivateProfileString("Company","Name","龙翰科技","SysIni\\SysIni.ini");<br> }<br> else<br> {<br> sCompanyName=temp.ToString( );<br> }<br> i = GetPrivateProfileString("PortIni","TcpAddress","",temp,255,"SysIni\\SysIni.ini");<br> if (i==0)<br> {<br> RemoteIp="127.0.0.1";<br> WritePrivateProfileString("PortIni","TcpAddress","127.0.0.1","SysIni\\SysIni.ini");<br> }<br> else<br> {<br> RemoteIp=temp.ToString( );<br> }<br> i = GetPrivateProfileString("PortIni","TcpPort","",temp,255,"SysIni\\SysIni.ini");<br> if (i==0)<br> {<br> RemotePort=6666;<br> WritePrivateProfileString("PortIni","TcpPort","6666","SysIni\\SysIni.ini");<br> }<br> else<br> {<br> RemotePort=int.Parse(temp.ToString( ));<br> }<br> }<br> else<br> {<br> //File.Create("SysIni\\SysIni.ini",255);<br> LocaPort=8888;<br> WritePrivateProfileString("PortIni","UdpPort","8888","SysIni\\SysIni.ini");<br> sCompanyName="龙翰科技";<br> WritePrivateProfileString("Company","Name","龙翰科技","SysIni\\SysIni.ini");<br> RemoteIp="127.0.0.1";<br> WritePrivateProfileString("PortIni","TcpAddress","127.0.0.1","SysIni\\SysIni.ini");<br> RemotePort=6666;<br> WritePrivateProfileString("PortIni","TcpPort","6666","SysIni\\SysIni.ini");<br> }<br> }<br> else<br> {<br> Directory.CreateDirectory("SysIni");<br> //File.Create("SysIni\\SysIni.ini",255);<br> LocaPort=8888;<br> WritePrivateProfileString("PortIni","UdpPort","8888","SysIni\\SysIni.ini");<br> sCompanyName="龙翰科技";<br> WritePrivateProfileString("Company","Name","龙翰科技","SysIni\\SysIni.ini");<br> RemoteIp="127.0.0.1";<br> WritePrivateProfileString("PortIni","TcpAddress","127.0.0.1","SysIni\\SysIni.ini");<br> RemotePort=6666;<br> WritePrivateProfileString("PortIni","TcpPort","6666","SysIni\\SysIni.ini");<br> }<br> }<br> /// <summary><br> /// 清理所有正在使用的资源。<br> /// </summary><br> <br> private void menuItem1_Click(object sender,System.EventArgs e)<br> { <br> //<br> } <br> private void menuItem2_Click(object sender,System.EventArgs e)<br> { <br> this.Close(); <br> Application.Exit(); <br> } <br> private void notifyIcon_DBClick(object sender, System.EventArgs e)<br> {<br> //<br> }<br><br> protected override void Dispose( bool disposing )<br> {<br> if( disposing )<br> {<br> if (components != null) <br> {<br> components.Dispose();<br> }<br> notifyIcon.Visible =false;; <br> notifyIcon.Icon=null;<br> notifyIcon.Dispose();<br> m_Icon1.Dispose();<br> m_Icon2.Dispose();<br> m_Icon3.Dispose();<br> }<br> base.Dispose( disposing );<br> }<br><br> #region Windows 窗体设计器生成的代码<br> /// <summary><br> /// 设计器支持所需的方法 - 不要使用代码编辑器修改<br> /// 此方法的内容。<br> /// </summary><br> private void InitializeComponent()<br> {<br> this.components = new System.ComponentModel.Container();<br> System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(GprsServer));<br> this.TimerIcon = new System.Windows.Forms.Timer(this.components);<br> this.lblInfo = new System.Windows.Forms.Label();<br> this.TimerConn = new System.Windows.Forms.Timer(this.components);<br> this.lvwMsg = new System.Windows.Forms.ListView();<br> this.sId = new System.Windows.Forms.ColumnHeader();<br> this.sNote = new System.Windows.Forms.ColumnHeader();<br> this.imgList = new System.Windows.Forms.ImageList(this.components);<br> this.checkBox1 = new System.Windows.Forms.CheckBox();<br> this.cmdExit = new System.Windows.Forms.Button();<br> this.cmdSet = new System.Windows.Forms.Button();<br> this.SuspendLayout();<br> // <br> // TimerIcon<br> // <br> this.TimerIcon.Enabled = true;<br> this.TimerIcon.Interval = 1000;<br> this.TimerIcon.Tick += new System.EventHandler(this.TimerIcon_Tick);<br> // <br> // lblInfo<br> // <br> this.lblInfo.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;<br> this.lblInfo.Location = new System.Drawing.Point(4, 298);<br> this.lblInfo.Name = "lblInfo";<br> this.lblInfo.Size = new System.Drawing.Size(310, 23);<br> this.lblInfo.TabIndex = 0;<br> this.lblInfo.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;<br> // <br> // TimerConn<br> // <br> this.TimerConn.Enabled = true;<br> this.TimerConn.Interval = 6000;<br> this.TimerConn.Tick += new System.EventHandler(this.TimerConn_Tick);<br> // <br> // lvwMsg<br> // <br> this.lvwMsg.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {<br> this.sId,<br> this.sNote});<br> this.lvwMsg.FullRowSelect = true;<br> this.lvwMsg.Location = new System.Drawing.Point(2, 2);<br> this.lvwMsg.Name = "lvwMsg";<br> this.lvwMsg.Size = new System.Drawing.Size(564, 292);<br> this.lvwMsg.SmallImageList = this.imgList;<br> this.lvwMsg.TabIndex = 1;<br> this.lvwMsg.View = System.Windows.Forms.View.Details;<br> // <br> // sId<br> // <br> this.sId.Text = "";<br> this.sId.Width = 21;<br> // <br> // sNote<br> // <br> this.sNote.Text = "消息内容";<br> this.sNote.Width = 522;<br> // <br> // imgList<br> // <br> this.imgList.ColorDepth = System.Windows.Forms.ColorDepth.Depth16Bit;<br> this.imgList.ImageSize = new System.Drawing.Size(16, 16);<br> this.imgList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgList.ImageStream")));<br> this.imgList.TransparentColor = System.Drawing.Color.Transparent;<br> // <br> // checkBox1<br> // <br> this.checkBox1.FlatStyle = System.Windows.Forms.FlatStyle.Popup;<br> this.checkBox1.Location = new System.Drawing.Point(332, 300);<br> this.checkBox1.Name = "checkBox1";<br> this.checkBox1.Size = new System.Drawing.Size(104, 19);<br> this.checkBox1.TabIndex = 2;<br> this.checkBox1.Text = "显示调试数据";<br> this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);<br> // <br> // cmdExit<br> // <br> this.cmdExit.FlatStyle = System.Windows.Forms.FlatStyle.Popup;<br> this.cmdExit.Location = new System.Drawing.Point(504, 298);<br> this.cmdExit.Name = "cmdExit";<br> this.cmdExit.Size = new System.Drawing.Size(60, 22);<br> this.cmdExit.TabIndex = 3;<br> this.cmdExit.Text = "退出(&E)";<br> this.cmdExit.Click += new System.EventHandler(this.cmdExit_Click);<br> // <br> // cmdSet<br> // <br> this.cmdSet.FlatStyle = System.Windows.Forms.FlatStyle.Popup;<br> this.cmdSet.Location = new System.Drawing.Point(432, 298);<br> this.cmdSet.Name = "cmdSet";<br> this.cmdSet.Size = new System.Drawing.Size(60, 22);<br> this.cmdSet.TabIndex = 4;<br> this.cmdSet.Text = "设置(&S)";<br> this.cmdSet.Click += new System.EventHandler(this.cmdSet_Click);<br> // <br> // GprsServer<br> // <br> this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);<br> this.ClientSize = new System.Drawing.Size(566, 323);<br> this.Controls.Add(this.cmdSet);<br> this.Controls.Add(this.cmdExit);<br> this.Controls.Add(this.checkBox1);<br> this.Controls.Add(this.lvwMsg);<br> this.Controls.Add(this.lblInfo);<br> this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;<br> this.MaximizeBox = false;<br> this.Name = "GprsServer";<br> this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;<br> this.Text = "中继服务器";<br> this.Load += new System.EventHandler(this.GprsServer_Load);<br> this.ResumeLayout(false);<br><br> }<br> #endregion<br><br> /// <summary><br> /// 应用程序的主入口点。<br> /// </summary><br> [STAThread]<br> static void Main() <br> {<br> Application.Run(new GprsServer());<br> }<br><br> private byte Get_CheckXor(ref byte[] temp,int len)<br> {<br> byte A=0;<br> for(int i=0;i<len;i++)<br> {<br> A^=temp[i];<br> }<br> return A;<br> }<br><br> private void ReadTcpMsg() //读取用户发送的指令数据<br> {<br> byte[] buff= new byte[2048];<br> string CartIpAddress="";//车辆的IP地址<br> EndPoint TempRemote = null;<br><br> int recv = 0;<br> byte[] Tbuff;<br> byte[] AllBuff;<br> int iLenght=0;<br> int iIndex=0;<br> int iLen=0;<br> int iXorValue=0;<br><br> while(true)<br> {<br> try<br> {<br> recv=TcpSocket.Receive(buff,0,TcpSocket.Available,SocketFlags.None);//读取数据内容<br> if (recv==0)<br> {<br> recv=TcpSocket.Receive(buff,0,TcpSocket.Available,SocketFlags.None);//读取数据内容<br> if (recv==0)<br> {<br> TcpSocket.Close();<br> break;<br> }<br> }<br><br> }<br> catch<br> {<br> break;<br> }<br><br> AllBuff=new byte[recv +TcpBuff.Length];<br> for (iIndex = 1; iIndex <=TcpBuff.Length; iIndex++)<br> {<br> AllBuff[iIndex-1]=TcpBuff[iIndex-1];<br> }<br><br> for (iIndex = 1; iIndex <=recv; iIndex++)<br> {<br> AllBuff[TcpBuff.Length+iIndex-1]=buff[iIndex-1];<br> }<br><br> for (iIndex = 1; iIndex <=AllBuff.Length; iIndex++)<br> {<br> iLenght=AllBuff.Length-iIndex+1;<br> if (iLenght<6)//检测数据包长度<br> {<br> //不完整,则将指令保存<br> if (iLenght>0)<br> {<br> TcpBuff=new byte[iLenght];<br> for (iLen = 1; iLen <=iLenght; iLen++)<br> {<br> TcpBuff[iLen-1]=AllBuff[iLen+iIndex-2];<br> }<br> }<br> break;<br> }<br> else<br> {<br> //检测当前指令是否是完整的指令,查找数据包头<br> if (AllBuff[iIndex-1]==0x29 & AllBuff[iIndex]==0x29)<br> {<br> if ((AllBuff.Length -iIndex)>=(AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+4))<br> {<br> //检测当前指令是否是完整的指令<br> if ((AllBuff[AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+iIndex+3])==0x0D)<br> {<br> //在接收的数据中获取单条完整的指令数据<br> Tbuff=new byte[AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+5];<br> for (iLen = 1; iLen <=Tbuff.Length; iLen++)<br> {<br> Tbuff[iLen-1]=AllBuff[iLen+iIndex-2];<br> }<br> iXorValue=Get_CheckXor(ref Tbuff,Tbuff.Length-2);<br> if(iXorValue!=Tbuff[Tbuff.Length-2])<br> {<br> //校验不合格,继续查找合法指令数据<br> continue;<br> }<br> else<br> {<br> if (bTsFlag)<br> {<br> string BuffToStr="";<br> for(int i=0;i<Tbuff.Length;i++)<br> {<br> BuffToStr+=Tbuff[i].ToString("X2")+" ";<br> }<br> ShowSysMsg(BuffToStr,2);<br> }<br> //获取车载终端手机号<br> CartIpAddress=Tbuff[5]+"." +Tbuff[6] +"."+Tbuff[7] +"."+Tbuff[8];<br> TempRemote=(EndPoint)CarID_RemoteIP_Hash[CartIpAddress];<br> if( TempRemote==null)<br> {<br> if (bTsFlag)<br> {<br> ShowSysMsg("无法查找到接收数据的远程终节点!",3);<br> }<br> }<br> else<br> {<br> try<br> {<br> socket.SendTo(Tbuff,TempRemote);<br> if (bTsFlag)<br> {<br> ShowSysMsg("数据成功转发到车载终端!",1);<br> }<br> }<br> catch<br> {<br> if (bTsFlag)<br> {<br> ShowSysMsg("数据转发到车载终端失败!",3);<br> }<br> }<br> } <br> iIndex=iIndex+Tbuff.Length-1;<br> TcpBuff=new byte[1];<br> }<br> }<br> else<br> {<br> continue;<br> }<br> }<br> else<br> {<br> if ((AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+4)>1024)<br> {<br> continue;<br> }<br> else<br> {<br> //不完整,则将指令保存<br> if (iLenght>0)<br> {<br> TcpBuff=new byte[iLenght];<br> for (iLen = 1; iLen <=iLenght; iLen++)<br> {<br> TcpBuff[iLen-1]=AllBuff[iLen+iIndex-2];<br> }<br> break;<br> }<br> else<br> {<br> TcpBuff=new byte[1];<br> break;<br> }<br><br> }<br> }<br> }<br> else<br> {<br> continue;<br> }<br> }//检测数据包长度<br> }<br> }<br> }<br><br> public void ShowSysMsg(string sNote,int iIcon)<br> {<br> //显示系统消息<br> try<br> {<br> lvwMsg.BeginUpdate();<br> if (lvwMsg.Items.Count >100)<br> lvwMsg.Items.Clear();<br> ListViewItem li = new ListViewItem();<br> //li.SubItems[0].Text =sNote ;<br> li.SubItems.Add (sNote);<br> li.ImageIndex=iIcon;<br> lvwMsg.Items.Add(li);<br> lvwMsg.EndUpdate();<br> }<br> catch<br> {}<br> }<br><br> private void ReadUdp() //从UDP数据端口读取GPRS数据<br> {<br> byte[] buff = new byte[1024];<br> int recv = 0;<br> byte[] Tbuff;<br> byte[] AllBuff;<br> int iLenght=0;<br> int iIndex=0;<br> int iLen=0;<br> int iXorValue=0;<br> string CarIpAddress="";<br> byte[] RecvAffirmBuff=new byte[]{0x29,0x29,0x21,0x00,0x05,0,0,0,0,0x0D};//回应终端数组<br><br> IPEndPoint ipep = new IPEndPoint(IPAddress.Any ,LocaPort); <br> //socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);<br> socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);<br> try<br> {<br> socket.Bind(ipep);<br> ShowSysMsg("系统成功在"+LocaPort + "端口侦听!",6);<br> }<br> catch<br> {<br> ShowSysMsg("端口"+LocaPort+"已被占用,系统侦听失败!",5);<br> return;<br> }<br> IPEndPoint sender = new IPEndPoint(IPAddress.Any , 0);//指远程终端(终节点)Ip地址对象 IPAddress.Any表示任何地址 0 表示任何端口<br> EndPoint remote = (EndPoint)(sender); //指远程终端(终节点)<br><br> while(true)<br> {<br> try<br> {<br> recv = socket.ReceiveFrom(buff , ref remote);<br> }<br> catch<br> {<br> ShowSysMsg("接收车载终端数据错误!",3);<br> }<br> //---------------------you2004-12-31 begin------------------------------//<br> AllBuff=new byte[recv +TempBuff.Length];<br> for (iIndex = 1; iIndex <=TempBuff.Length; iIndex++)<br> {<br> AllBuff[iIndex-1]=TempBuff[iIndex-1];<br> }<br><br> for (iIndex = 1; iIndex <=recv; iIndex++)<br> {<br> AllBuff[TempBuff.Length+iIndex-1]=buff[iIndex-1];<br> }<br><br> for (iIndex = 1; iIndex <=AllBuff.Length; iIndex++)<br> {<br> iLenght=AllBuff.Length-iIndex+1;<br> if (iLenght<6)//检测数据包长度<br> {<br> //不完整,则将指令保存<br> if (iLenght>0)<br> {<br> TempBuff=new byte[iLenght];<br> for (iLen = 1; iLen <=iLenght; iLen++)<br> {<br> TempBuff[iLen-1]=AllBuff[iLen+iIndex-2];<br> }<br> }<br> break;<br> }<br> else<br> {<br> //检测当前指令是否是完整的指令,查找数据包头<br> if (AllBuff[iIndex-1]==0x29 & AllBuff[iIndex]==0x29)<br> {<br> if ((AllBuff.Length -iIndex)>=(AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+4))<br> {<br> //检测当前指令是否是完整的指令<br> if ((AllBuff[AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+iIndex+3])==0x0D)<br> {<br> //在接收的数据中获取单条完整的指令数据<br> Tbuff=new byte[AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+5];<br> for (iLen = 1; iLen <=Tbuff.Length; iLen++)<br> {<br> Tbuff[iLen-1]=AllBuff[iLen+iIndex-2];<br> }<br> iXorValue=Get_CheckXor(ref Tbuff,Tbuff.Length-2);<br> if(iXorValue!=Tbuff[Tbuff.Length-2])<br> {<br> //校验不合格,继续查找合法指令数据<br> continue;<br> }<br> else<br> {<br> if (bTsFlag)<br> {<br> string BuffToStr="";<br> for(int i=0;i<Tbuff.Length;i++)<br> {<br> BuffToStr+=Tbuff[i].ToString("X2")+" ";<br> }<br> ShowSysMsg(BuffToStr,0);<br> }<br><br> //获取车载终端手机号<br> CarIpAddress=Tbuff[5]+"." +Tbuff[6] +"."+Tbuff[7] +"."+Tbuff[8];<br> <br> //-----------------检测系统哈希表是否包含此终端数据---------------------\\<br> if(CarID_RemoteIP_Hash.ContainsKey(CarIpAddress))<br> {<br> CarID_RemoteIP_Hash[CarIpAddress]=remote;//有更新<br> }<br> else<br> {<br> CarID_RemoteIP_Hash.Add(CarIpAddress,remote);//没有添加<br> }<br><br> //--------------------将数据转发到中心处理程序-----------------\\<br> if (TcpSocket.Connected)<br> {<br> try<br> {<br> TcpSocket.Send(Tbuff,0,Tbuff.Length,SocketFlags.None);<br> if (bTsFlag)<br> {<br> ShowSysMsg("数据成功转发到网络中心处理程序!",1);<br> }<br> }<br> catch<br> {<br> if (bTsFlag)<br> {<br> ShowSysMsg("数据转发到网络中心处理程序失败!",3);<br> }<br> }<br> }<br> //-------------------向终端发出0x21的接收确认-------------------\\<br> RecvAffirmBuff[5]=Tbuff[Tbuff.Length-2];<br> RecvAffirmBuff[6]=Tbuff[2];<br> RecvAffirmBuff[7]=Tbuff[9];<br> RecvAffirmBuff[8]=Get_CheckXor(ref RecvAffirmBuff,8);<br> socket.SendTo(RecvAffirmBuff,remote);<br> iIndex=iIndex+Tbuff.Length-1;<br> TempBuff=new byte[1];<br> }<br> }<br> else<br> {<br> continue;<br> }<br> }<br> else<br> {<br> if ((AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+4)>1024)<br> {<br> continue;<br> }<br> else<br> {<br> //不完整,则将指令保存<br> if (iLenght>0)<br> {<br> TempBuff=new byte[iLenght];<br> for (iLen = 1; iLen <=iLenght; iLen++)<br> {<br> TempBuff[iLen-1]=AllBuff[iLen+iIndex-2];<br> }<br> break;<br> }<br> else<br> {<br> TempBuff=new byte[1];<br> break;<br> }<br><br> }<br> }<br> }<br> else<br> {<br> continue;<br> }<br> }//检测数据包长度<br> <br> }<br> //---------------------you2004-12-31 end------------------------------//<br> }<br><br> }<br><br> private void GprsServer_Load(object sender, System.EventArgs e)<br> {<br> //<br> }<br><br> int I=0;<br> private void TimerIcon_Tick(object sender, System.EventArgs e)<br> {<br> if(thGprs!=null)<br> { <br> if(thGprs.IsAlive)<br> notifyIcon.Icon=notifyIcon.Icon==m_Icon1?m_Icon2:m_Icon1;<br> else<br> notifyIcon.Icon=notifyIcon.Icon==m_Icon1?m_Icon3:m_Icon1;<br> }<br> I++;<br> if(I>5)<br> {<br> I=FindWindow(null,@sCompanyName);<br> if( I!= 0)<br> {<br> SendMessage(I,0x501,1002,"");<br> }<br> I=0;<br> } <br> }<br><br> private void TimerConn_Tick(object sender, System.EventArgs e)<br> {<br> if (!TcpSocket.Connected)<br> {<br> try<br> {<br> lblInfo.Text ="与中心数据处理程序断开,正在进行二次连接...";<br> IPHostEntry IPHost = Dns.Resolve(RemoteIp);<br> string []aliases = IPHost.Aliases; <br> IPAddress []addr = IPHost.AddressList;<br> EndPoint ep = new IPEndPoint(addr[0],RemotePort); <br> TcpSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);<br> TcpSocket.Connect(ep);<br><br> thTcpMsg = new Thread ( new ThreadStart(ReadTcpMsg)) ;<br> //启动线程<br> thTcpMsg.IsBackground =true;<br> thTcpMsg.Start( ) ;<br> lblInfo.Text ="系统运行正常,正在中转GPRS数据...";<br> }<br> catch<br> {<br> return;<br> }<br> }<br> }<br><br> private void checkBox1_CheckedChanged(object sender, System.EventArgs e)<br> {<br> bTsFlag=checkBox1.Checked;<br> }<br><br> private void cmdExit_Click(object sender, System.EventArgs e)<br> {<br> if(MessageBox.Show("确定关闭中继服务器?", "提示",MessageBoxButtons.YesNo,MessageBoxIcon.Information) == DialogResult.Yes)<br> {<br> Application.Exit ();<br> }<br> }<br><br> private void cmdSet_Click(object sender, System.EventArgs e)<br> {<br> frmUdpSet frmudpset=new frmUdpSet();<br> frmudpset.Show();<br> }<br> <br> protected override void OnClosing(CancelEventArgs e)<br> {<br> e.Cancel =true;<br> this.WindowState =FormWindowState.Minimized;<br> }<br> }<br>}<br>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值