Skip to content

Commit

Permalink
done with initial version of greenhouse app
Browse files Browse the repository at this point in the history
  • Loading branch information
freddycoder committed May 25, 2024
1 parent 5fc1e66 commit bab1bdf
Show file tree
Hide file tree
Showing 6 changed files with 362 additions and 254 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ bld/
[Oo]bj/
[Ll]og/
[Ll]ogs/
log*.txt

# Visual Studio 2015/2017 cache/options directory
.vs/
Expand Down
25 changes: 25 additions & 0 deletions DirectNet.Net.Greenhouse.GUI/DirectNet.Net.Greenhouse.GUI.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.002.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DirectNet.Net.Greenhouse.GUI", "DirectNet.Net.Greenhouse.GUI.csproj", "{B83970EE-3EF8-49ED-83F7-8490E662B377}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B83970EE-3EF8-49ED-83F7-8490E662B377}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B83970EE-3EF8-49ED-83F7-8490E662B377}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B83970EE-3EF8-49ED-83F7-8490E662B377}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B83970EE-3EF8-49ED-83F7-8490E662B377}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {360FC248-4327-4F88-9A47-132AB121F47F}
EndGlobalSection
EndGlobal
215 changes: 152 additions & 63 deletions DirectNet.Net.Greenhouse.GUI/Form1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public partial class Form1 : Form
private IDirectNetClient? _client;
private CancellationTokenSource? _cst;
private Task? _task;
private const int readLength = 8;

