|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using Controlzmo.Hubs; |
| 6 | +using SimConnectzmo; |
| 7 | +using System.IO.Ports; |
| 8 | +using System.Threading; |
| 9 | + |
| 10 | +namespace Controlzmo.Serial |
| 11 | +{ |
| 12 | + [Component] |
| 13 | + public class Serial : CreateOnStartup, IDisposable |
| 14 | + { |
| 15 | + private readonly SerialPort _serialPort; |
| 16 | + private readonly Thread readThread; // Convert to BackgroundWorker a la Adapter |
| 17 | + private bool running = true; |
| 18 | + |
| 19 | + public Serial() |
| 20 | + { |
| 21 | + _serialPort = new SerialPort(portName: "COM3", baudRate: 115200, parity: Parity.None, dataBits: 8); |
| 22 | + _serialPort.StopBits = StopBits.One; |
| 23 | + _serialPort.Handshake = Handshake.RequestToSend; |
| 24 | + _serialPort.DtrEnable = true; |
| 25 | + _serialPort.ReadTimeout = 500; |
| 26 | + _serialPort.WriteTimeout = 500; |
| 27 | + _serialPort.Open(); |
| 28 | + //TOOD: read thread... https://docs.microsoft.com/en-us/dotnet/api/system.io.ports.serialport?view=dotnet-plat-ext-5.0 |
| 29 | + readThread = new Thread(Read); |
| 30 | + readThread.IsBackground = true; |
| 31 | + readThread.Start(); |
| 32 | + Console.Error.WriteLine("Started serial <><><><><>"); |
| 33 | + } |
| 34 | + |
| 35 | + public void Read() |
| 36 | + { |
| 37 | + byte[] writeData = { 0 }; |
| 38 | + while (running) |
| 39 | + { |
| 40 | + try |
| 41 | + { |
| 42 | + string message = _serialPort.ReadLine(); |
| 43 | + Console.Error.WriteLine(message); |
| 44 | + } |
| 45 | + catch (TimeoutException) |
| 46 | + { |
| 47 | + Console.Error.WriteLine("Nothing to read"); |
| 48 | + writeData[0] ^= 1; |
| 49 | + _serialPort.Write(writeData, 0, 1); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + public void Dispose() |
| 55 | + { |
| 56 | + running = false; |
| 57 | + readThread.Join(); |
| 58 | + _serialPort.Close(); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments