Coder Social home page Coder Social logo

genielabs / serialport-lib-dotnet Goto Github PK

View Code? Open in Web Editor NEW
146.0 19.0 62.0 111 KB

Serial Port libray for .Net / Mono

Home Page: https://www.nuget.org/packages/SerialPortLib/

License: Apache License 2.0

C# 97.14% PowerShell 2.86%
serialport dotnet

serialport-lib-dotnet's Introduction

Build status NuGet License

Serial Port library for .Net

Features

  • Easy to use
  • Event driven
  • Hot plug
  • Automatically restabilish connection on error/disconnect
  • Compatible with Mono
  • It overcomes the lack of DataReceived event in Mono

NuGet Package

SerialPortLib is available as a NuGet package.

Run Install-Package SerialPortLib in the Package Manager Console or search for “SerialPortLib” in your IDE’s package management plug-in.

Example usage

using SerialPortLib;
...
var serialPort = new SerialPortInput();

// Listen to Serial Port events

serialPort.ConnectionStatusChanged += delegate(object sender, ConnectionStatusChangedEventArgs args) 
{
    Console.WriteLine("Connected = {0}", args.Connected);
};

serialPort.MessageReceived += delegate(object sender, MessageReceivedEventArgs args)
{
    Console.WriteLine("Received message: {0}", BitConverter.ToString(args.Data));
};

// Set port options
serialPort.SetPort("/dev/ttyUSB0", 115200);

// Connect the serial port
serialPort.Connect();

// Send a message
var message = System.Text.Encoding.UTF8.GetBytes("Hello World!");
serialPort.SendMessage(message);

License

SerialPortLib is open source software, licensed under the terms of Apache License 2.0. See the LICENSE file for details.

Who's using this library?

serialport-lib-dotnet's People

Contributors

bounz avatar clancey avatar davidwallis3101 avatar genemars avatar hiprox avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

serialport-lib-dotnet's Issues

Setting Data bit?

Hi,
Maybe I've not seen it, but is it possible to set data bit length? I'd like to assume its the default 8, but I would also like to know whether it is possible to change it - if need be.

dot net 3.5 compatible ?

Hi,
I can install this nuget package in dot net 3.5.

But it complains about the namespace not found, can this package made to work in 3.5 also?

.NET Core support

First of all: thanks for sharing this library and also your zwave-lib-dotnet.

I came across it while searching for a library that would allow me to talk to a z-wave stick from a Rasperry Pi running Linux. As far as I can see, the main problem with using your zwave-lib-dotnet is that it depends on your serialport-lib-dotnet which depends on Microsoft Serial.IO.Ports.
Unfortunately MS currently does not seem to have much interest in a Linux implementation of Serial.IO.Ports for .NET Core although independent contributors already implemented support for Windows on ARM devices.

On the other side there is a quite active project here https://github.com/jcurl/SerialPortStream which now seems to be .NET Core compatible and would open a door to serial ports in the Linux world.
I am not sure whether you are interested in continuing your projects in that direction?
I doubt that I have enough skills and time to do it myself but I am sure I could help with testing.

Setting a new baudrate with SetPort(...) doesn't work

Hi All,

I tried to set a new baudrate with SetPort() methode, but it doesn't work.
Indeed, SetPort() test if a change occured for portName only, but not the other parameters.
I suggest the following changes

public void SetPort(string portName, int baudRate = 115200, StopBits stopBits = StopBits.One, Parity parity = Parity.None, DataBits dataBits = DataBits.Eight)
{
	if (_portName != portName || _baudRate != baudRate || stopBits != _stopBits || parity != _parity || dataBits != _dataBits)
	{
		// set to error so that the connection watcher will reconnect
		// using the new port
		gotReadWriteError = true;
		logger.Trace("Port parameter changed (port name / baudrate / stopbits / parity / databits) = " + portName + " / " + baudRate + " / " + stopBits + " / " + parity + " / " + dataBits);
	}
	_portName = portName;
	_baudRate = baudRate;
	_stopBits = stopBits;
	_parity = parity;
	_dataBits = dataBits;
}

How to support synchronous communication?

thank you for your work!
this lib is very good support for asynchronous communication.
much easier to use than System.IO.Ports.dll.

in most case, i wanna use it for synchronous communication, like real-time write/read, or request/response or ping/pang.
many people may need this feature.
thank you so much!

the same question: #23

Exception on disconnect

When I disconnect I have this following Exception :
Unhandled Exception:
System.AggregateException: ---> System.Threading.Tasks.TaskCanceledException: The Task was canceled
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.Wait (Int32 millisecondsTimeout, CancellationToken cancellationToken) [0x00000] in :0
at System.Threading.Tasks.Task.Wait (Int32 millisecondsTimeout) [0x00000] in :0
at SerialPortLib.SerialPortInput.Disconnect () [0x00000] in :0
at ConsoleApplication1.COMPort.Dispose () [0x00000] in :0
at ConsoleApplication1.Program.Main (System.String[] args) [0x00000] in :0
--> (Inner exception 0) System.Threading.Tasks.TaskCanceledException: The Task was canceled

