Aggiungere i file di progetto.
This commit is contained in:
53
OMControl/Serial/SerialManager.cs
Normal file
53
OMControl/Serial/SerialManager.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.IO.Ports;
|
||||
using System.Text;
|
||||
|
||||
public class SerialManager : IDisposable
|
||||
{
|
||||
private SerialPort _serialPort;
|
||||
|
||||
public event Action<string>? DataReceived;
|
||||
|
||||
public bool IsOpen => _serialPort?.IsOpen ?? false;
|
||||
|
||||
public SerialManager(string portName, int baudRate)
|
||||
{
|
||||
_serialPort = new SerialPort(portName, baudRate)
|
||||
{
|
||||
Encoding = Encoding.ASCII,
|
||||
NewLine = "\n"
|
||||
};
|
||||
|
||||
_serialPort.DataReceived += OnDataReceived;
|
||||
}
|
||||
|
||||
public void Open()
|
||||
{
|
||||
if (!_serialPort.IsOpen)
|
||||
_serialPort.Open();
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (_serialPort.IsOpen)
|
||||
_serialPort.Close();
|
||||
}
|
||||
|
||||
public void Send(string data)
|
||||
{
|
||||
if (_serialPort.IsOpen)
|
||||
_serialPort.WriteLine(data);
|
||||
}
|
||||
|
||||
private void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
|
||||
{
|
||||
string data = _serialPort.ReadLine();
|
||||
DataReceived?.Invoke(data);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Close();
|
||||
_serialPort.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user