Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using SerialPort::BaseStream for reading from serial port ... #8

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
Binary file added .vs/SerialPortLib/v15/Server/sqlite3/storage.ide
Binary file not shown.
67 changes: 38 additions & 29 deletions SerialPortLib/SerialPort.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ You should have received a copy of the GNU General Public License
using System.Threading;

using NLog;
using System.IO;

namespace SerialPortLib
{
Expand Down Expand Up @@ -56,6 +57,9 @@ public class SerialPortInput
private object accessLock = new object();
private bool disconnectRequested = false;

byte[] buffer = new byte[2048];
Action kickoffRead = null;

#endregion

#region Public Events
Expand Down Expand Up @@ -85,6 +89,38 @@ public class SerialPortInput
/// <summary>
/// Connect to the serial port.
/// </summary>
public SerialPortInput()
{
kickoffRead = delegate
{
if (!IsConnected)
{
return;
}

_serialPort.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate (IAsyncResult ar)
{
if (IsConnected)
{
try
{
int actualLength = _serialPort.BaseStream.EndRead(ar);
byte[] received = new byte[actualLength];
Buffer.BlockCopy(buffer, 0, received, 0, actualLength);
OnMessageReceived(new MessageReceivedEventArgs(received));
}
catch (IOException exc)
{
logger.Error(exc);
gotReadWriteError = true;
Thread.Sleep(1000);
}
kickoffRead();
}
}, null);
};
}

public bool Connect()
{
if (disconnectRequested)
Expand Down Expand Up @@ -262,36 +298,9 @@ private void HandleErrorReceived(object sender, SerialErrorReceivedEventArgs e)

private void ReaderTask()
{
while (IsConnected)
if (IsConnected)
{
int msglen = 0;
//
try
{
msglen = _serialPort.BytesToRead;
if (msglen > 0)
{
byte[] message = new byte[msglen];
//
int readbytes = 0;
while (_serialPort.Read(message, readbytes, msglen - readbytes) <= 0)
; // noop
if (MessageReceived != null)
{
OnMessageReceived(new MessageReceivedEventArgs(message));
}
}
else
{
Thread.Sleep(100);
}
}
catch (Exception e)
{
logger.Error(e);
gotReadWriteError = true;
Thread.Sleep(1000);
}
kickoffRead();
}
}

Expand Down