Aggiungere i file di progetto.
This commit is contained in:
112
OMControl/Serial/SerialDeviceProbe.cs
Normal file
112
OMControl/Serial/SerialDeviceProbe.cs
Normal file
@@ -0,0 +1,112 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Ports;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public sealed class SerialDeviceProbe
|
||||
{
|
||||
public record ProbeResult(string Port, bool Success, string? DeviceId, byte[]? RawResponse, string? Error);
|
||||
|
||||
// Define known signatures here
|
||||
// Example: response contains ASCII "DEV:XYZ" or starts with 0xAA 0x55 etc.
|
||||
private readonly List<(string Name, Func<byte[], bool> Match)> _signatures = new();
|
||||
|
||||
public SerialDeviceProbe AddSignature(string name, Func<byte[], bool> match)
|
||||
{
|
||||
_signatures.Add((name, match));
|
||||
return this;
|
||||
}
|
||||
|
||||
public async Task<ProbeResult> ProbeAsync(
|
||||
string portName,
|
||||
int baudRate,
|
||||
byte[] probeBytes,
|
||||
int readTimeoutMs = 250,
|
||||
int writeTimeoutMs = 250,
|
||||
int settleDelayMs = 80,
|
||||
int maxReadBytes = 256,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
using var sp = new SerialPort(portName, baudRate)
|
||||
{
|
||||
ReadTimeout = readTimeoutMs,
|
||||
WriteTimeout = writeTimeoutMs,
|
||||
Encoding = Encoding.ASCII,
|
||||
DtrEnable = true, // often needed for Arduino-like boards
|
||||
RtsEnable = true
|
||||
};
|
||||
|
||||
sp.Open();
|
||||
|
||||
// Some devices reboot on open (Arduino). Give them a moment.
|
||||
Thread.Sleep(settleDelayMs);
|
||||
|
||||
sp.DiscardInBuffer();
|
||||
sp.DiscardOutBuffer();
|
||||
|
||||
sp.Write(probeBytes, 0, probeBytes.Length);
|
||||
|
||||
// Read available bytes up to timeout
|
||||
var buffer = new List<byte>(maxReadBytes);
|
||||
var start = Environment.TickCount;
|
||||
|
||||
while (buffer.Count < maxReadBytes && Environment.TickCount - start < readTimeoutMs)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
try
|
||||
{
|
||||
int b = sp.ReadByte(); // blocks until byte or timeout
|
||||
if (b >= 0) buffer.Add((byte)b);
|
||||
|
||||
// Optional: break early if you know response length or terminator
|
||||
// e.g. if buffer ends with '\n'
|
||||
if (buffer.Count >= 2 && buffer[^1] == (byte)'\n') break;
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var resp = buffer.ToArray();
|
||||
if (resp.Length == 0)
|
||||
return new ProbeResult(portName, false, null, resp, "No response");
|
||||
|
||||
// Identify by signature
|
||||
foreach (var sig in _signatures)
|
||||
{
|
||||
if (sig.Match(resp))
|
||||
return new ProbeResult(portName, true, sig.Name, resp, null);
|
||||
}
|
||||
|
||||
// Unknown but responded
|
||||
return new ProbeResult(portName, true, "Unknown", resp, null);
|
||||
|
||||
}, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ProbeResult(portName, false, null, null, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ProbeResult[]> ProbeAllAsync(
|
||||
IEnumerable<string> ports,
|
||||
int baudRate,
|
||||
byte[] probeBytes,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var tasks = ports.Select(p => ProbeAsync(p, baudRate, probeBytes, ct: ct));
|
||||
return await Task.WhenAll(tasks);
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
52
OMControl/Serial/SerialPortWatcher.cs
Normal file
52
OMControl/Serial/SerialPortWatcher.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Ports;
|
||||
using System.Linq;
|
||||
using System.Timers;
|
||||
|
||||
public sealed class SerialPortWatcher : IDisposable
|
||||
{
|
||||
private readonly System.Timers.Timer _timer;
|
||||
private HashSet<string> _last = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public event Action<string[]>? PortsAdded;
|
||||
public event Action<string[]>? PortsRemoved;
|
||||
|
||||
public SerialPortWatcher(double intervalMs = 1000)
|
||||
{
|
||||
_timer = new System.Timers.Timer(intervalMs);
|
||||
_timer.Elapsed += (_, _) => Tick();
|
||||
_timer.AutoReset = true;
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
_last = GetPorts();
|
||||
_timer.Start();
|
||||
}
|
||||
|
||||
public void Stop() => _timer.Stop();
|
||||
|
||||
private void Tick()
|
||||
{
|
||||
var current = GetPorts();
|
||||
|
||||
var added = current.Except(_last).ToArray();
|
||||
var removed = _last.Except(current).ToArray();
|
||||
|
||||
if (added.Length > 0) PortsAdded?.Invoke(added);
|
||||
if (removed.Length > 0) PortsRemoved?.Invoke(removed);
|
||||
|
||||
_last = current;
|
||||
}
|
||||
|
||||
private static HashSet<string> GetPorts()
|
||||
=> new HashSet<string>(SerialPort.GetPortNames(), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_timer.Stop();
|
||||
_timer.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user