Skip to content

Commit 5554a00

Browse files
author
Dave 'Gizmo' Gymer
committed
Add Ports assembly and experimental serial class.
1 parent 120e5e5 commit 5554a00

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

Controlzmo/Controlzmo.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535

3636
<ItemGroup>
3737
<PackageReference Include="Microsoft.Web.LibraryManager.Build" Version="2.1.113" />
38+
<PackageReference Include="System.IO.Ports" Version="5.0.1" />
3839
<PackageReference Include="System.Text.Json" Version="5.0.1" />
3940
</ItemGroup>
4041

Controlzmo/Serial/Serial.cs

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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

Comments
 (0)