https://github.com/chrispulman/serialportrx
A Reactive Serial Port Library
https://github.com/chrispulman/serialportrx
dotnet observable reactive serialport
Last synced: 7 months ago
JSON representation
A Reactive Serial Port Library
- Host: GitHub
- URL: https://github.com/chrispulman/serialportrx
- Owner: ChrisPulman
- License: mit
- Created: 2016-09-25T13:37:19.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2024-05-14T23:31:10.000Z (over 1 year ago)
- Last Synced: 2024-05-15T18:30:47.300Z (over 1 year ago)
- Topics: dotnet, observable, reactive, serialport
- Language: C#
- Homepage:
- Size: 3.14 MB
- Stars: 21
- Watchers: 3
- Forks: 5
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# SerialPortRx
A Reactive Serial Port Library
This serial port is configured to provide a stream of data Read and accept a stream of Write requests[](https://github.com/ChrisPulman/SerialPortRx/actions/workflows/dotnet.yml)  
## An Example of the usage of SerialPortRx
```csharp
using System;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using ReactiveMarbles.Extensions;namespace CP.IO.Ports.Test;
internal static class Program
{
private static void Main(string[] args)
{
const string comPortName = "COM1";// configure the data to write, this can be a string, a byte array, or a char array
const string dataToWrite = "DataToWrite";
var dis = new CompositeDisposable();// Setup the start of message and end of message
var startChar = 0x21.AsObservable();
var endChar = 0x0a.AsObservable();// Create a disposable for each COM port to allow automatic disposal upon loss of COM port
var comdis = new CompositeDisposable();// Subscribe to com ports available
SerialPortRx.PortNames().Do(x =>
{
if (comdis?.Count == 0 && x.Contains(comPortName))
{
// Create a port
var port = new SerialPortRx(comPortName, 9600);
port.DisposeWith(comdis);// Subscribe to Exceptions from port
port.ErrorReceived.Subscribe(Console.WriteLine).DisposeWith(comdis);
port.IsOpenObservable.Subscribe(x => Console.WriteLine($"Port {comPortName} is {(x ? "Open" : "Closed")}")).DisposeWith(comdis);// Subscribe to the Data Received
port.DataReceived.BufferUntil(startChar, endChar, 100).Subscribe(data => Console.WriteLine(data)).DisposeWith(comdis);// Subscribe to the Is Open @500ms intervals and write to com port
port.WhileIsOpen(TimeSpan.FromMilliseconds(500)).Subscribe(_ => port.Write(dataToWrite)).DisposeWith(comdis);// Open the Com Port after subscriptions created
port.Open();
}
else
{
comdis?.Dispose();
Console.WriteLine($"Port {comPortName} Disposed");
comdis = [];
}
}).ForEach().Subscribe(name =>
{
// Show available ports
Console.WriteLine(name);
}).DisposeWith(dis);
Console.ReadLine();// Cleanup ports
comdis.Dispose();
dis.Dispose();
}
}
```