[ERROR] FATAL UNHANDLED EXCEPTION: System.AggregateException: ---> System.Threading.Tasks.TaskCanceledException: The Task was canceled
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.Wait (Int32 millisecondsTimeout, CancellationToken cancellationToken) [0x00000] in :0
at System.Threading.Tasks.Task.Wait (Int32 millisecondsTimeout) [0x00000] in :0
at SerialPortLib.SerialPortInput.Disconnect () [0x00000] in :0
at ConsoleApplication1.COMPort.Dispose () [0x00000] in :0
at ConsoleApplication1.Program.Main (System.String[] args) [0x00000] in :0
--> (Inner exception 0) System.Threading.Tasks.TaskCanceledException: The Task was canceled

Unable to use on VS 2010 as it appears to be targetting NET 4.5

I tried to use this on VS 2010 and received the following error

Warning 1 The primary reference "SerialPortLib, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL" could not be resolved because it was built against the ".NETFramework,Version=v4.5" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client". NSP

VS 2010 will only go as high as NET 4.0.

Would you mind making it compatible with 4.0 o that it can be used on VS2010?

Great work by the way, this will be a big help for those using serial ports on Linux using Mono!

Greg

max. baud rate available ?

Is there any MAX. baud rate speed limitation?
I can set the baudrate to 921600 then connect correctly, (Ubuntu 16.04 Mono)
but once I set the baudrate to 1843200 or 2000000 got connect() errors like:

System.IO.IOException: Inappropriate ioctl for device
at SerialPortLib2.Port.SerialPortStream.ThrowIOException () [0x00013] in <76c0701fbbf54b82a7cf07603294b4f7>:0 System.IO.IOException: Inappropriate ioctl for device
at SerialPortLib2.Port.SerialPortStream.ThrowIOException () [0x00013] in <76c0701fbbf54b82a7cf07603294b4f7>:0
at SerialPortLib2.Port.SerialPortStream..ctor (System.String portName, System.Int32 baudRate, System.Int32 dataBits, SerialPortLib2.Port.Parity parity, SerialPortLib2.Port.StopBits stopBits, System.Boolean dtrEnable, System.Boolean rtsEnable, SerialPortLib2.Port.Handshake handshake, System.Int32 readTimeout, System.Int32 writeTimeout, System.Int32 readBufferSize, System.Int32 writeBufferSize, System.Boolean IsAVirtualPort) [0x00041] in <76c0701fbbf54b82a7cf07603294b4f7>:0
at (wrapper remoting-invoke-with-check) SerialPortLib2.Port.SerialPortStream..ctor(string,int,int,SerialPortLib2.Port.Parity,SerialPortLib2.Port.StopBits,bool,bool,SerialPortLib2.Port.Handshake,int,int,int,int,bool)
at SerialPortLib2.Port.SerialPort.Open () [0x00074] in <76c0701fbbf54b82a7cf07603294b4f7>:0
at (wrapper remoting-invoke-with-check) SerialPortLib2.Port.SerialPort.Open()
at SerialPortLib2.SerialPortInput.Open () [0x0010c] in <76c0701fbbf54b82a7cf07603294b4f7>:0
at SerialPortLib2.Port.SerialPortStream..ctor (System.String portName, System.Int32 baudRate, System.Int32 dataBits, SerialPortLib2.Port.Parity parity, SerialPortLib2.Port.StopBits stopBits, System.Boolean dtrEnable, System.Boolean rtsEnable, SerialPortLib2.Port.Handshake handshake, System.Int32 readTimeout, System.Int32 writeTimeout, System.Int32 readBufferSize, System.Int32 writeBufferSize, System.Boolean IsAVirtualPort) [0x00041] in <76c0701fbbf54b82a7cf07603294b4f7>:0
at (wrapper remoting-invoke-with-check) SerialPortLib2.Port.SerialPortStream..ctor(string,int,int,SerialPortLib2.Port.Parity,SerialPortLib2.Port.StopBits,bool,bool,SerialPortLib2.Port.Handshake,int,int,int,int,bool)
at SerialPortLib2.Port.SerialPort.Open () [0x00074] in <76c0701fbbf54b82a7cf07603294b4f7>:0
at (wrapper remoting-invoke-with-check) SerialPortLib2.Port.SerialPort.Open()
at SerialPortLib2.SerialPortInput.Open () [0x0010c] in <76c0701fbbf54b82a7cf07603294b4f7>:0

ConnectionStatusChanged not fired on disconneciton

While talking with a device, I pull off the cable.
The port is removed by system.
The IsConnected becomes false but the the ConnectionStatusChanged is not fired.

On closure this gets logged. (Porta chiusa = Closed port)

