File name
Commit message
Commit date
File name
Commit message
Commit date
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
namespace KHSCALE_TP
{
public class SerialPort
{
public bool m_IsConn = false;
public string m_strPortMsg = "";
public int m_recvCount = 0;
private System.IO.Ports.SerialPort port = null;
private List<byte> m_buffer = new List<byte>();
public void AddBuffer(byte[] data)
{
lock (this)
{
m_buffer.AddRange(data);
}
}
public List<byte> GetBuffer(bool bClear)
{
List<byte> buffer = new List<byte>();
lock (this)
{
buffer.AddRange(m_buffer);
if (bClear) m_buffer.Clear();
}
return buffer;
}
public void ClearBuffer()
{
lock (this)
{
m_buffer.Clear();
}
}
public int GetBufferSize()
{
lock (this)
{
return m_buffer.Count;
}
}
public void Close()
{
try
{
if (port != null) port.Close();
}
catch
{
}
port = null;
m_IsConn = false;
}
public void Init(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
{
try
{
port = new System.IO.Ports.SerialPort(portName, baudRate, parity, dataBits, stopBits);
//port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.ReadBufferSize = 1024 * 1024;
port.Open();
m_IsConn = true;
m_strPortMsg = portName + " 포트를 정상적으로 오픈하였습니다.";
}
catch (Exception ex)
{
m_strPortMsg = portName + " " + ex.Message;
m_IsConn = false;
}
}
public void Read()
{
m_strPortMsg = "";
try
{
port.ReadTimeout = 1;
while (port.BytesToRead > 0)
{
int bytesToRead = port.BytesToRead;
if (bytesToRead > 0)
{
byte[] bytesBuffer = new byte[bytesToRead];
int readBytes = port.Read(bytesBuffer, 0, bytesToRead);
if (readBytes > 0)
{
m_recvCount++;
byte[] bytesBuffer2 = new byte[readBytes];
Array.Copy(bytesBuffer, bytesBuffer2, readBytes);
AddBuffer(bytesBuffer2);
}
}
if (GetBufferSize() >= 256)
{
port.DiscardInBuffer();
return;
}
System.Threading.Thread.Sleep(1);
}
}
catch (Exception ex)
{
m_strPortMsg = ex.Message;
Close();
}
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//Console.WriteLine(port.ReadExisting());
}
}
}