最近写了个简单的串口接收GPS数据的程序,下面主程序中的代码,主要利用BackGroundWork组件来实现数据的接收。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.Common;
using System.Collections;
namespace GPSSerialPortData
...{
public partial class MainFrom : Form
...{
private System.IO.Ports.SerialPort[] ports = null;
private bool IsShowData = false;
StringBuilder f_SB = new StringBuilder();
public MainFrom()
...{
InitializeComponent();
}
private string newline()
...{
return " ";
}
/**//// <summary>
/// 打开串口并开始数据接收
/// </summary>
private void OpenPort()
...{
for (int i = 0; i < SerialPortConfig.Ports.Count; i++)
...{
try
...{
ports[i].Open();
ports[i].DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SPort_DataReceived);
tbPortState.Text += "串口" + ports[i].PortName + "已经打开" + newline();
}
catch
...{
tbPortState.Text += "串口" + ports[i].PortName + "不存在或已占用" + newline();
}
}
}
/**//// <summary>
/// 停止数据接收并关闭串口
/// </summary>
private void ClosePort()
...{
for (int i = 0; i < SerialPortConfig.Ports.Count; i++)
...{
try
...{
if (ports[i].IsOpen)
...{
ports[i].DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(SPort_DataReceived);
ports[i].Close();
}
tbPortState.Text += "串口" + ports[i].PortName + "已经关闭" + newline();
}
catch
...{
tbPortState.Text += "串口" + ports[i].PortName + "不存在或已占用" + newline();
}
}
}
private void AddReceiveData(byte[] bytes)
...{
lock (f_SB)
...{
foreach (byte b in bytes)
...{
if (b < 16)
...{
f_SB.Append( "0"+Convert.ToString(b, 16).ToUpper());
}
else
...{
f_SB.Append(Convert.ToString(b, 16).ToUpper());
}
}
}
}
BackgroundWorker f_BG = new BackgroundWorker();
private void bgWorkerAnalyze_DoWork(object sender, DoWorkEventArgs e)
...{
while (true)
...{
if (f_SB.Length < 58)
...{
System.Threading.Thread.Sleep(200);
}
else
...{
lock (f_SB)
...{
while (f_SB.Length>=58)
...{
if (f_SB.ToString().Substring(0,4).ToUpper() == "ACAC")
...{
SaveGPSData(f_SB.ToString().Substring(0, 58));
f_SB.Remove(0, 58);
}
else
...{
f_SB.Remove(0, 4);
}
}
}
}
}
}
void SPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
...{
System.IO.Ports.SerialPort serialPort = (System.IO.Ports.SerialPort)sender;
//此处 在测试时不能够确定出发的次数 故做了长度判断当长度为0时 不予考虑
int len = serialPort.BytesToRead;
byte[] bs = new byte[len];
serialPort.Read(bs, 0, len);
if (len == 0)
...{
return;
}
else
...{
BackgroundWorker bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerAsync(bs);
return;
}
}
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
...{
byte[] bs = (byte[])e.Argument;
AddReceiveData(bs);
}
delegate void ShowGPSDataCallback(string text);
private void ShowGPSData(string message)
...{
if (tbView.InvokeRequired == true)
...{
ShowGPSDataCallback callback = new ShowGPSDataCallback(ShowGPSData);
tbView.Invoke(callback, message);
}
else
...{
tbView.Text += message;
}
}
private void SaveGPSData(string data)
...{
GPSData gpsData = new GPSData();
设置数据设置数据
switch (data.Substring(18, 2))
...{
case "89":
if (IsShowData)
...{
ShowGPSData(
"终端" + gpsData.Terminal_Id +
" 北纬" + gpsData.Latitude +
" 东经" + gpsData.Longitude+
" 海拔" + gpsData.Height.ToString() +
" 时间" + gpsData.AddTime.ToString("hh:mm:ss" + newline())
);
}
break;
case "4B":
ShowGPSData(gpsData.Terminal_Id + "时间设置成功" + newline());
return;
case "50":
ShowGPSData(gpsData.Terminal_Id + "已停止回送数据" + newline());
return;
default:
return;
}
SaveData(gpsData);
}
/**//// <summary>
/// 保存接收到的GPS数据
/// </summary>
/// <param name="bs"></param>
private void SaveGPSData(byte[] bs)
...{
GPSData gpsData = new GPSData();
设置数据设置数据
switch (Convert.ToString(bs[9], 16).ToUpper())
...{
case "89":
if (IsShowData)
...{
ShowGPSData(
"终端" + Convert.ToInt32(Convert.ToString(bs[5], 16) + Convert.ToString(bs[6], 16) + Convert.ToString(bs[7], 16) + Convert.ToString(bs[8], 16)).ToString() +
" 北纬" + gpsData.Latitude +
" 东经" + gpsData.Longitude +
" 海拔" + gpsData.Height.ToString() +
" 时间" + gpsData.AddTime.ToString("hh:mm:ss" + newline())
);
}
break;
case "4B":
ShowGPSData(Convert.ToInt32(
Convert.ToString(bs[5], 16) + Convert.ToString(bs[6], 16) +
Convert.ToString(bs[7], 16) + Convert.ToString(bs[8], 16)).ToString() + "时间设置成功" + newline());
return;
case "50":
ShowGPSData(Convert.ToInt32(
Convert.ToString(bs[5], 16) + Convert.ToString(bs[6], 16) +
Convert.ToString(bs[7], 16) + Convert.ToString(bs[8], 16)).ToString() + "已停止回送数据" + newline());
return;
default:
return;
}
SaveData(gpsData);
}
private void SaveData(GPSData data)
...{
Database db = DatabaseFactory.CreateDatabase();
StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO [soft_sailingservice].[dbo].[NS_GPS_Data]");
sb.Append("([TerminalNumber],[Latitude],[OriginalLatitude],[Longitude],[OriginalLongitude],[Height],[AddTime])");
sb.Append("VALUES (");
sb.Append(data.Terminal_Id + ",'");
sb.Append(data.Latitude + "',");
sb.Append(data.OriginalLatitude + ",'");
sb.Append(data.Longitude + "',");
sb.Append(data.OriginalLongitude + ",");
sb.Append(data.Height + ",'");
sb.Append(data.AddTime + "')");
db.ExecuteNonQuery(CommandType.Text, sb.ToString());
}
按钮事件处理按钮事件处理
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.Common;
using System.Collections;
namespace GPSSerialPortData
...{
public partial class MainFrom : Form
...{
private System.IO.Ports.SerialPort[] ports = null;
private bool IsShowData = false;
StringBuilder f_SB = new StringBuilder();
public MainFrom()
...{
InitializeComponent();
}
private string newline()
...{
return " ";
}
/**//// <summary>
/// 打开串口并开始数据接收
/// </summary>
private void OpenPort()
...{
for (int i = 0; i < SerialPortConfig.Ports.Count; i++)
...{
try
...{
ports[i].Open();
ports[i].DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SPort_DataReceived);
tbPortState.Text += "串口" + ports[i].PortName + "已经打开" + newline();
}
catch
...{
tbPortState.Text += "串口" + ports[i].PortName + "不存在或已占用" + newline();
}
}
}
/**//// <summary>
/// 停止数据接收并关闭串口
/// </summary>
private void ClosePort()
...{
for (int i = 0; i < SerialPortConfig.Ports.Count; i++)
...{
try
...{
if (ports[i].IsOpen)
...{
ports[i].DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(SPort_DataReceived);
ports[i].Close();
}
tbPortState.Text += "串口" + ports[i].PortName + "已经关闭" + newline();
}
catch
...{
tbPortState.Text += "串口" + ports[i].PortName + "不存在或已占用" + newline();
}
}
}
private void AddReceiveData(byte[] bytes)
...{
lock (f_SB)
...{
foreach (byte b in bytes)
...{
if (b < 16)
...{
f_SB.Append( "0"+Convert.ToString(b, 16).ToUpper());
}
else
...{
f_SB.Append(Convert.ToString(b, 16).ToUpper());
}
}
}
}
BackgroundWorker f_BG = new BackgroundWorker();
private void bgWorkerAnalyze_DoWork(object sender, DoWorkEventArgs e)
...{
while (true)
...{
if (f_SB.Length < 58)
...{
System.Threading.Thread.Sleep(200);
}
else
...{
lock (f_SB)
...{
while (f_SB.Length>=58)
...{
if (f_SB.ToString().Substring(0,4).ToUpper() == "ACAC")
...{
SaveGPSData(f_SB.ToString().Substring(0, 58));
f_SB.Remove(0, 58);
}
else
...{
f_SB.Remove(0, 4);
}
}
}
}
}
}
void SPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
...{
System.IO.Ports.SerialPort serialPort = (System.IO.Ports.SerialPort)sender;
//此处 在测试时不能够确定出发的次数 故做了长度判断当长度为0时 不予考虑
int len = serialPort.BytesToRead;
byte[] bs = new byte[len];
serialPort.Read(bs, 0, len);
if (len == 0)
...{
return;
}
else
...{
BackgroundWorker bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerAsync(bs);
return;
}
}
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
...{
byte[] bs = (byte[])e.Argument;
AddReceiveData(bs);
}
delegate void ShowGPSDataCallback(string text);
private void ShowGPSData(string message)
...{
if (tbView.InvokeRequired == true)
...{
ShowGPSDataCallback callback = new ShowGPSDataCallback(ShowGPSData);
tbView.Invoke(callback, message);
}
else
...{
tbView.Text += message;
}
}
private void SaveGPSData(string data)
...{
GPSData gpsData = new GPSData();
设置数据设置数据
switch (data.Substring(18, 2))
...{
case "89":
if (IsShowData)
...{
ShowGPSData(
"终端" + gpsData.Terminal_Id +
" 北纬" + gpsData.Latitude +
" 东经" + gpsData.Longitude+
" 海拔" + gpsData.Height.ToString() +
" 时间" + gpsData.AddTime.ToString("hh:mm:ss" + newline())
);
}
break;
case "4B":
ShowGPSData(gpsData.Terminal_Id + "时间设置成功" + newline());
return;
case "50":
ShowGPSData(gpsData.Terminal_Id + "已停止回送数据" + newline());
return;
default:
return;
}
SaveData(gpsData);
}
/**//// <summary>
/// 保存接收到的GPS数据
/// </summary>
/// <param name="bs"></param>
private void SaveGPSData(byte[] bs)
...{
GPSData gpsData = new GPSData();
设置数据设置数据
switch (Convert.ToString(bs[9], 16).ToUpper())
...{
case "89":
if (IsShowData)
...{
ShowGPSData(
"终端" + Convert.ToInt32(Convert.ToString(bs[5], 16) + Convert.ToString(bs[6], 16) + Convert.ToString(bs[7], 16) + Convert.ToString(bs[8], 16)).ToString() +
" 北纬" + gpsData.Latitude +
" 东经" + gpsData.Longitude +
" 海拔" + gpsData.Height.ToString() +
" 时间" + gpsData.AddTime.ToString("hh:mm:ss" + newline())
);
}
break;
case "4B":
ShowGPSData(Convert.ToInt32(
Convert.ToString(bs[5], 16) + Convert.ToString(bs[6], 16) +
Convert.ToString(bs[7], 16) + Convert.ToString(bs[8], 16)).ToString() + "时间设置成功" + newline());
return;
case "50":
ShowGPSData(Convert.ToInt32(
Convert.ToString(bs[5], 16) + Convert.ToString(bs[6], 16) +
Convert.ToString(bs[7], 16) + Convert.ToString(bs[8], 16)).ToString() + "已停止回送数据" + newline());
return;
default:
return;
}
SaveData(gpsData);
}
private void SaveData(GPSData data)
...{
Database db = DatabaseFactory.CreateDatabase();
StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO [soft_sailingservice].[dbo].[NS_GPS_Data]");
sb.Append("([TerminalNumber],[Latitude],[OriginalLatitude],[Longitude],[OriginalLongitude],[Height],[AddTime])");
sb.Append("VALUES (");
sb.Append(data.Terminal_Id + ",'");
sb.Append(data.Latitude + "',");
sb.Append(data.OriginalLatitude + ",'");
sb.Append(data.Longitude + "',");
sb.Append(data.OriginalLongitude + ",");
sb.Append(data.Height + ",'");
sb.Append(data.AddTime + "')");
db.ExecuteNonQuery(CommandType.Text, sb.ToString());
}
按钮事件处理按钮事件处理
}
}