using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.IO;
using Haier_Common;
using System.Linq;
namespace Control
{
public static class SerialHelper
{
public static SerialPort _serialPort = new SerialPort();
public static void initialize()//初始化
{
//关闭串口时回抛异常
try
{
string[] ports = SerialPort.GetPortNames();//获取当前计算机的串行端口名的数组。
_serialPort.PortName = Global.PortName;//ports[0].ToString();//串口号//
_serialPort.BaudRate = Convert.ToInt32(115200);//波特率
_serialPort.DataBits = 8;//数据位
_serialPort.StopBits = StopBits.One;//停止位
_serialPort.Parity = Parity.None;//校验位
_serialPort.WriteBufferSize = 2048;
pubfunction.WriteLogWorkDate("小屏幕", Global.PortName);
}
catch (Exception ex)
{
pubfunction.WriteLogWorkDate("串口报错", ex.Message);
}
}
public static void SerialOpen()//串口开
{
try
{
_serialPort.Open();
_serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);//添加数据接收事件
}
catch (Exception ex)
{
pubfunction.WriteLogWorkDate("串口报错", ex.Message);
}
}
public static void SerialClose()//串口关
{
try
{
_serialPort.DataReceived -= DataReceivedHandler;
_serialPort.Close();
}
catch (Exception ex)
{
pubfunction.WriteLogWorkDate("串口报错", ex.Message);
}
}
public static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)//读取下位机的数据
{
try
{
int len = _serialPort.BytesToRead;
byte[] buffer = new byte[len];
_serialPort.Read(buffer, 0, len);
string strData = BitConverter.ToString(buffer, 0, len);
pubfunction.WriteLogWorkDate("小屏幕", "接收:" + strData);
}
catch (Exception ex)
{
pubfunction.WriteLogWorkDate("串口报错", ex.Message);
Global.ShowMessge(ex.Message);
}
}
public static void SerialSend(string SendData)//发送按钮
{
try
{
//string a = SendData.Trim();
SendData = SendData.Replace(" ", "");
byte[] Data = new byte[SendData.Length / 2];
for (int i = 0; i < SendData.Length / 2; i++)
{
//每次取两位字符组成一个16进制
Data[i] = Convert.ToByte(SendData.Substring(i * 2, 2), 16);
}
_serialPort.Write(Data, 0, Data.Length);
}
catch (Exception ex)
{
pubfunction.WriteLogWorkDate("串口报错", ex.Message);
//Global.ShowMessge(ex.Message);
}
}
public static void SerialStopSend()//停止接收数据
{
try
{
byte[] data = { 0x99 };
_serialPort.DataReceived -= DataReceivedHandler;
_serialPort.Write(data, 0, data.Length);
}
catch (Exception ex)
{
pubfunction.WriteLogWorkDate("串口报错", ex.Message);
Global.ShowMessge(ex.Message);
}
}
private static void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
_serialPort.Close();
}
}
}
|