public Form1(IServiceProvider provider)
{
Expand All @@ -33,9 +34,13 @@ private void ChooseComPortAndLaunchTask()
string[] ports = SetPortListCombobox();
if (ports.Length > 0)
{
toolStripComboBox1.SelectedIndex = 0;
toolStripComboBox1.SelectedIndex = ports.ToList().IndexOf("COM4");
if (toolStripComboBox1.SelectedIndex == -1)
{
toolStripComboBox1.SelectedIndex = 0;
}
toolStripComboBox1.SelectedIndexChanged += ToolStripComboBox1_SelectedIndexChanged;
RunAndManageBackgroundTask(ports[0]);
RunAndManageBackgroundTask(ports[toolStripComboBox1.SelectedIndex]);
}
else
{
Expand All @@ -51,25 +56,36 @@ private void ChooseComPortAndLaunchTask()
private string[] SetPortListCombobox()
{
toolStripComboBox1.Items.Clear();
var ports = SerialPort.GetPortNames();
var ports = SerialPort.GetPortNames().OrderBy(p => p).ToArray();
_logger.LogInformation("Available ports: {ports}", ports.Aggregate((a, b) => $"{a}, {b}"));
toolStripComboBox1.Items.AddRange(ports);
return ports;
}

private void RunAndManageBackgroundTask(string port)
{
_logger.LogInformation("RunAndManageBackgroundTask with port {port}", port);
CleanupBackgroudTask();
_logger.LogInformation("CleanupBackgroudTask done. Creating new CancellationTokenSource");

_cst = new CancellationTokenSource();
if (!string.IsNullOrWhiteSpace(port))
{
_client = new DirectNetClient(port);
}
var token = _cst.Token;
_task = Task.Run(async () =>
{
_logger.LogInformation("Task.Run started");

var chrono = new Stopwatch();

if (_client?.IsOpen == false || _client == null)
{
if (_client == null)
{
_logger.LogInformation("Creating new DirectNetClient with port {port}", port);
_client = new DirectNetClient(port);
}
await OpenSerialClient(token);
}

int exceptionInRow = 0;

var api = _provider.GetRequiredService<IErabliereAPIProxy>();
Expand All @@ -78,6 +94,13 @@ private void RunAndManageBackgroundTask(string port)
{
try
{
if (_client == null)
{
throw new InvalidOperationException("Client must not be null to run the background task");
}

var values = await _client.ReadAsync("V4000", readLength, token: token);

var lastHour = DateTimeOffset.UtcNow - TimeSpan.FromHours(1);

var erablieres = await api.ErablieresAllAsync(
Expand All @@ -87,11 +110,17 @@ private void RunAndManageBackgroundTask(string port)
top: null,
skip: null,
expand: $"capteurs($expand=donneescapteur($filter=d gt {lastHour:yyyy-MM-ddTHH:mm:ss.FFFZ};$top=1;$orderby=d desc))",
orderby: null);
orderby: null,
cancellationToken: token);

var erabliere = erablieres.First();

var precipitations = await api.HourlyAsync(erabliere.Id.Value, "fr-CA");
if (erabliere.Id == null)
{
throw new InvalidOperationException("Erabliere Id must not be null");
}

var precipitations = await api.HourlyAsync(erabliere.Id.Value, "fr-CA", cancellationToken: token);

Invoke(() =>
{
Expand All @@ -101,23 +130,15 @@ private void RunAndManageBackgroundTask(string port)
groupBox15.Text = "Valve 1";
groupBox16.Text = "Valve 2";

groupBox14.Text = "Précipitation 12h";
groupBox14.Text = "Précipitation 12h";
label12.Text = $"{precipitations.Sum(f => f.HasPrecipitation == true ? 1 : 0)} heures";

button1.Text = "Ouvrir";
button2.Text = "Fermer";
button3.Text = "Ouvrir";
button4.Text = "Fermer";

if (_client?.IsOpen == true)
{

}
else
{
label13.Text = "Non connecté";
label14.Text = "Non connecté";
}
UpdatePLCUI(values);

for (var i = 0; i < _options.Value.CapteursIds.Length; i++)
{
Expand Down Expand Up @@ -176,6 +197,8 @@ private void RunAndManageBackgroundTask(string port)
}
}
}

toolStripStatusLabel5.Text = $"Last update: {DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss}";
});

await Task.Delay(TimeSpan.FromSeconds(_options.Value.PLCScanFrequencyInSeconds), token);
Expand Down Expand Up @@ -228,6 +251,23 @@ private void RunAndManageBackgroundTask(string port)
}, token);
}

private void UpdatePLCUI(byte[] values)
{
_logger.LogInformation("UpdatePLCUI with values {values}", values.Select(v => v.ToString()).Aggregate((a, b) => $"{a}, {b}"));

if (_client?.IsOpen == true && values != null)
{
label13.Text = values[0] == 1 ? "Ouverte" : "Fermé";
label14.Text = values[4] == 1 ? "Ouverte" : "Fermé";
}
else
{
label13.Text = "Non connecté";
label14.Text = "Non connecté";
}
}


private string FormatLabelText(Capteur capteur)
{
var data = capteur.DonneesCapteur?.SingleOrDefault();
Expand Down Expand Up @@ -276,30 +316,6 @@ private async Task OpenSerialClient(CancellationToken token)

public DateTime _lastSend;

private async ValueTask UpdateErabliereAPI(int[] values, CancellationToken token)
{
var options = _provider.GetRequiredService<IOptions<ErabliereApiOptionsWithSensors>>().Value;

if (options.SendIntervalInMinutes <= 0)
{
Invoke(() =>
{
toolStripStatusLabel5.Text = "ErabliereAPI: Disabled";
});
}
else if (DateTime.Now - _lastSend > TimeSpan.FromMinutes(options.SendIntervalInMinutes))
{
Invoke(() =>
{
toolStripStatusLabel5.Text = $"ErabliereAPI: Sending datas {DateTime.Now}";
});

await ErabliereApiTasks.Send24ValuesAsync(_provider, values, token);

_lastSend = DateTime.Now;
}
}

private void ToolStripComboBox1_SelectedIndexChanged(object? sender, EventArgs e)
{
if (sender is ToolStripComboBox comboBox)
Expand Down Expand Up @@ -345,7 +361,11 @@ private void CleanupBackgroudTask()
{
try
{
_cst.Cancel();
if (!_cst.IsCancellationRequested)
{
_logger.LogInformation("CancellationTokenSource.Cancel");
_cst.Cancel();
}
_cst.Dispose();
if (_task != null)
{
Expand All @@ -356,6 +376,10 @@ private void CleanupBackgroudTask()

try
{
if (_task.Status == TaskStatus.WaitingForActivation)
{
_task.Start();
}
_task.Dispose();
}
catch (Exception e)
Expand All @@ -376,13 +400,24 @@ private void CleanupBackgroudTask()

if (_client != null)
{
_logger.LogInformation("Closing com port {portName}", _client.PortName);
_client.Close();
toolStripStatusLabel2.Text = $"State: Close";
toolStripStatusLabel3.Text = "";
toolStripStatusLabel4.Text = $"Enquery: n/a";
_logger.LogInformation("Disposing serial client");
_client.Dispose();
try
{
_logger.LogInformation("Closing com port {portName}", _client.PortName);
_client.Close();
toolStripStatusLabel2.Text = $"State: Close";
toolStripStatusLabel3.Text = "";
toolStripStatusLabel4.Text = $"Enquery: n/a";
_logger.LogInformation("Disposing serial client");
_client.Dispose();
}
catch (Exception e)
{
_logger.LogError(e, "Error when closing the serial client");
}
finally
{
_client = null;
}
}
}

Expand All @@ -393,38 +428,92 @@ private void ToolStripResetDriverButton_Click(object sender, EventArgs e)
ChooseComPortAndLaunchTask();
}

private void OuvrirValve1(object sender, EventArgs e)
private async void OuvrirValve1(object sender, EventArgs e)
{
if (_client?.IsOpen == true)
try
{
if (_client?.IsOpen == true)
{
_client.WriteAsync("V4000", new byte[] { 0b1 });
if (_client?.IsOpen == true)
{
await _client.WriteAsync("V4000", [0b0, 0b1], token: _cst?.Token ?? default);

var values = await _client.ReadAsync("V4000", readLength, token: _cst?.Token ?? default);

Invoke(() =>
{
UpdatePLCUI(values);
});
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error when opening valve 1");
}
}

private void FermerVavle1(object sender, EventArgs e)
private async void FermerVavle1(object sender, EventArgs e)
{
if (_client?.IsOpen == true)
try
{
if (_client?.IsOpen == true)
{
await _client.WriteAsync("V4000", [0b0, 0b0], token: _cst?.Token ?? default);

var values = await _client.ReadAsync("V4000", readLength, token: _cst?.Token ?? default);

Invoke(() =>
{
UpdatePLCUI(values);
});
}
}
catch (Exception ex)
{
_client.WriteAsync("V4000", new byte[] { 0b0 });
_logger.LogError(ex, "Error when closing valve 1");
}
}

private void OuvrirValve2(object sender, EventArgs e)
private async void OuvrirValve2(object sender, EventArgs e)
{
if (_client?.IsOpen == true)
try {
if (_client?.IsOpen == true)
{
await _client.WriteAsync("V4002",[0b0, 0b1], token: _cst?.Token ?? default);

var values = await _client.ReadAsync("V4000", readLength, token: _cst?.Token ?? default);

Invoke(() =>
{
UpdatePLCUI(values);
});
}
}
catch (Exception ex)
{
_client.WriteAsync("V4002", new byte[] { 0b1 });
_logger.LogError(ex, "Error when opening valve 2");
}
}

private void FermerValve2(object sender, EventArgs e)
private async void FermerValve2(object sender, EventArgs e)
{
if (_client?.IsOpen == true)
try {
if (_client?.IsOpen == true)
{
await _client.WriteAsync("V4002", [0b0, 0b0], token: _cst?.Token ?? default);

var values = await _client.ReadAsync("V4000", readLength, token: _cst?.Token ?? default);

Invoke(() =>
{
UpdatePLCUI(values);
});
}
}
catch (Exception ex)
{
_client.WriteAsync("V4002", new byte[] { 0b0 });
_logger.LogError(ex, "Error when closing valve 2");
}
}
}
Loading

0 comments on commit bab1bdf

Please sign in to comment.