using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CcrewMachine
{ ///
/// 基恩士扫码枪串口通讯类
///
internal class KeyenceScan
{ // 串口状态标识
public bool IsOpened; // 记录串口是否打开
public SerialPort SerialPort; // 串口对象
public int SerialPortSendCount; // 串口发送次数
public string BufferString; // 接收到的字符串
public string OpenScanCommand = "LON\r\n"; // 开启扫描命令
public string CloseScanCommand = "LOFF\r\n"; // 关闭扫描命令
///
/// 构造函数
///
/// 串口数据接收事件处理器
public KeyenceScan(SerialDataReceivedEventHandler dataReceivedHandler)
{ SerialPort = new SerialPort();
SerialPort.DataReceived += dataReceivedHandler;
IsOpened = false;
SerialPortSendCount = 0;
BufferString = "";
}
///
/// 初始化串口
///
/// 串口号
/// 波特率
/// 校验位
/// 数据位
/// 停止位
/// 初始化成功返回true,失败返回false
public bool Initialize(string comPort, int baudRate, Parity parity, int dataBits, StopBits stopBit)
{ try
{ IsOpened = false;
SerialPortSendCount = 0;
SerialPort.PortName = comPort;
SerialPort.BaudRate = baudRate;
SerialPort.Parity = parity;
SerialPort.DataBits = dataBits;
SerialPort.StopBits = stopBit;
SerialPort.ReceivedBytesThreshold = 1;
SerialPort.ReadTimeout = 1000;
SerialPort.Open();
BufferString = "";
IsOpened = true;
}
catch (Exception)
{ return false;
}
return true;
}
///
/// 检查接收数据是否有效
///
/// 有效返回true,无效返回false
public bool CheckData()
{ bool result = false;
do
{ if (BufferString[0] == 0x15)
{ // 写入错误
break;
}
result = true;
} while (false);
return result;
}
///
/// 发送开启扫描命令
///
/// 发送成功返回true,失败返回false
public bool OpenScan()
{ try
{ SerialPort.Write(OpenScanCommand);
}
catch (Exception)
{ return false;
}
return true;
}
///
/// 发送关闭扫描命令
///
/// 发送成功返回true,失败返回false
public bool CloseScan()
{ try
{ SerialPort.Write(CloseScanCommand);
}
catch (Exception)
{ return false;
}
return true;
}
///
/// 读取串口接收的所有数据
///
/// 0表示接收完成,-1表示未完成或失败
public int ReadExisting()
{ int returnValue = -1;
do
{ if (SerialPort.IsOpen)
{ BufferString += SerialPort.ReadExisting();
// 判断回车结束
if (BufferString.Length > 1)
{ // 转换字节判断末尾是否为回车
byte[] byteBuffer = System.Text.Encoding.Default.GetBytes(BufferString);
if (byteBuffer[byteBuffer.Length - 1] == 0x0D)
{ // 接收结束,移除末尾回车
BufferString = BufferString.Remove(BufferString.Length - 1);
returnValue = 0;
}
else
{ break;
}
}
else
{ break;
}
}
else
{ BufferString = "";
break;
}
} while (false);
return returnValue;
}
///
/// 关闭串口
///
public void Close()
{ if (SerialPort.IsOpen)
{ try
{ IsOpened = false;
SerialPort.Close();
}
catch (Exception)
{ // 忽略关闭异常
}
}
}
}
}