<ERRO> 2022-01-18 15:31:37.5691 (6792:021) [SerialPortLib.SerialPortInput.LogError] System.InvalidOperationException: Porta chiusa.
   in System.IO.Ports.SerialPort.get_BytesToRead()
   in SerialPortLib.SerialPortInput.ReaderTask(Object data) in C:\projects\serialport-lib-dotnet\SerialPortLib\SerialPort.cs:riga 354 System.InvalidOperationException: Porta chiusa.
   in System.IO.Ports.SerialPort.get_BytesToRead()
   in SerialPortLib.SerialPortInput.ReaderTask(Object data) in C:\projects\serialport-lib-dotnet\SerialPortLib\SerialPort.cs:riga 354

About each second then I get this into log. (La porta 'COM7' non esiste = The port 'COM7' does not exist)

<ERRO> 2022-01-18 15:31:39.5880 (6792:022) [SerialPortLib.SerialPortInput.LogError] System.IO.IOException: La porta 'COM7' non esiste.
   in System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
   in System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
   in System.IO.Ports.SerialPort.Open()
   in SerialPortLib.SerialPortInput.Open() in C:\projects\serialport-lib-dotnet\SerialPortLib\SerialPort.cs:riga 288 System.IO.IOException: La porta 'COM7' non esiste.
   in System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
   in System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
   in System.IO.Ports.SerialPort.Open()
   in SerialPortLib.SerialPortInput.Open() in C:\projects\serialport-lib-dotnet\SerialPortLib\SerialPort.cs:riga 288

If I put the cable back, as soon as the port is ready again the ConnectionStatusChanged gets fired for a new connection.

I'm currently using reflection to check when IsConnected == false if "connectionWatcher" field is not null and force a Disconnect().
This simple hack seems to fix the issue, but the fact I'm searching for a private field after it's name is so ugly I decided to open this issue.

Thank you for your attention.

Arduino Mega 2560 Response Problem

Sorry for my English.

i'm using SerialPortLib for communicating with Arduino Mega 2560.
My code written like in Example usage manual section.
Sending data to serial is correct, but the event MessageReceived does not raise.

is any suggestions about my problem?
Thank you.

var serialPort = new SerialPortInput();
serialPort.ConnectionStatusChanged += SerialPort_ConnectionStatusChanged;
serialPort.MessageReceived += SerialPort_MessageReceived;
serialPort.SetPort("COM3", 250000);
serialPort.Connect();

foreach (var workContext in WorkContexts.Where(c=>c != null)) {
    var cmd = workContext.CommandFrame;
    var message = Encoding.UTF8.GetBytes(cmd);
    serialPort.SendMessage(message);
    Console.WriteLine($">> {cmd}"); 
}

...

readline feature

Hi , thanks for easy using lib, now i'm using erialportlib2, dose it support readline ? and with deafult setting on which condition it notify the data ?

got lots of ConnectionStatusChanged events

after open the port and waiting communication data arrival,
the ConnectionStatusChanged events arriving every 2 to 3 minutes
(args.Connected changed to false, then true)
but I didn't put any close() in my code, what's the possible cause of this problem?

(build and run on Ubuntu 14.04 Server, using /dev/ttyS1 )

Disconnects and reconnects when receiving 1 line in less than 100ms

I have the same issue as #9 and i have traced it back to the transmit speed of the serial device i am connecting to.
In my case that serial device is a teensy (arduino-like device) that transmits sensor data in a 100ms interval.
For my use case 100ms interval is too slow but is working reliably, when i set to a faster interval like 95ms or slower then i have a disconnect and reconnect after every message, and multiple lines are displayed in one message instead of each their separate message event.
Serial driver is microsoft's USBSER.SYS on Windows 10 Pro x64, i am using Unity 2019 and .net 4.7.1.

Closing Port COM while receiving data often creates a Deadlock in application

Hi,

I found an issue when closing Port COM while sending data. It creates a Deadlock in the application.
This is the stack trace below :

[En attente du verrou détenu par le thread 4156]	
WindowsBase.dll!System.Windows.Threading.DispatcherSynchronizationContext.Wait(System.IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)	
[Transition Natif à Managé]	
[Transition Managé à Natif]	
System.dll!System.IO.Ports.SerialStream.Dispose(bool disposing)
mscorlib.dll!System.IO.Stream.Close()
System.dll!System.IO.Ports.SerialPort.Dispose(bool disposing)
System.dll!System.IO.Ports.SerialPort.Close()

The execution pointer is blocked in method

private void Close()

when executing

_serialPort.Close();

I think that this deadlock occurs in native Framework SerialPort.
I've no idea how to solve this, beside waiting the end of transmission...

See this thread : https://social.msdn.microsoft.com/Forums/en-US/ce8ce1a3-64ed-4f26-b9ad-e2ff1d3be0a5/serial-port-hangs-whilst-closing?forum=Vsexpressvcs

Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.