Skip to content
This repository has been archived by the owner on Dec 26, 2020. It is now read-only.

Commit

Permalink
Additional tweaks for robustness, configurability and design
Browse files Browse the repository at this point in the history
  • Loading branch information
Oceanswave committed Sep 13, 2020
1 parent f7e2e7a commit 574947c
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 31 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/CreateFSMosquitoClientRelease.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ jobs:
# - name: Run WarpPacker
# run: .\WarpPacker.exe --arch windows-x64 --input_dir "bin\x64\Release\netcoreapp3.1\win10-x64\publish\" --exec FSMosquitoClient.exe --output FSMosquitoClient.exe

- name: Remove Unnecessary files
run: rm "bin\x64\Release\netcoreapp3.1\win10-x64\publish\appsettings.dev.json"

# Zip up our build artifacts using powershell
- name: Zip build artifacts
run: Compress-Archive -Path "${{ github.workspace }}\bin\x64\Release\netcoreapp3.1\win10-x64\publish\*" FSMosquitoClient.zip
Expand Down
1 change: 1 addition & 0 deletions FSMosquitoClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.8" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.8" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.8" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="3.1.8" />
<PackageReference Include="MQTTnet" Version="3.0.12" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="2.0.0" />
Expand Down
18 changes: 4 additions & 14 deletions Forms/MainForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,21 @@ public class MainForm : Form
{
private const int PulseInterval = 1000;

public event EventHandler SimConnectMessageReceived;

private readonly System.Timers.Timer _pulseMqttStatusTimer = new System.Timers.Timer(PulseInterval);
private readonly System.Timers.Timer _pulseSimConnectStatusTimer = new System.Timers.Timer(PulseInterval);
private readonly ILogger<MainForm> _logger;
private readonly ISimConnectMqttAdapter _adapter;
private bool _hasShown = false;
private Color? _nextSimConnectStatusColor = null;
private Color? _nextMqttStatusColor = null;

private Panel _simConnectStatus;
private Panel _mqttStatus;

public MainForm(IFsMqtt fsMqtt, IFsSimConnect fsSimConnect, ISimConnectMqttAdapter adapter, ILogger<MainForm> logger)
public MainForm(IFsMqtt fsMqtt, IFsSimConnect fsSimConnect, ILogger<MainForm> logger)
{
FsMqtt = fsMqtt ?? throw new ArgumentNullException(nameof(fsMqtt));
FsSimConnect = fsSimConnect ?? throw new ArgumentNullException(nameof(fsSimConnect));
_adapter = adapter ?? throw new ArgumentNullException(nameof(adapter));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));

FsMqtt.MqttConnectionOpened += FsMqtt_MqttConnectionOpened;
Expand Down Expand Up @@ -66,7 +65,7 @@ protected override void WndProc(ref Message m)
if (FsSimConnect != null && m.Msg == Consts.WM_USER_SIMCONNECT)
{
// Fire and forget as to not block the UI thread.
Task.Run(_adapter.SignalReceiveSimConnectMessage).Forget();
Task.Run(() => SimConnectMessageReceived?.Invoke(this, EventArgs.Empty)).Forget();
}

base.WndProc(ref m);
Expand All @@ -79,15 +78,6 @@ protected override void OnShown(EventArgs e)
base.OnShown(e);
}

protected override void OnLoad(EventArgs e)
{
var handle = Handle;
// Fire and forget as to not block the UI thread.
Task.Run(() => { Task.Delay(1000); _adapter.Start(handle); }).Forget();

base.OnLoad(e);
}

