实例介绍
【实例简介】串口通讯:化验数据采集[测硫仪]
【实例截图】
【核心代码】
using System;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Text.RegularExpressions;
using DataParse;
//using System.Windows.Forms;
namespace SendData
{
/// <summary>
///
/// </summary>
public partial class uSerPort : Label
{
private SerialPort[] serPorts;
public delegate void GetComData(string sValue);
public GetComData getData;
private bool[] isOpens;
public static string _weightZL = "";
[DescriptionAttribute("通讯端口号")]
/// <summary>
/// 串口号
/// </summary>
public string[] Ports;
[DescriptionAttribute("通讯波特率")]
public int[] iBits;
[DescriptionAttribute("数据长度")]
public int[] iLengths;
[DescriptionAttribute("数据较验:0,1,2")]
//0为None,1为寄校验,2为偶较验
public int[] iParitys;
[DescriptionAttribute("数据停止位:0,1,2")]
public string[] iStops;
[DescriptionAttribute("过滤的字符")]
public string[] filters;
[DescriptionAttribute("是否连续发送")]
public string CanSpace;
[DescriptionAttribute("台称个数")]
public int iNum=1;
[DescriptionAttribute("数据解析方法")]
public string dataParse = "";
[DescriptionAttribute("设备ID")]
public string deviceId = "";
public uSerPort()
{
InitializeComponent();
//this.TextAlign = ContentAlignment.MiddleCenter;
//this.serPort.ReadBufferSize = 1024;
}
/// <summary>
/// 串口打开
/// </summary>
/// <returns></returns>
public bool[] OpenPort()
{
isOpens = new bool[iNum];
try
{
serPorts = new SerialPort[iNum];
for (int i = 0; i < iNum; i )
{
isOpens[i] = false;
serPorts[i] = new SerialPort();
serPorts[i].ReceivedBytesThreshold = 1;
serPorts[i].BaudRate = iBits[i];
serPorts[i].DataBits = iLengths[i];
serPorts[i].DtrEnable = true;
serPorts[i].PortName = Ports[i];
int iStop = 0;
if (iStops[i] == "1.5")
iStop = 15;
else
{
try
{
iStop = Convert.ToInt16(iStops[i]);
}
catch { }
}
switch (iParitys[i])
{
default:
case 0:
serPorts[i].Parity = Parity.None;
break;
case 1:
serPorts[i].Parity = Parity.Odd;
break;
case 2:
serPorts[i].Parity = Parity.Even;
break;
}
switch (iStop)
{
default:
serPorts[i].StopBits = StopBits.One;
break;
case 2:
serPorts[i].StopBits = StopBits.Two;
break;
case 15:
serPorts[i].StopBits = StopBits.OnePointFive;
break;
}
if (serPorts[i].IsOpen)
serPorts[i].Close();
serPorts[i].Open();
isOpens[i] = true;
if (i == 0)
{
serPorts[i].DataReceived = new SerialDataReceivedEventHandler(serPort_DataReceived);
}
else
{
serPorts[i].DataReceived = new SerialDataReceivedEventHandler(serPort_DataReceived2);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return isOpens;
}
/// <summary>
/// 串口关闭
/// </summary>
/// <returns></returns>
public bool ClosePort()
{
bool flag = false;
isOpens = new bool[iNum];
try
{
for (int i=0;i<iNum;i )
{
if (serPorts[i].IsOpen)
{
if(i==0)
serPorts[i].DataReceived -= new SerialDataReceivedEventHandler(serPort_DataReceived);
else
serPorts[i].DataReceived -= new SerialDataReceivedEventHandler(serPort_DataReceived2);
serPorts[i].Close();
//serPort.Dispose();
}
flag = true;
isOpens[i] = false;
}
}
catch (Exception ex)
{
flag = false;
throw new Exception(ex.Message);
}
return flag;
}
/// <summary>
/// 获取端口打开状态
/// </summary>
/// <returns></returns>
public bool[] GetPortState()
{
bool[] isOp = new bool[iNum];
for (int i = 0; i < iNum;i )
{
isOp[i] = serPorts[i].IsOpen;
}
return isOp;
}
private void serPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SerialPort serPort = sender as SerialPort;
getWeight(serPort, filters[0]);
}
private void serPort_DataReceived2(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SerialPort serPort = sender as SerialPort;
getWeight(serPort, filters[1]);
}
private void getWeight(SerialPort serPort, string Filter)
{
string str = TransWeight.getWeight(serPort, Filter);
getData(str);
//this.Dispatcher.Invoke(getData, new string[] { str });
//this.Invoke(getData, new string[] { str });
_weightZL = str;
//SerialPort serPort = sender as SerialPort;
//try
//{
// if (serPort.IsOpen)
// {
// string extStr = "";
// string str = "";
// if (Filter != "0")
// {
// System.Threading.Thread.Sleep(200);
// extStr = serPort.ReadExisting();
// loger.Info(string.Format("ReadExisting:{0}", extStr));
// if (extStr.IndexOf("\r") > 0)//带换行
// {
// str = extStr.Replace("\r", "");
// if (str.IndexOf("Net") >= 0)
// {
// str = str.Substring(str.IndexOf("Net") 3);
// }
// else if (str.IndexOf("Weight") >= 0)
// {
// str = str.Substring(str.IndexOf("Weight") 6);
// }
// else if (str.IndexOf("WT:") >= 0)
// {
// str = str.Substring(str.IndexOf("WT:") 3);
// }
// }
// else//不带换行
// {
// #region 不带回车符的连续发送
// if (extStr.Contains("ENTER."))
// {
// serPort.NewLine = "ENTER."; //空格代表换行
// str = serPort.ReadLine();
// }
// else
// {
// str = extStr;
// }
// #endregion
// }
// }
// else//数据不做任何处理,按键发送
// {
// str = extStr = serPort.ReadLine();
// loger.Info(string.Format("ReadExisting:{0}", str));
// }
// if (str.Length > 0)
// {
// if (Filter.Length > 0 && str.IndexOf(Filter) >= 0 && Filter != "0")
// {
// str = str.Substring(str.IndexOf(Filter) Filter.Length);
// }
// Regex reg = new Regex(@"-?[\d] .?[\d] ");
// str = reg.Match(str).Value;
// loger.Info(string.Format("MatchString:{0}", str));
// //if (this.IsHandleCreated && str.Length > 1) { this.Invoke(getData, new string[] { str }); }
// //try { }
// //catch { getData(str); }
// //getData(str);
// this.Dispatcher.Invoke(getData, new string[] { str });
// _weightZL = toDouble(str);
// }
// }
//}
//catch (Exception ex)
//{
// //MessageBox.Show(ex.Message);
//}
}
/// <summary>
/// 设置串口属性
/// </summary>
/// <param name="strPort">端口号</param>
/// <param name="Bit">波特率</param>
/// <param name="Length">数据位</param>
/// <param name="Parity">较验码</param>
/// <param name="Stop">停止位</param>
public void IniSerPort(string[] strPorts,int[] Bits,int[] Lengths,int[] Paritys,string[] Stops)
{
Ports = strPorts;
iBits = Bits;
iLengths = Lengths;
iParitys = Paritys;
iStops = Stops;
}
private double toDouble(object str)
{
double result = 0.0;
try { result=Convert.ToDouble(str); }
catch { }
return result;
}
/// <summary>
/// 返回计量仪表上的重量数据
/// </summary>
/// <returns></returns>
public static string GetjlybData()
{
return _weightZL;
}
}
}
├── DataParse
│ ├── DataParse.cs
│ ├── DataParse.csproj
│ ├── FileClass.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── TransWeight.cs
│ ├── bin
│ │ ├── Debug
│ │ │ ├── DataParse.dll
│ │ │ ├── DataParse.pdb
│ │ │ ├── Model.dll
│ │ │ ├── Model.pdb
│ │ │ ├── Newtonsoft.Json.dll
│ │ │ ├── Service.dll
│ │ │ ├── Service.pdb
│ │ │ └── log4net.dll
│ │ └── Release
│ └── obj
│ └── Debug
│ ├── DataParse.csproj.AssemblyReference.cache
│ ├── DataParse.csproj.CopyComplete
│ ├── DataParse.csproj.CoreCompileInputs.cache
│ ├── DataParse.csproj.FileListAbsolute.txt
│ ├── DataParse.csprojResolveAssemblyReference.cache
│ ├── DataParse.dll
│ ├── DataParse.pdb
│ ├── DesignTimeResolveAssemblyReferencesInput.cache
│ └── TempPE
├── Lib
│ ├── 2_0
│ │ └── Newtonsoft.Json.dll
│ ├── Newtonsoft.Json.dll
│ └── log4net.dll
├── Model
│ ├── IfSampleCheckConnector.cs
│ ├── Model.csproj
│ ├── Param
│ │ ├── Base.cs
│ │ └── IfSampleCheckConnectorParam.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── bin
│ │ ├── Debug
│ │ │ ├── Model.dll
│ │ │ └── Model.pdb
│ │ └── Release
│ └── obj
│ └── Debug
│ ├── DesignTimeResolveAssemblyReferencesInput.cache
│ ├── Model.csproj.AssemblyReference.cache
│ ├── Model.csproj.CoreCompileInputs.cache
│ ├── Model.csproj.FileListAbsolute.txt
│ ├── Model.dll
│ ├── Model.pdb
│ └── TempPE
├── SendData.sln
├── SendData.suo
├── SendMMS
│ ├── BalanceCommRead
│ │ ├── BalanceCon.cs
│ │ ├── clsRWIniFile.cs
│ │ ├── uSerPort.Designer.cs
│ │ ├── uSerPort.cs
│ │ └── uSerPort.resx
│ ├── CreateDelegateHelper.cs
│ ├── FileClass.cs
│ ├── Program.cs
│ ├── ProjectInstaller.Designer.cs
│ ├── ProjectInstaller.cs
│ ├── ProjectInstaller.resx
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── SendData.csproj
│ ├── SendData.csproj.user
│ ├── SendDataService.Designer.cs
│ ├── SendDataService.cs
│ ├── SendDataService.resx
│ ├── System.Ini
│ ├── app.config
│ ├── bin
│ │ ├── Debug
│ │ │ ├── DataParse.dll
│ │ │ ├── DataParse.pdb
│ │ │ ├── Log
│ │ │ │ ├── 20200929.log
│ │ │ │ ├── 20201007.log
│ │ │ │ └── 20201009.log
│ │ │ ├── Model.dll
│ │ │ ├── Model.pdb
│ │ │ ├── Newtonsoft.Json.dll
│ │ │ ├── SendData.exe
│ │ │ ├── SendData.exe.config
│ │ │ ├── SendData.pdb
│ │ │ ├── SendData.vshost.exe
│ │ │ ├── SendData.vshost.exe.config
│ │ │ ├── SendData.vshost.exe.manifest
│ │ │ ├── SendMMS.vshost.exe.manifest
│ │ │ ├── Service.dll
│ │ │ ├── Service.pdb
│ │ │ ├── System.Ini
│ │ │ ├── System.Net.Http.dll
│ │ │ ├── System1.Ini
│ │ │ ├── System2.Ini
│ │ │ └── log4net.dll
│ │ └── Release
│ └── obj
│ └── x86
│ └── Debug
│ ├── DesignTimeResolveAssemblyReferences.cache
│ ├── DesignTimeResolveAssemblyReferencesInput.cache
│ ├── SendData.SendDataService.resources
│ ├── SendData.csproj.AssemblyReference.cache
│ ├── SendData.csproj.CopyComplete
│ ├── SendData.csproj.CoreCompileInputs.cache
│ ├── SendData.csproj.FileListAbsolute.txt
│ ├── SendData.csproj.GenerateResource.Cache
│ ├── SendData.csprojResolveAssemblyReference.cache
│ ├── SendData.exe
│ ├── SendData.pdb
│ ├── SendData.uSerPort.resources
│ ├── SendMMS.ProjectInstaller.resources
│ ├── SendMMS.csproj.FileListAbsolute.txt
│ ├── SendMMS.csproj.GenerateResource.Cache
│ └── TempPE
├── SendMmsSetup
│ ├── Debug
│ │ ├── Debug.zip
│ │ ├── SendMmsSetup.msi
│ │ ├── WindowsInstaller3_1
│ │ │ └── WindowsInstaller-KB893803-v2-x86.exe
│ │ └── setup.exe
│ ├── Release
│ ├── SendMmsSetup.vdproj
│ └── 化验数据采集发送服务部署说明.docx
├── Service
│ ├── ApiWebClient.cs
│ ├── ApiWebClientInterface.cs
│ ├── FileClass.cs
│ ├── IfSampleCheckConnectorService.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── Service.csproj
│ ├── Service.csproj.user
│ ├── ServiceProvider.cs
│ ├── WebClientPro.cs
│ ├── bin
│ │ ├── Debug
│ │ │ ├── Model.dll
│ │ │ ├── Model.pdb
│ │ │ ├── Newtonsoft.Json.dll
│ │ │ ├── Service.dll
│ │ │ └── Service.pdb
│ │ └── Release
│ └── obj
│ └── Debug
│ ├── DesignTimeResolveAssemblyReferences.cache
│ ├── DesignTimeResolveAssemblyReferencesInput.cache
│ ├── Service.csproj.AssemblyReference.cache
│ ├── Service.csproj.CopyComplete
│ ├── Service.csproj.CoreCompileInputs.cache
│ ├── Service.csproj.FileListAbsolute.txt
│ ├── Service.csprojResolveAssemblyReference.cache
│ ├── Service.dll
│ ├── Service.pdb
│ └── TempPE
├── UpgradeLog.htm
├── WfTest
│ ├── FileClass.cs
│ ├── Form1.Designer.cs
│ ├── Form1.cs
│ ├── Form1.resx
│ ├── Program.cs
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ ├── Resources.Designer.cs
│ │ ├── Resources.resx
│ │ ├── Settings.Designer.cs
│ │ └── Settings.settings
│ ├── WfTest.csproj
│ ├── bin
│ │ └── Debug
│ │ ├── System.Ini
│ │ ├── System.Net.Http.dll
│ │ ├── WfTest.exe
│ │ └── WfTest.pdb
│ └── obj
│ └── x86
│ └── Debug
│ ├── DesignTimeResolveAssemblyReferences.cache
│ ├── DesignTimeResolveAssemblyReferencesInput.cache
│ ├── TempPE
│ ├── WfTest.Form1.resources
│ ├── WfTest.Properties.Resources.resources
│ ├── WfTest.csproj.FileListAbsolute.txt
│ ├── WfTest.csproj.GenerateResource.Cache
│ ├── WfTest.csprojResolveAssemblyReference.cache
│ ├── WfTest.exe
│ └── WfTest.pdb
└── 好例子网_化验数据采集[测硫仪].zip
50 directories, 150 files
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论