-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
817 lines (710 loc) · 31.8 KB
/
MainWindow.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
using Microsoft.Win32;
using MQTTnet.Protocol;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Generic;
using Hardcodet.Wpf.TaskbarNotification;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using PC2MQTT.api;
using System.Windows.Controls;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using Microsoft.VisualBasic.Devices;
using MQTTnet.Client;
using System.Text;
namespace PC2MQTT
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
private MenuItem _aboutMenuItem;
private MenuItem _logMenuItem;
private Dictionary<string, string> _previousSensorStates = new Dictionary<string, string>();
private AppSettings _settings;
private string _settingsFilePath;
private pc_sensors _pcSensors;
private MenuItem _teamsStatusMenuItem;
private string deviceid;
private MenuItem _mqttStatusMenuItem;
private PCMetrics _pcMetrics;
private bool isDarkTheme = true;
private bool mqttStatusUpdated = false;
private System.Timers.Timer _updateTimer;
private MqttService _mqttService;
private PerformanceCounter cpuCounter; // Declare, but don't initialize here
private PerformanceCounter memoryCounter;
private MainViewModel _viewModel;
private double _totalPhysicalMemory;
public double TotalPhysicalMemory
{
get => _totalPhysicalMemory;
set
{
if (_totalPhysicalMemory != value)
{
_totalPhysicalMemory = value;
OnPropertyChanged(nameof(TotalPhysicalMemory));
}
}
}
private double _usedMemoryPercentage;
public double UsedMemoryPercentage
{
get => _usedMemoryPercentage;
set
{
if (_usedMemoryPercentage != value)
{
_usedMemoryPercentage = value;
OnPropertyChanged(nameof(UsedMemoryPercentage));
}
}
}
private Queue<double> cpuReadings = new Queue<double>();
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private double _cpuUsage;
public double CpuUsage
{
get => _cpuUsage;
set
{
if (_cpuUsage != value)
{
_cpuUsage = value;
OnPropertyChanged(nameof(CpuUsage)); // Notify the UI that value has changed
}
}
}
private double _memoryUsage;
public double MemoryUsage
{
get => _memoryUsage;
set
{
if (_memoryUsage != value)
{
_memoryUsage = value;
OnPropertyChanged(nameof(MemoryUsage));
}
}
}
private double memoryAvailableGB;
private double totalMemoryGB;
private double memoryUsedGB;
public MainWindow()
{
// Get the local application data folder path
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
// Configure logging
LoggingConfig.Configure();
// Create the PC2MQTT folder in the local application data folder
var appDataFolder = Path.Combine(localAppData, "PC2MQTT");
Log.Debug("Set Folder Path to {path}", appDataFolder);
Directory.CreateDirectory(appDataFolder); // Ensure the directory exists
// Set the settings file path
_settingsFilePath = Path.Combine(appDataFolder, "settings.json");
// Get the app settings instance
var settings = AppSettings.Instance;
_settings = AppSettings.Instance;
// Get the device ID
if (string.IsNullOrEmpty(_settings.SensorPrefix))
{
deviceid = System.Environment.MachineName;
}
else
{
deviceid = _settings.SensorPrefix;
}
// Log the settings file path
Log.Debug("Settings file path is {path}", _settingsFilePath);
// Initialize the main window
this.InitializeComponent();
_viewModel = new MainViewModel();
DataContext = _viewModel;
InitializeMqttService();
// Add event handler for when the main window is loaded
this.Loaded += MainPage_Loaded;
// Set the icon for the notification tray
string iconPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Square150x150Logo.scale-200.ico");
MyNotifyIcon.Icon = new System.Drawing.Icon(iconPath);
CreateNotifyIconContextMenu();
// Create a new instance of the MQTT Service class
}
private double GetCpuUsage()
{
if (cpuCounter == null) return 0; // Safety check
var value = cpuCounter.NextValue();
cpuReadings.Enqueue(value);
while (cpuReadings.Count > 10) cpuReadings.Dequeue();
return cpuReadings.Average();
}
private void MqttManager_ConnectionStatusChanged(string status)
{
Dispatcher.Invoke(() =>
{
MQTTConnectionStatus.Text = status; // Ensure MQTTConnectionStatus is the correct UI element's name
});
}
private async void InitializeMqttService()
{
// Assuming _settings is already initialized here correctly
if (_settings == null)
{
// Log or handle the error as needed
Console.WriteLine("Settings must be initialized before initializing MqttService.");
return;
}
// Initialize MqttService with settings
_mqttService = MqttService.InitializeInstance(_settings);
await _mqttService.InitializeAsync(_settings, "uniqueClientId");
// Setup event handlers
_mqttService.ConnectionStatusChanged += MqttManager_ConnectionStatusChanged;
SetupMqttEventHandlers();
// Ensure this method waits for the MQTT service to be fully initialized if needed
UpdateMqttStatus(_mqttService.CurrentStatus);
// After initializing the MqttService, subscribe to switch commands
await _mqttService.SubscribeToSwitchCommandsAsync();
// Other configurations can follow here
await PublishConfigurationsAsync();
await PublishAutoDiscoveryConfigs();
}
private async Task OnMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
{
// Process received message
var message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
Console.WriteLine($"Message received on topic {e.ApplicationMessage.Topic}: {message}");
// Implement further processing as needed
}
private void OnMqttMessageReceived(string topic, string payload)
{
// Handle the received message. Update UI or process data as needed.
Dispatcher.Invoke(() => {
// Example: Update UI based on topic and payload
if (topic == "some/specific/topic")
{
// Update your UI or internal state
}
});
}
private async void UpdateCpuUsageDisplay()
{
//if (cpuCounter == null) return;
double cpuUsage = GetCpuUsage(); // Fetch new value
PCMetrics metrics = PCMetrics.Instance;
metrics.CpuUsage = cpuUsage; // Update the singleton instance
Dispatcher.Invoke(() => {
_viewModel.CpuUsage = cpuUsage; // Update bound property
//Log.Debug("CPU Usage: {cpuUsage}", cpuUsage);
});
}
private void UpdateMemoryUsageDisplay()
{
// Initialization and safety checks.
if (memoryCounter == null || TotalPhysicalMemory <= 0) return;
PCMetrics metrics = PCMetrics.Instance;
// Perform calculations.
double memoryAvailableGB = memoryCounter.NextValue() / 1024; // Convert from MB to GB
double totalMemoryGB = TotalPhysicalMemory; // Already in GB from MainPage_Loaded
double memoryUsedGB = totalMemoryGB - memoryAvailableGB;
double memoryUsagePercentage = (memoryUsedGB / totalMemoryGB) * 100;
// Update the singleton instance.
metrics.MemoryUsage = memoryUsagePercentage;
metrics.TotalRam = totalMemoryGB;
metrics.FreeRam = memoryAvailableGB;
metrics.UsedRam = memoryUsedGB;
// Update UI.
Dispatcher.Invoke(() =>
{
MemoryUsage = memoryUsagePercentage; // Update UI element for memory usage
UsedMemoryPercentage = memoryUsagePercentage;
_viewModel.UsedMemoryPercentage = memoryUsagePercentage;// Update other UI elements if necessary.
});
}
private void InitializeTimer()
{
_updateTimer = new System.Timers.Timer(1000); // Update every second
_updateTimer.Elapsed += OnTimedEvent; // Assign the event handler
_updateTimer.AutoReset = true; // Continue raising events
_updateTimer.Enabled = true; // Start the timer
}
private void MyNotifyIcon_Click(object sender, EventArgs e)
{
if (this.WindowState == WindowState.Minimized)
{
// Restore the window if it's minimized
this.Show();
this.WindowState = WindowState.Normal;
}
else
{
// Minimize the window if it's currently normal or maximized
this.WindowState = WindowState.Minimized;
}
}
private async void InitializePerformanceCounters()
{
await Task.Run(() =>
{
cpuCounter = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total", true);
var unusedCpu = cpuCounter.NextValue(); // Prime the CPU counter.
// Initialize and prime memory counter.
memoryCounter = new PerformanceCounter("Memory", "Available MBytes", true);
var unusedMem = memoryCounter.NextValue(); // Prime the memory counter.
});
}
protected override void OnStateChanged(EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
// Only hide the window and show the NotifyIcon when minimized
this.Hide();
MyNotifyIcon.Visibility = Visibility.Visible;
}
else
{
// Ensure the NotifyIcon is hidden when the window is not minimized
MyNotifyIcon.Visibility = Visibility.Collapsed;
}
base.OnStateChanged(e);
}
private void AboutMenuItem_Click(object sender, RoutedEventArgs e)
{
// Retrieve the current theme from settings
string currentTheme = _settings.Theme;
// Get the device ID from the MqttService instance
if (string.IsNullOrEmpty(_settings.SensorPrefix))
{
deviceid = System.Environment.MachineName;
}
else
{
deviceid = _settings.SensorPrefix;
}
// Get the list of sensors and switches from the MqttService instance
var sensorsAndSwitches = new List<string>(_pcSensors.GetSensorAndSwitchNames(deviceid));
// Create and display the AboutWindow
AboutWindow aboutWindow = new AboutWindow(deviceid, MyNotifyIcon, sensorsAndSwitches);
aboutWindow.Owner = this;
aboutWindow.ShowDialog();
}
public async Task PublishConfigurationsAsync(bool forcePublish = false)
{
var deviceId = _settings.SensorPrefix;
var deviceInfo = new
{
identifiers = new[] { deviceId },
manufacturer = "Custom",
model = "PC Monitor",
name = deviceId,
sw_version = "1.0"
};
List<string> entityNames = new List<string>
{
"shutdown", "reboot", "standby", "hibernate"
};
foreach (var entityName in entityNames)
{
string topic;
object payload;
if (entityName.Contains("shutdown") || entityName.Contains("reboot") || entityName.Contains("standby") || entityName.Contains("hibernate"))
{
topic = $"homeassistant/switch/{deviceId}/{entityName}/config";
payload = new
{
name = $"{deviceId}_{entityName}",
unique_id = $"{deviceId}_{entityName}",
device = deviceInfo,
command_topic = $"homeassistant/switch/{deviceId}/{entityName}/set",
state_topic = $"homeassistant/switch/{deviceId}/{entityName}/state",
payload_on = "ON",
payload_off = "OFF"
};
}
else
{
topic = $"homeassistant/sensor/{deviceId}/{entityName}/config";
payload = new
{
name = $"{deviceId}_{entityName}",
unique_id = $"{deviceId}_{entityName}",
device = deviceInfo,
state_topic = $"homeassistant/sensor/{deviceId}/{entityName}/state",
unit_of_measurement = entityName.Contains("usage") ? "%" : "GB",
icon = entityName.Contains("cpu") ? "mdi:cpu-64-bit" : "mdi:memory"
};
}
await _mqttService.PublishAsync(topic, JsonConvert.SerializeObject(payload), MqttQualityOfServiceLevel.AtLeastOnce);
if (topic.Contains("/switch/"))
{
string stateTopic = topic.Replace("/config", "/state");
await _mqttService.PublishAsync(stateTopic, "OFF", MqttQualityOfServiceLevel.AtLeastOnce);
}
}
}
private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
// Initialize local variables to default values
double localCpuUsage = 0;
double localMemoryUsage = 0;
double localTotalRam = 0;
double localFreeRam = 0;
double localUsedRam = 0;
// Now update the singleton instance of PCMetrics with the latest values
var metrics = PCMetrics.Instance;
// Update logic (should run in the UI thread because it might update UI elements)
Dispatcher.Invoke(() =>
{
UpdateCpuUsageDisplay(); // This updates this.CpuUsage based on latest system info
UpdateMemoryUsageDisplay(); // This updates this.MemoryUsage and RAM values based on latest system info
CpuUsage = metrics.CpuUsage;
MemoryUsage = metrics.MemoryUsage;
// Copy values to local variables after they have been updated
localCpuUsage = metrics.CpuUsage;
localMemoryUsage = metrics.MemoryUsage;
localTotalRam = metrics.TotalRam;
localFreeRam = metrics.FreeRam;
localUsedRam = metrics.UsedRam;
});
_ = PublishMetrics(); // Publish the updated metrics to MQTT
metrics.CpuUsage = localCpuUsage;
// Pass the updated singleton instance to your MQTT service for publishing
_pcSensors?.UpdatePCMetrics(metrics);
}
private void ApplyTheme(string theme)
{
isDarkTheme = theme == "Dark";
Uri themeUri;
if (theme == "Dark")
{
themeUri = new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Dark.xaml");
isDarkTheme = true;
}
else
{
themeUri = new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml");
isDarkTheme = false;
}
// Update the theme
var existingTheme = System.Windows.Application.Current.Resources.MergedDictionaries.FirstOrDefault(d => d.Source == themeUri);
if (existingTheme == null)
{
existingTheme = new ResourceDictionary() { Source = themeUri };
System.Windows.Application.Current.Resources.MergedDictionaries.Add(existingTheme);
}
// Remove the other theme
var otherThemeUri = isDarkTheme
? new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml")
: new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Dark.xaml");
var currentTheme = System.Windows.Application.Current.Resources.MergedDictionaries.FirstOrDefault(d => d.Source == otherThemeUri);
if (currentTheme != null)
{
System.Windows.Application.Current.Resources.MergedDictionaries.Remove(currentTheme);
}
}
private void ExitMenuItem_Click(object sender, RoutedEventArgs e)
{
// Handle the click event for the exit menu item (Close the application)
System.Windows.Application.Current.Shutdown();
}
private void LogsButton_Click(object sender, RoutedEventArgs e)
{
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PC2MQTT");
// Ensure the directory exists
if (!Directory.Exists(folderPath))
{
Log.Error("Log directory does not exist.");
return;
}
// Get the most recent log file
var logFile = Directory.GetFiles(folderPath, "PC2MQTT_Log*.log")
.OrderByDescending(File.GetCreationTime)
.FirstOrDefault();
if (logFile != null && File.Exists(logFile))
{
try
{
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
FileName = logFile,
UseShellExecute = true
};
Process.Start(processStartInfo);
}
catch (Exception ex)
{
Log.Error($"Error opening log file: {ex.Message}");
}
}
else
{
Log.Error("Log file does not exist.");
}
}
private void ShowHideMenuItem_Click(object sender, RoutedEventArgs e)
{
if (this.IsVisible)
{
this.Hide();
}
else
{
this.Show();
this.WindowState = WindowState.Normal;
}
}
private void CreateNotifyIconContextMenu()
{
ContextMenu contextMenu = new ContextMenu();
// Show/Hide Window
MenuItem showHideMenuItem = new MenuItem();
showHideMenuItem.Header = "Show/Hide";
showHideMenuItem.Click += ShowHideMenuItem_Click;
// MQTT Status
_mqttStatusMenuItem = new MenuItem { Header = "MQTT Status: Unknown", IsEnabled = false };
// Logs
_logMenuItem = new MenuItem { Header = "View Logs" };
_logMenuItem.Click += LogsButton_Click; // Reuse existing event handler
// About
_aboutMenuItem = new MenuItem { Header = "About" };
_aboutMenuItem.Click += AboutMenuItem_Click;
// Exit
MenuItem exitMenuItem = new MenuItem();
exitMenuItem.Header = "Exit";
exitMenuItem.Click += ExitMenuItem_Click;
contextMenu.Items.Add(showHideMenuItem);
contextMenu.Items.Add(_logMenuItem);
contextMenu.Items.Add(_aboutMenuItem);
contextMenu.Items.Add(new Separator()); // Separator before exit
contextMenu.Items.Add(exitMenuItem);
MyNotifyIcon.ContextMenu = contextMenu;
}
private void UpdateMqttStatus(string status)
{
Dispatcher.Invoke(() =>
{
_viewModel.MqttStatus = status;
});
}
protected override async void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
_updateTimer.Elapsed -= OnTimedEvent;
_updateTimer.Stop();
_updateTimer.Dispose();
MyNotifyIcon.Dispose();
if (_mqttService != null)
{
await _mqttService.DisconnectAsync();
}
}
private void UpdateStatusMenuItems()
{
Dispatcher.Invoke(() =>
{
// Check if _mqttService is not null and use the IsConnected property
var isConnected = _mqttService?.IsConnected ?? false;
var statusText = isConnected ? "MQTT Status: Connected" : "MQTT Status: Disconnected";
// Update MQTT connection status text
//MQTTConnectionStatus.Text = statusText;
// Update menu items
if (_mqttStatusMenuItem != null) // Ensure _mqttStatusMenuItem is not null
{
_mqttStatusMenuItem.Header = statusText;
}
// Add other status updates here as necessary
});
}
private async Task PublishAutoDiscoveryConfigs()
{
var baseTopic = $"homeassistant/sensor/{deviceid}/";
var sensors = new Dictionary<string, (string Unit, string Icon)>
{
{"cpu_usage", ("%", "mdi:memory")},
// Add other sensors here, e.g., "total_ram", "free_ram", "used_ram" with their respective units and icons
{"total_ram", ("GB", "mdi:memory")},
{"free_ram", ("GB", "mdi:memory")},
{"used_ram", ("GB", "mdi:memory")}
};
foreach (var sensor in sensors)
{
var configTopic = $"{baseTopic}{sensor.Key}/config";
var payload = new
{
name = $"{deviceid.ToUpper()} {sensor.Key.Replace("_", " ")}",
unique_id = $"{deviceid}_{sensor.Key}",
device = new
{
identifiers = new[] { deviceid },
manufacturer = "Custom",
model = "PC Monitor",
name = deviceid.ToUpper(),
sw_version = "1.0"
},
state_topic = $"{baseTopic}{sensor.Key}/state",
unit_of_measurement = sensor.Value.Unit,
icon = sensor.Value.Icon
};
await _mqttService.PublishAsync(configTopic, JsonConvert.SerializeObject(payload));
Log.Debug($"Published auto-discovery config for {sensor.Key}");
}
}
private async Task PublishMetrics()
{
_pcMetrics = PCMetrics.Instance;
if (_pcMetrics == null) return;
var baseTopic = $"homeassistant/sensor/{deviceid}/";
var metrics = new Dictionary<string, object>
{
{"cpu_usage", _pcMetrics.CpuUsage},
// Add other metrics here as needed
{"total_ram", _pcMetrics.TotalRam},
{"free_ram", _pcMetrics.FreeRam},
{"used_ram", _pcMetrics.UsedRam}
};
foreach (var metric in metrics)
{
var stateTopic = $"{baseTopic}{metric.Key}/state";
// Format the value as a string with two decimal places
var payload = string.Format("{0:F2}", metric.Value);
await _mqttService.PublishAsync(stateTopic, payload);
}
}
private async void SaveSettings_Click(object sender, RoutedEventArgs e)
{
Log.Debug("SaveSettings_Click: Save Settings Clicked" + _settings.ToString());
await SaveSettingsAsync();
}
private void ToggleThemeButton_Click(object sender, RoutedEventArgs e)
{
// Toggle the theme
isDarkTheme = !isDarkTheme;
_settings.Theme = isDarkTheme ? "Dark" : "Light";
ApplyTheme(_settings.Theme);
// Save settings after changing the theme
_ = SaveSettingsAsync();
}
private async Task SaveSettingsAsync()
{
// Get the current settings from the singleton instance
var settings = AppSettings.Instance;
// Temporary storage for old values to compare after updating
var oldMqttAddress = settings.MqttAddress;
var oldMqttPort = settings.MqttPort;
var oldMqttUsername = settings.MqttUsername;
var oldMqttPassword = settings.MqttPassword;
var oldUseTLS = settings.UseTLS;
var oldIgnoreCertificateErrors = settings.IgnoreCertificateErrors;
var oldUseWebsockets = settings.UseWebsockets;
var oldSensorPrefix = settings.SensorPrefix;
var oldUseSafeCommands = settings.UseSafeCommands;
// Update the settings from UI components
Dispatcher.Invoke(() =>
{
settings.MqttAddress = MqttAddress.Text;
settings.MqttPort = MqttPort.Text;
settings.MqttUsername = MqttUserNameBox.Text;
settings.MqttPassword = MQTTPasswordBox.Password;
settings.UseTLS = UseTLS.IsChecked ?? false;
settings.IgnoreCertificateErrors = IgnoreCert.IsChecked ?? false;
settings.RunMinimized = RunMinimisedCheckBox.IsChecked ?? false;
settings.UseWebsockets = Websockets.IsChecked ?? false;
settings.RunAtWindowsBoot = RunAtWindowsBootCheckBox.IsChecked ?? false;
settings.SensorPrefix = string.IsNullOrEmpty(SensorPrefixBox.Text) ? System.Environment.MachineName : SensorPrefixBox.Text;
settings.UseSafeCommands = SafePowerCheckBox.IsChecked ?? false;
});
// Now check if MQTT settings have changed
bool mqttSettingsChanged = (oldMqttAddress != settings.MqttAddress) ||
(oldMqttPort != settings.MqttPort) ||
(oldMqttUsername != settings.MqttUsername) ||
(oldMqttPassword != settings.MqttPassword) ||
(oldUseTLS != settings.UseTLS) ||
(oldIgnoreCertificateErrors != settings.IgnoreCertificateErrors) ||
(oldUseWebsockets != settings.UseWebsockets);
bool sensorPrefixChanged = (oldSensorPrefix != settings.SensorPrefix);
// Save the updated settings to file
settings.SaveSettingsToFile();
if (mqttSettingsChanged || sensorPrefixChanged)
{
restartMqtt();
}
}
private async void restartMqtt()
{
Log.Debug("SaveSettingsAsync: MQTT settings have changed. Reconnecting MQTT client...");
_mqttService.MessageReceived -= OnMessageReceivedAsync;
_mqttService.StatusMessageReceived -= UpdateMqttStatus;
_mqttService.ConnectionStatusChanged -= MqttManager_ConnectionStatusChanged;
await MqttService.Instance.ReinitializeAsync(_settings, "PC2MQTT");
_mqttService = MqttService.Instance;
SetupMqttEventHandlers();
}
private void SetupMqttEventHandlers()
{
_mqttService.MessageReceived += OnMessageReceivedAsync;
_mqttService.StatusMessageReceived += UpdateMqttStatus;
_mqttService.ConnectionStatusChanged += MqttManager_ConnectionStatusChanged;
Log.Information("MQTT event handlers set up.");
}
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
//LoadSettings();
ComputerInfo computerInfo = new ComputerInfo();
TotalPhysicalMemory = computerInfo.TotalPhysicalMemory / (1024.0 * 1024 * 1024); // Convert from bytes to gigabytes
await Task.Run(() => InitializePerformanceCounters()); // Move heavy lifting off the UI thread.
InitializeTimer();
RunAtWindowsBootCheckBox.IsChecked = _settings.RunAtWindowsBoot;
RunMinimisedCheckBox.IsChecked = _settings.RunMinimized;
MqttUserNameBox.Text = _settings.MqttUsername;
UseTLS.IsChecked = _settings.UseTLS;
Websockets.IsChecked = _settings.UseWebsockets;
IgnoreCert.IsChecked = _settings.IgnoreCertificateErrors;
MQTTPasswordBox.Password = _settings.MqttPassword;
MqttAddress.Text = _settings.MqttAddress;
SafePowerCheckBox.IsChecked = _settings.UseSafeCommands;
// Added to set the sensor prefix
if (string.IsNullOrEmpty(_settings.SensorPrefix))
{
SensorPrefixBox.Text = System.Environment.MachineName;
}
else
{
SensorPrefixBox.Text = _settings.SensorPrefix;
}
SensorPrefixBox.Text = _settings.SensorPrefix;
MqttPort.Text = _settings.MqttPort;
ApplyTheme(_settings.Theme);
if (RunMinimisedCheckBox.IsChecked == true)
{// Start the window minimized and hide it
this.WindowState = WindowState.Minimized;
this.Hide();
MyNotifyIcon.Visibility = Visibility.Visible; // Show the NotifyIcon in the system tray
}
Dispatcher.Invoke(() => UpdateStatusMenuItems());
ShowOneTimeNoticeIfNeeded();
}
private void ShowOneTimeNoticeIfNeeded()
{
// Check if the one-time notice has already been shown
if (!_settings.HasShownOneTimeNotice)
{
// Show the notice to the user
System.Windows.MessageBox.Show("Important: Due to recent updates, the functionality of PC2MQTT has changed. Sensors are now Binarysensors - please make sure you update any automations etc that rely on the sensors.", "Notice", MessageBoxButton.OK, MessageBoxImage.Information);
// Update the setting so that the notice isn't shown again
_settings.HasShownOneTimeNotice = true;
// Save the updated settings to file
_settings.SaveSettingsToFile();
}
}
}
}