主要是用于条码枪扫描。所以只读就可以了。
public class ZEBEXCommunicate
{
#region com /// <summary>
/// COM初始化
/// </summary>
/// <param name="portName">名称</param>
/// <param name="bautRate">波特率</param>
/// <param name="dataBits">数据位</param>
/// <param name="parity">奇偶校验</param>
/// <param name="stopBits">停止位</param>
/// <param name="readTimeOut">读超时</param>
public bool com_initiate(string portName, int bautRate, int dataBits, int parity, int stopBits, int readTimeOut)
{
bool res = true;
try
{
com = new SerialPort();
if (com.IsOpen)
{
com.Close();
}
com.PortName = portName;
com.BaudRate = bautRate;
com.DataBits = dataBits;
com.StopBits = (StopBits)stopBits;
com.Parity = (Parity)parity;
com.ReadTimeout = readTimeOut;
com.ReceivedBytesThreshold = 1;
com.Handshake = Handshake.None;
com.RtsEnable = true;
com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);//定义接受事件
}
catch
{
res = false;
}
return res;
} #region 属性 private static SerialPort com;
public delegate void delegateComData(string data);//定义委托
public static event delegateComData ManageCom;//接收事件,该事件的注册是在外部的,因为我要将读出的条码显示在主窗体的列表中。
private static string connstr = ConfigurationManager.AppSettings["connstr"].ToString();//数据库连接字符串
#endregion public bool openCom()
{
bool res = true;
try
{
if (com.IsOpen)
{
com.Close();
com.Open();
}
else
{
com.Open();
}
}
catch
{
res = false;
}
return res;
} public bool closeCom()
{
bool res = true;
try
{
com.Open();
}
catch
{
res = false;
}
return res;
} private void com_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string dataStr = com.ReadLine();//读出数据
addComData(dataStr);//添加列表
} public void addComData(string data)
{
if (chargeCode(data))//验证成功,将条码加入列表。
{
//触发事件,然后外部就可以接受了。
ManageCom(data);
}
}
//主要是用于检查条码是否已经在数据库中存在
private bool chargeCode(string code)
{
bool res = true;
SqlConnection conn = new SqlConnection(connstr);
SqlCommand command = new SqlCommand();
string storePro = "chargeTyreCode";
try
{
command.Connection = conn;
command.CommandText = storePro;
command.CommandType = CommandType.StoredProcedure;
SqlParameter parm = new SqlParameter("tyreCode", code);
SqlParameter outParm = new SqlParameter("outParm", SqlDbType.Int);
outParm.Direction = ParameterDirection.Output;
command.Parameters.Add(parm);
command.Parameters.Add(outParm);
conn.Open();
command.ExecuteNonQuery();
conn.Close(); string val = command.Parameters["outParm"].Value.ToString();
if (val == "1")
{
res = false;
}
}
catch (Exception ee)
{
res = false;
}
return res;
}
#endregion }
我觉得思路应该是正确的吧,为什么会读超时呢?网上关于超时的资料好像了了啊,是不是还有什么属性没有设置?30分。
如果您的回答纯属为了好玩,就请不要指点了,如果您为了技术交流,30奉上。
public class ZEBEXCommunicate
{
#region com /// <summary>
/// COM初始化
/// </summary>
/// <param name="portName">名称</param>
/// <param name="bautRate">波特率</param>
/// <param name="dataBits">数据位</param>
/// <param name="parity">奇偶校验</param>
/// <param name="stopBits">停止位</param>
/// <param name="readTimeOut">读超时</param>
public bool com_initiate(string portName, int bautRate, int dataBits, int parity, int stopBits, int readTimeOut)
{
bool res = true;
try
{
com = new SerialPort();
if (com.IsOpen)
{
com.Close();
}
com.PortName = portName;
com.BaudRate = bautRate;
com.DataBits = dataBits;
com.StopBits = (StopBits)stopBits;
com.Parity = (Parity)parity;
com.ReadTimeout = readTimeOut;
com.ReceivedBytesThreshold = 1;
com.Handshake = Handshake.None;
com.RtsEnable = true;
com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);//定义接受事件
}
catch
{
res = false;
}
return res;
} #region 属性 private static SerialPort com;
public delegate void delegateComData(string data);//定义委托
public static event delegateComData ManageCom;//接收事件,该事件的注册是在外部的,因为我要将读出的条码显示在主窗体的列表中。
private static string connstr = ConfigurationManager.AppSettings["connstr"].ToString();//数据库连接字符串
#endregion public bool openCom()
{
bool res = true;
try
{
if (com.IsOpen)
{
com.Close();
com.Open();
}
else
{
com.Open();
}
}
catch
{
res = false;
}
return res;
} public bool closeCom()
{
bool res = true;
try
{
com.Open();
}
catch
{
res = false;
}
return res;
} private void com_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string dataStr = com.ReadLine();//读出数据
addComData(dataStr);//添加列表
} public void addComData(string data)
{
if (chargeCode(data))//验证成功,将条码加入列表。
{
//触发事件,然后外部就可以接受了。
ManageCom(data);
}
}
//主要是用于检查条码是否已经在数据库中存在
private bool chargeCode(string code)
{
bool res = true;
SqlConnection conn = new SqlConnection(connstr);
SqlCommand command = new SqlCommand();
string storePro = "chargeTyreCode";
try
{
command.Connection = conn;
command.CommandText = storePro;
command.CommandType = CommandType.StoredProcedure;
SqlParameter parm = new SqlParameter("tyreCode", code);
SqlParameter outParm = new SqlParameter("outParm", SqlDbType.Int);
outParm.Direction = ParameterDirection.Output;
command.Parameters.Add(parm);
command.Parameters.Add(outParm);
conn.Open();
command.ExecuteNonQuery();
conn.Close(); string val = command.Parameters["outParm"].Value.ToString();
if (val == "1")
{
res = false;
}
}
catch (Exception ee)
{
res = false;
}
return res;
}
#endregion }
我觉得思路应该是正确的吧,为什么会读超时呢?网上关于超时的资料好像了了啊,是不是还有什么属性没有设置?30分。
如果您的回答纯属为了好玩,就请不要指点了,如果您为了技术交流,30奉上。
try
{
zebex_com.com_initiate(common.ZEBXE_COMPORT, 9600, 8, 0, 1, 1000);
data.ZEBEXCommunicate.ManageCom+=new ZEBEXCommunicate.delegateComData(zebex_ManageCom);//注册事件
}
catch(Exception ee)
{
MessageBox.Show("初始化条码枪端口失败!");
} private void zebex_ManageCom(string data)
{
lock (listBox_obj)
{
//添加列表
}
}
bool res = true;
try
{
com = new SerialPort();
if (!IsOpen)
{
com.Open();
IsOpen = true;
}
com.PortName = portName;
com.BaudRate = bautRate;
com.DataBits = dataBits;
com.StopBits = (StopBits)stopBits;
com.Parity = (Parity)parity;
com.ReadTimeout = readTimeOut;
com.ReceivedBytesThreshold = 1;
com.Handshake = Handshake.None;
com.RtsEnable = true;
com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);//定义接受事件
}
catch
{
res = false;
}
return res;
* Copyright(c) : Tangxu
* Description :
* CreateDate : 2006-9-01 04:53:08
* Creater : Tang.xu
* LastChangeDate:
* LastChanger :
* Version Info : 1.0.0
* ******************************************************************/
using System;
using System.IO.Ports;
using System.Threading;
using System.Text; namespace Tangxu.Common
{
public class ReadCom
{
public ReadCom()
{
_ReadConfig = new ReadConfigure(System.Environment.CurrentDirectory + "\\Com_Info.xml");
} public ReadCom(string sCom,int nBaud):this()
{
} private byte[] _ReadBuffer;
private SerialPort ss_port = new SerialPort();
private static int nReadCount = 0;
private ReadConfigure _ReadConfig; #region Initialize com port public bool InitCom()//初始化建串口类实例
{
// return true;
try
{
ss_port.PortName = _ReadConfig.GetNodeValue("PORT");// _sComPort;
ss_port.BaudRate = int.Parse(_ReadConfig.GetNodeValue("BAUD"));//_nBaud;
ss_port.ReadBufferSize = 10240;
ss_port.DataBits = int.Parse(_ReadConfig.GetNodeValue("DATA"));//8;
switch (_ReadConfig.GetNodeValue("PARITY"))
{
case "None":
ss_port.Parity = Parity.None;
break;
case "Even":
ss_port.Parity = Parity.Even;
break;
case "Mark":
ss_port.Parity = Parity.Mark;
break;
case "Odd":
ss_port.Parity = Parity.Odd;
break;
case "Space":
ss_port.Parity = Parity.Mark;
break;
}
switch (_ReadConfig.GetNodeValue("STOP"))
{
case "1":
ss_port.StopBits = StopBits.One;
break;
case "1.5":
ss_port.StopBits = StopBits.OnePointFive;
break;
case "2":
ss_port.StopBits = StopBits.Two;
break;
}
ss_port.ReadTimeout = 600;
ss_port.WriteTimeout = 700; ss_port.Open();//打开串口
return true;
}
catch (Exception ex)
{
throw new Exception("打开串口失败!\r\n错误信息:" + ex.Message);
}
}
#endregion #region FreeDrv
/// <summary>
/// free opw
/// </summary>
public void FreeDrv()
{
try
{
if (ss_port != null)
{
ss_port.Close();
}
}
catch
{ }
}
#endregion #region Write command to OPW
/// <summary>
/// 发操作命令给OPW设备
/// 并返回状态
/// </summary>
/// <param name="sCommand"> </param>
/// <returns> </returns>
public string WriteCommand(string sCommand)
{
StringBuilder sb = new StringBuilder();
bool bRead = true;
try
{
ss_port.DiscardInBuffer();
ss_port.Write(sCommand);
Thread.Sleep(1500);
while (bRead)
{
_ReadBuffer = new byte[ss_port.BytesToRead];
ss_port.Read(_ReadBuffer, 0, _ReadBuffer.Length);
sb.Append(Encoding.ASCII.GetString(_ReadBuffer));
Thread.Sleep(500);
if (ss_port.BytesToRead <= 0)
{
bRead= false;
}
}
if (sb.ToString().Length== 0)
{
nReadCount++;
} if (nReadCount == 3)
{
nReadCount = 0;
throw new Exception("设置不正确或没有联接设备!");
}
}
catch (Exception ex)
{
throw new Exception("从设备获取数据失败!\r\n错误信息:" + ex.Message);
}
return sb.ToString(); ;
} public string WriteCommand(byte[] bCommand)
{
StringBuilder sb = new StringBuilder();
bool bRead = true;
try
{
ss_port.DiscardInBuffer();
ss_port.Write(bCommand,0,bCommand.Length);
Thread.Sleep(1500);
while (bRead)
{
_ReadBuffer = new byte[ss_port.BytesToRead];
ss_port.Read(_ReadBuffer, 0, _ReadBuffer.Length);
sb.Append(Encoding.ASCII.GetString(_ReadBuffer));
Thread.Sleep(500);
if (ss_port.BytesToRead <= 0)
{
bRead = false;
}
}
if (sb.ToString().Length == 0)
{
nReadCount++;
} if (nReadCount == 3)
{
nReadCount = 0;
throw new Exception("设置不正确或没有联接设备!");
}
}
catch (Exception ex)
{
throw new Exception("从设备获取数据失败!\r\n错误信息:" + ex.Message);
}
return sb.ToString();
}
#endregion #region Get All COM Port
public string[] GetAllComPort()
{
string[] sAllPort = null;
try
{
sAllPort = SerialPort.GetPortNames();
}
catch (Exception ex)
{
throw new Exception("获取计算机COM口列表失败!\r\n错误信息:" + ex.Message);
}
return sAllPort;
}
#endregion
} }