protected override void OnActivated(EventArgs e)
{
_logger.LogInformation("Main Form Activated.");
Expand Down
18 changes: 15 additions & 3 deletions FsMqtt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,25 @@ public FsMqtt(IConfigurationRoot configuration, ILogger<FsMqtt> logger)
var fsmUsername = configuration["fs_mosquito_username"];
var fsmPassword = configuration["fs_mosquito_password"];

if (!int.TryParse(configuration["fs_mosquito_keep_alive_period"], out int keepAlivePeriod)) {
keepAlivePeriod = 10000;
}

if (!int.TryParse(configuration["fs_mosquito_communication_timeout"], out int communicationTimeout)) {
communicationTimeout = 30000;
}

if (!uint.TryParse(configuration["fs_mosquito_delay_interval"], out uint delayInterval)) {
delayInterval = 15000;
}

_mqttClientOptions = new MqttClientOptionsBuilder()
.WithClientId(_clientId)
.WithWebSocketServer(MqttBrokerUrl)
.WithCredentials(fsmUsername, fsmPassword)
.WithKeepAlivePeriod(TimeSpan.FromSeconds(15))
.WithCommunicationTimeout(TimeSpan.FromSeconds(120))
.WithWillDelayInterval(15 * 1000)
.WithKeepAlivePeriod(TimeSpan.FromMilliseconds(keepAlivePeriod))
.WithCommunicationTimeout(TimeSpan.FromMilliseconds(communicationTimeout))
.WithWillDelayInterval(delayInterval)
.WithWillMessage(new MqttApplicationMessage()
{
PayloadFormatIndicator = MQTTnet.Protocol.MqttPayloadFormatIndicator.CharacterData,
Expand Down
17 changes: 12 additions & 5 deletions FsSimConnect.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public sealed class FsSimConnect : IFsSimConnect

private IntPtr _lastHandle;
private SimConnect _simConnect;

public event EventHandler SimConnectOpened;
public event EventHandler SimConnectClosed;
public event EventHandler<(SimConnectTopic, uint, object)> TopicValueChanged;
Expand Down Expand Up @@ -62,6 +62,8 @@ public bool IsDisposed
get;
private set;
}

public bool IsOpen { get; private set; }
#endregion

public void Connect(IntPtr handle)
Expand Down Expand Up @@ -133,7 +135,10 @@ public void SignalReceiveSimConnectMessage()

try
{
_simConnect.ReceiveMessage();
lock (_simConnect)
{
_simConnect.ReceiveMessage();
}
}
catch(Exception ex)
{
Expand Down Expand Up @@ -248,7 +253,7 @@ private void RegisterSubscriptionDataDefinition(SimConnectSubscription subscript
catch(Exception ex)
{
_logger.LogError($"An exception occurred attempting to register a data definition {ex.Message}", ex);
}
}
}

#region Event Handlers
Expand All @@ -259,8 +264,9 @@ private void RegisterSubscriptionDataDefinition(SimConnectSubscription subscript
/// <param name="data"></param>
private void SimConnect_OnRecvOpen(SimConnect sender, SIMCONNECT_RECV_OPEN data)
{
IsOpen = true;
_logger.LogInformation("SimConnect_OnRecvOpen");

_pulseTimer.Start();
OnSimConnect_Opened();
}
Expand All @@ -272,6 +278,7 @@ private void SimConnect_OnRecvOpen(SimConnect sender, SIMCONNECT_RECV_OPEN data)
/// <param name="data"></param>
private void SimConnect_OnRecvQuit(SimConnect sender, SIMCONNECT_RECV data)
{
IsOpen = false;
_logger.LogInformation("SimConnect_OnRecvQuit");
OnSimConnect_Closed();

Expand Down Expand Up @@ -303,7 +310,7 @@ private void SimConnect_OnRecvSimObjectDataByType(SimConnect sender, SIMCONNECT_
uint requestId = data.dwRequestID;
uint objectId = data.dwObjectID;

// ObjectID == 1 is the user object data (I think)
// ObjectID == 0 is the user object data. See SimConnect.SIMCONNECT_OBJECT_ID_USER;
object currentValue;
if (_pendingSubscriptions.TryRemove((int)requestId, out SimConnectSubscription subscription))
{
Expand Down
7 changes: 6 additions & 1 deletion IFsSimConnect.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public interface IFsSimConnect : IDisposable
public event EventHandler SimConnectDataRequested;

/// <summary>
/// Gets a value that indicates if the current instance is connected to SimConnect
/// Gets a value that indicates if the current instance has been able to create a SimConnect instance
/// </summary>
bool IsConnected { get; }

Expand All @@ -42,6 +42,11 @@ public interface IFsSimConnect : IDisposable
/// </summary>
bool IsDisposed { get; }

/// <summary>
/// Gets a value that indicates if the SimConnect connection is open and active
/// </summary>
bool IsOpen { get; }

/// <summary>
/// Start receiving messages from SimConnect
/// </summary>
Expand Down
29 changes: 24 additions & 5 deletions Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FSMosquitoClient
{
using FSMosquitoClient.Extensions;
using FSMosquitoClient.Forms;
using FSMosquitoClient.Properties;
using Microsoft.Extensions.Configuration;
Expand All @@ -12,6 +13,7 @@
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tmds.Utils;

Expand Down Expand Up @@ -70,12 +72,25 @@ public Program(bool showWindowOnStartup = true)

_trayIcon.BalloonTipClosed += (sender, e) =>
{
var thisIcon = (NotifyIcon)sender; thisIcon.Visible = false; thisIcon.Dispose();
_trayIcon.Visible = false;
_trayIcon.Dispose();
};

// Associate the form with the adapter
var form = _serviceProvider.GetService<MainForm>();
var adapter = _serviceProvider.GetService<ISimConnectMqttAdapter>();
var handle = form.Handle; // Use a separate variable as to not pass the thread context
form.SimConnectMessageReceived += (object sender, EventArgs e) =>
{
adapter.SignalReceiveSimConnectMessage();
};

// Fire and forget as to not block the UI thread.
Task.Run(() => { Task.Delay(2500); adapter.Start(handle); }).Forget();

if (showWindowOnStartup)
{
MainForm = _serviceProvider.GetService<MainForm>();
MainForm = form;
MainForm.Show();
MainForm.Activate();
}
Expand All @@ -89,8 +104,12 @@ public Program(bool showWindowOnStartup = true)
[STAThread]
static void Main(string[] args)
{
if (args.Length < 1 || !bool.TryParse(args[0], out bool showWindowOnStartup))
{
showWindowOnStartup = true;
}
#if DEBUG
Launch();
Launch(showWindowOnStartup);
#else

if (ExecFunction.IsExecFunctionCommand(args))
Expand All @@ -101,7 +120,7 @@ static void Main(string[] args)
{
FSMosquitoExecutor.Run(() =>
{
Launch();
Launch(showWindowOnStartup);
});
}
#endif
Expand All @@ -128,7 +147,7 @@ private static void Launch(bool showWindowOnStartup = true)
.SetBasePath(GetBasePath())
.AddJsonFile("appsettings.json", false)
#if DEBUG
.AddJsonFile("appsettings.dev.json", false)
.AddJsonFile("appsettings.dev.json", true)
#endif
.AddEnvironmentVariables();
var configuration = builder.Build();
Expand Down
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,9 @@ This project contains a publishing profile that will bundle the application (inc
A GitHub action is included that will automatically build and publish new releases to GitHub

- On Push to Master or on PR - Builds the project and stores the result as an artifact (except for changes to README.md and /docs/*)
- On tag that starts with 'v' (ex: ```git tag -a v0.2.0-alpha01 -m "Release Description" && git push --tags```) Builds the project and creates a release that corresponds to the tag.
- On tag that starts with 'v' (ex: ```git tag -a v0.2.0-alpha01 -m "Release Description" && git push --tags```) Builds the project and creates a release that corresponds to the tag.


## Resources

https://csharp.hotexamples.com/examples/-/SimConnect/RequestDataOnSimObject/php-simconnect-requestdataonsimobject-method-examples.html
5 changes: 3 additions & 2 deletions Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ public void ConfigureServices(IServiceCollection services)
builder
.AddSerilog()
.SetMinimumLevel(LogLevel.Error)
.AddFile("Logs/FSMosquitoClient-{Date}.txt");
.AddFile("Logs/FSMosquitoClient-{Date}.txt")
.AddConfiguration(Configuration.GetSection("Logging"));
});

services.AddSingleton(Configuration);
Expand All @@ -39,7 +40,7 @@ public void ConfigureServices(IServiceCollection services)

services.AddSingleton(f =>
{
return new MainForm(f.GetService<IFsMqtt>(), f.GetService<IFsSimConnect>(), f.GetService<ISimConnectMqttAdapter>(), f.GetService<ILogger<MainForm>>())
return new MainForm(f.GetService<IFsMqtt>(), f.GetService<IFsSimConnect>(), f.GetService<ILogger<MainForm>>())
{
StartPosition = FormStartPosition.CenterScreen,
ShowInTaskbar = false,
Expand Down

0 comments on commit 574947c

Please sign in to comment.