From ebae183f3afada176add65b9a026194a2038dffd Mon Sep 17 00:00:00 2001 From: sleevezipper Date: Sat, 16 Jan 2021 23:15:27 +0100 Subject: [PATCH] implement more commands, use will messages to turn entities unavailable --- README.md | 18 +++++++- UserInterface/Views/AddCommandDialog.axaml | 2 +- UserInterface/Views/AddCommandDialog.axaml.cs | 15 +++++++ UserInterface/Views/CommandSettings.axaml | 2 +- .../InterProcessApi.cs | 9 ++++ .../ServiceContractModels.cs | 5 ++- .../Communication/MQTT/MqttPublisher.cs | 20 ++++----- .../MQTT/SensorDiscoveryConfigModel.cs | 6 +-- .../Data/ConfigurationService.cs | 29 +++++++++--- .../Domain/Commands/AbstractCommand.cs | 5 ++- .../Domain/Commands/CustomCommand.cs | 45 +++++++++++++++---- .../Domain/Commands/LogOffCommand.cs | 17 +++++++ .../Domain/Commands/RestartCommand.cs | 17 +++++++ .../Domain/Commands/ShutdownCommand.cs | 17 +++++++ .../Domain/Sensors/ActiveWindowSensor.cs | 3 +- .../Domain/Sensors/CPULoadSensor.cs | 3 +- .../Domain/Sensors/CurrentClockSpeedSensor.cs | 3 +- .../Domain/Sensors/DummySensor.cs | 3 +- .../Domain/Sensors/LastActiveSensor.cs | 3 +- .../Domain/Sensors/LastBootSensor.cs | 3 +- .../Domain/Sensors/MemoryUsageSensor.cs | 3 +- .../Domain/Sensors/MicrophoneActiveSensor.cs | 3 +- .../Domain/Sensors/NamedWindowSensor.cs | 3 +- .../Domain/Sensors/SessionStateSensor.cs | 3 +- .../Sensors/UserNotificationStateSensor.cs | 3 +- .../Domain/Sensors/WMIQuerySensor.cs | 3 +- .../Domain/Sensors/WebcamActiveSensor.cs | 3 +- hass-workstation-service/Program.cs | 3 +- hass-workstation-service/Worker.cs | 16 +++++-- 29 files changed, 196 insertions(+), 69 deletions(-) create mode 100644 hass-workstation-service/Domain/Commands/LogOffCommand.cs create mode 100644 hass-workstation-service/Domain/Commands/RestartCommand.cs create mode 100644 hass-workstation-service/Domain/Commands/ShutdownCommand.cs diff --git a/README.md b/README.md index cba50fc..bde5317 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,19 @@ This sensor spits out a random number every second. Useful for testing, maybe yo ## Commands -Commands can be used to trigger certain things on the client. +Commands can be used to trigger certain things on the client. For each command, a switch will be available in Home Assistant. Turning on the switch fires the command on the client and it will turn the switch off when it's done. Turning it off will cancel thje running command. + +### ShutdownCommand + +This command shuts down the computer immediately. It runs `shutdown /s`. + +### RestartCommand + +This command restarts the computer immediately. It runs `shutdown /r`. + +### LogOffCommand + +This command logs off the current user. It runs `shutdown /l`. ### CustomCommand @@ -135,4 +147,6 @@ This command allows you to run any Windows Commands. The command will be run in |Command|Explanation| |---|---| -|Rundll32.exe user32.dll,LockWorkStation|This locks the current session.| \ No newline at end of file +|Rundll32.exe user32.dll,LockWorkStation|This locks the current session.| +|shutdown /s /t 300|Shuts the PC down after 5 minutes (300 seconds).| +|C:\path\to\your\batchfile.bat|Run the specified batch file.| diff --git a/UserInterface/Views/AddCommandDialog.axaml b/UserInterface/Views/AddCommandDialog.axaml index f359fc5..0ea8d9f 100644 --- a/UserInterface/Views/AddCommandDialog.axaml +++ b/UserInterface/Views/AddCommandDialog.axaml @@ -20,7 +20,7 @@ Command - + diff --git a/UserInterface/Views/AddCommandDialog.axaml.cs b/UserInterface/Views/AddCommandDialog.axaml.cs index 9db4d7b..f0499b5 100644 --- a/UserInterface/Views/AddCommandDialog.axaml.cs +++ b/UserInterface/Views/AddCommandDialog.axaml.cs @@ -63,6 +63,21 @@ namespace UserInterface.Views item.MoreInfoLink = "https://github.com/sleevezipper/hass-workstation-service#customcommand"; item.ShowCommandInput = true; break; + case AvailableCommands.ShutdownCommand: + item.Description = "This command shuts down the PC immediately. "; + item.MoreInfoLink = "https://github.com/sleevezipper/hass-workstation-service#shutdowncommand"; + item.ShowCommandInput = false; + break; + case AvailableCommands.RestartCommand: + item.Description = "This command restarts the PC immediately. "; + item.MoreInfoLink = "https://github.com/sleevezipper/hass-workstation-service#restartcommand"; + item.ShowCommandInput = false; + break; + case AvailableCommands.LogOffCommand: + item.Description = "This command logs the current user off immediately. "; + item.MoreInfoLink = "https://github.com/sleevezipper/hass-workstation-service#logoffcommand"; + item.ShowCommandInput = false; + break; default: item.Description = null; item.MoreInfoLink = null; diff --git a/UserInterface/Views/CommandSettings.axaml b/UserInterface/Views/CommandSettings.axaml index 587d109..efc93f0 100644 --- a/UserInterface/Views/CommandSettings.axaml +++ b/UserInterface/Views/CommandSettings.axaml @@ -18,7 +18,7 @@ Width="1*" /> - Add some commands by clicking the "Add" button. + Add some commands by clicking the "Add" button. diff --git a/hass-workstation-service/Communication/InterProcesCommunication/InterProcessApi.cs b/hass-workstation-service/Communication/InterProcesCommunication/InterProcessApi.cs index da03e81..95c4a6b 100644 --- a/hass-workstation-service/Communication/InterProcesCommunication/InterProcessApi.cs +++ b/hass-workstation-service/Communication/InterProcesCommunication/InterProcessApi.cs @@ -173,6 +173,15 @@ namespace hass_workstation_service.Communication.InterProcesCommunication AbstractCommand commandToCreate = null; switch (commandType) { + case AvailableCommands.ShutdownCommand: + commandToCreate = new ShutdownCommand(this._publisher, model.Name); + break; + case AvailableCommands.RestartCommand: + commandToCreate = new RestartCommand(this._publisher, model.Name); + break; + case AvailableCommands.LogOffCommand: + commandToCreate = new LogOffCommand(this._publisher, model.Name); + break; case AvailableCommands.CustomCommand: commandToCreate = new CustomCommand(this._publisher, model.Command, model.Name); break; diff --git a/hass-workstation-service/Communication/InterProcesCommunication/ServiceContractModels.cs b/hass-workstation-service/Communication/InterProcesCommunication/ServiceContractModels.cs index 175ba8c..9f7481a 100644 --- a/hass-workstation-service/Communication/InterProcesCommunication/ServiceContractModels.cs +++ b/hass-workstation-service/Communication/InterProcesCommunication/ServiceContractModels.cs @@ -55,6 +55,9 @@ namespace hass_workstation_service.Communication.InterProcesCommunication.Models public enum AvailableCommands { - CustomCommand + CustomCommand, + ShutdownCommand, + LogOffCommand, + RestartCommand, } } diff --git a/hass-workstation-service/Communication/MQTT/MqttPublisher.cs b/hass-workstation-service/Communication/MQTT/MqttPublisher.cs index 37e32ae..ebd7b93 100644 --- a/hass-workstation-service/Communication/MQTT/MqttPublisher.cs +++ b/hass-workstation-service/Communication/MQTT/MqttPublisher.cs @@ -61,6 +61,7 @@ namespace hass_workstation_service.Communication if (options != null) { + options.WillMessage.Topic = $"homeassistant/sensor/{this.DeviceConfigModel.Name}/availability"; this._mqttClient.ConnectAsync(options); this._mqttClientMessage = "Connecting..."; } @@ -72,7 +73,6 @@ namespace hass_workstation_service.Communication this._mqttClient.UseConnectedHandler(e => { this._mqttClientMessage = "All good"; }); - this._mqttClient.UseApplicationMessageReceivedHandler(e => this.HandleMessageReceived(e.ApplicationMessage)); // configure what happens on disconnect @@ -93,7 +93,6 @@ namespace hass_workstation_service.Communication _logger.LogError(ex, "Reconnecting failed"); } } - }); } @@ -211,16 +210,17 @@ namespace hass_workstation_service.Communication { if (command.GetAutoDiscoveryConfig().Command_topic == applicationMessage.Topic) { - command.Execute(); + if (Encoding.UTF8.GetString(applicationMessage?.Payload) == "ON") + { + command.TurnOn(); + } + else if (Encoding.UTF8.GetString(applicationMessage?.Payload) == "OFF") + { + command.TurnOff(); + } + } } - Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###"); - Console.WriteLine($"+ Topic = {applicationMessage.Topic}"); - - Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(applicationMessage?.Payload)}"); - Console.WriteLine($"+ QoS = {applicationMessage.QualityOfServiceLevel}"); - Console.WriteLine($"+ Retain = {applicationMessage.Retain}"); - Console.WriteLine(); } } } diff --git a/hass-workstation-service/Communication/MQTT/SensorDiscoveryConfigModel.cs b/hass-workstation-service/Communication/MQTT/SensorDiscoveryConfigModel.cs index a67f6b6..1c5218d 100644 --- a/hass-workstation-service/Communication/MQTT/SensorDiscoveryConfigModel.cs +++ b/hass-workstation-service/Communication/MQTT/SensorDiscoveryConfigModel.cs @@ -109,11 +109,7 @@ namespace hass_workstation_service.Communication /// /// public string Device_class { get; set; } - /// - /// (Optional) Defines the number of seconds after the sensor’s state expires, if it’s not updated. After expiry, the sensor’s state becomes unavailable. Defaults to 0 in hass. - /// - /// - public int? Expire_after { get; set; } + /// /// Sends update events even if the value hasn’t changed. Useful if you want to have meaningful value graphs in history. /// diff --git a/hass-workstation-service/Data/ConfigurationService.cs b/hass-workstation-service/Data/ConfigurationService.cs index f130014..aa50dd3 100644 --- a/hass-workstation-service/Data/ConfigurationService.cs +++ b/hass-workstation-service/Data/ConfigurationService.cs @@ -26,6 +26,7 @@ namespace hass_workstation_service.Data public ICollection ConfiguredSensors { get; private set; } public ICollection ConfiguredCommands { get; private set; } public Action MqqtConfigChangedHandler { get; set; } + private readonly DeviceConfigModel _deviceConfigModel; private bool BrokerSettingsFileLocked { get; set; } private bool SensorsSettingsFileLocked { get; set; } @@ -33,8 +34,9 @@ namespace hass_workstation_service.Data private readonly string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Hass Workstation Service"); - public ConfigurationService() + public ConfigurationService(DeviceConfigModel deviceConfigModel) { + this._deviceConfigModel = deviceConfigModel; if (!File.Exists(Path.Combine(path, "mqttbroker.json"))) { File.Create(Path.Combine(path, "mqttbroker.json")).Close(); @@ -156,6 +158,15 @@ namespace hass_workstation_service.Data AbstractCommand command = null; switch (configuredCommand.Type) { + case "ShutdownCommand": + command = new ShutdownCommand(publisher, configuredCommand.Name, configuredCommand.Id); + break; + case "RestartCommand": + command = new RestartCommand(publisher, configuredCommand.Name, configuredCommand.Id); + break; + case "LogOffCommand": + command = new LogOffCommand(publisher, configuredCommand.Name, configuredCommand.Id); + break; case "CustomCommand": command = new CustomCommand(publisher, configuredCommand.Command, configuredCommand.Name, configuredCommand.Id); break; @@ -184,6 +195,12 @@ namespace hass_workstation_service.Data AllowUntrustedCertificates = true }) .WithCredentials(configuredBroker.Username, configuredBroker.Password.ToString()) + .WithKeepAlivePeriod(TimeSpan.FromSeconds(30)) + .WithWillMessage(new MqttApplicationMessageBuilder() + .WithRetainFlag() + .WithTopic($"homeassistant/sensor/{_deviceConfigModel.Name}/availability") + .WithPayload("offline") + .Build()) .Build(); return mqttClientOptions; } @@ -315,12 +332,12 @@ namespace hass_workstation_service.Data public async void DeleteConfiguredCommand(Guid id) { - var sensorToRemove = this.ConfiguredCommands.FirstOrDefault(s => s.Id == id); - if (sensorToRemove != null) + var commandToRemove = this.ConfiguredCommands.FirstOrDefault(s => s.Id == id); + if (commandToRemove != null) { - await sensorToRemove.UnPublishAutoDiscoveryConfigAsync(); - this.ConfiguredCommands.Remove(sensorToRemove); - WriteSensorSettingsAsync(); + await commandToRemove.UnPublishAutoDiscoveryConfigAsync(); + this.ConfiguredCommands.Remove(commandToRemove); + WriteCommandSettingsAsync(); } else { diff --git a/hass-workstation-service/Domain/Commands/AbstractCommand.cs b/hass-workstation-service/Domain/Commands/AbstractCommand.cs index 7e29b98..b1b30e6 100644 --- a/hass-workstation-service/Domain/Commands/AbstractCommand.cs +++ b/hass-workstation-service/Domain/Commands/AbstractCommand.cs @@ -13,7 +13,7 @@ namespace hass_workstation_service.Domain.Commands /// /// The update interval in seconds. It checks state only if the interval has passed. /// - public int UpdateInterval { get; protected set; } + public int UpdateInterval { get => 1; } public DateTime? LastUpdated { get; protected set; } public string PreviousPublishedState { get; protected set; } public MqttPublisher Publisher { get; protected set; } @@ -74,6 +74,7 @@ namespace hass_workstation_service.Domain.Commands { await this.Publisher.AnnounceAutoDiscoveryConfig(this.GetAutoDiscoveryConfig(), this.Domain, true); } - public abstract void Execute(); + public abstract void TurnOn(); + public abstract void TurnOff(); } } \ No newline at end of file diff --git a/hass-workstation-service/Domain/Commands/CustomCommand.cs b/hass-workstation-service/Domain/Commands/CustomCommand.cs index aff15ec..6a62b53 100644 --- a/hass-workstation-service/Domain/Commands/CustomCommand.cs +++ b/hass-workstation-service/Domain/Commands/CustomCommand.cs @@ -1,6 +1,8 @@ using hass_workstation_service.Communication; +using Serilog; using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -10,39 +12,64 @@ namespace hass_workstation_service.Domain.Commands public class CustomCommand : AbstractCommand { public string Command { get; protected set; } + public string State { get; protected set; } + public Process Process { get; private set; } public CustomCommand(MqttPublisher publisher, string command, string name = "Custom", Guid id = default(Guid)) : base(publisher, name ?? "Custom", id) { this.Command = command; + this.State = "OFF"; } - public override void Execute() + public override async void TurnOn() { - System.Diagnostics.Process process = new System.Diagnostics.Process(); - System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); - startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; + this.State = "ON"; + this.Process = new Process(); + ProcessStartInfo startInfo = new ProcessStartInfo(); + startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.CreateNoWindow = true; startInfo.FileName = "cmd.exe"; startInfo.Arguments = $"/C {this.Command}"; - process.StartInfo = startInfo; - process.Start(); + this.Process.StartInfo = startInfo; + try + { + this.Process.Start(); + } + catch (Exception e) + { + Log.Logger.Error($"Sensor {this.Name} failed", e); + this.State = "FAILED"; + } + + while (!this.Process.HasExited) + { + await Task.Delay(1000); + } + this.State = "OFF"; } + + public override CommandDiscoveryConfigModel GetAutoDiscoveryConfig() { return new CommandDiscoveryConfigModel() { Name = this.Name, Unique_id = this.Id.ToString(), - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", + Availability_topic = $"homeassistant/sensor/{Publisher.DeviceConfigModel.Name}/availability", Command_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/set", + State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Device = this.Publisher.DeviceConfigModel, - Expire_after = 60 }; } public override string GetState() { - return "off"; + return this.State; + } + + public override void TurnOff() + { + this.Process.Kill(); } } } diff --git a/hass-workstation-service/Domain/Commands/LogOffCommand.cs b/hass-workstation-service/Domain/Commands/LogOffCommand.cs new file mode 100644 index 0000000..921393e --- /dev/null +++ b/hass-workstation-service/Domain/Commands/LogOffCommand.cs @@ -0,0 +1,17 @@ +using hass_workstation_service.Communication; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace hass_workstation_service.Domain.Commands +{ + public class LogOffCommand : CustomCommand + { + public LogOffCommand(MqttPublisher publisher, string name = "Shutdown", Guid id = default(Guid)) : base(publisher, "shutdown /l", name ?? "LogOff", id) + { + this.State = "OFF"; + } + } +} diff --git a/hass-workstation-service/Domain/Commands/RestartCommand.cs b/hass-workstation-service/Domain/Commands/RestartCommand.cs new file mode 100644 index 0000000..323b806 --- /dev/null +++ b/hass-workstation-service/Domain/Commands/RestartCommand.cs @@ -0,0 +1,17 @@ +using hass_workstation_service.Communication; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace hass_workstation_service.Domain.Commands +{ + public class RestartCommand : CustomCommand + { + public RestartCommand(MqttPublisher publisher, string name = "Shutdown", Guid id = default(Guid)) : base(publisher, "shutdown /r", name ?? "Restart", id) + { + this.State = "OFF"; + } + } +} diff --git a/hass-workstation-service/Domain/Commands/ShutdownCommand.cs b/hass-workstation-service/Domain/Commands/ShutdownCommand.cs new file mode 100644 index 0000000..7ef5211 --- /dev/null +++ b/hass-workstation-service/Domain/Commands/ShutdownCommand.cs @@ -0,0 +1,17 @@ +using hass_workstation_service.Communication; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace hass_workstation_service.Domain.Commands +{ + public class ShutdownCommand : CustomCommand + { + public ShutdownCommand(MqttPublisher publisher, string name = "Shutdown", Guid id = default(Guid)) : base(publisher, "shutdown /s", name ?? "Shutdown", id) + { + this.State = "OFF"; + } + } +} diff --git a/hass-workstation-service/Domain/Sensors/ActiveWindowSensor.cs b/hass-workstation-service/Domain/Sensors/ActiveWindowSensor.cs index 79cdcb3..b9fb58b 100644 --- a/hass-workstation-service/Domain/Sensors/ActiveWindowSensor.cs +++ b/hass-workstation-service/Domain/Sensors/ActiveWindowSensor.cs @@ -18,8 +18,7 @@ namespace hass_workstation_service.Domain.Sensors Device = this.Publisher.DeviceConfigModel, State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Icon = "mdi:window-maximize", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } diff --git a/hass-workstation-service/Domain/Sensors/CPULoadSensor.cs b/hass-workstation-service/Domain/Sensors/CPULoadSensor.cs index 21710fa..d84fe1f 100644 --- a/hass-workstation-service/Domain/Sensors/CPULoadSensor.cs +++ b/hass-workstation-service/Domain/Sensors/CPULoadSensor.cs @@ -27,8 +27,7 @@ namespace hass_workstation_service.Domain.Sensors State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Icon = "mdi:chart-areaspline", Unit_of_measurement = "%", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } diff --git a/hass-workstation-service/Domain/Sensors/CurrentClockSpeedSensor.cs b/hass-workstation-service/Domain/Sensors/CurrentClockSpeedSensor.cs index 5512d02..523fe30 100644 --- a/hass-workstation-service/Domain/Sensors/CurrentClockSpeedSensor.cs +++ b/hass-workstation-service/Domain/Sensors/CurrentClockSpeedSensor.cs @@ -19,8 +19,7 @@ namespace hass_workstation_service.Domain.Sensors State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Icon = "mdi:speedometer", Unit_of_measurement = "MHz", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } } diff --git a/hass-workstation-service/Domain/Sensors/DummySensor.cs b/hass-workstation-service/Domain/Sensors/DummySensor.cs index b63cee1..3431fb5 100644 --- a/hass-workstation-service/Domain/Sensors/DummySensor.cs +++ b/hass-workstation-service/Domain/Sensors/DummySensor.cs @@ -21,8 +21,7 @@ namespace hass_workstation_service.Domain.Sensors Unique_id = this.Id.ToString(), Device = this.Publisher.DeviceConfigModel, State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } diff --git a/hass-workstation-service/Domain/Sensors/LastActiveSensor.cs b/hass-workstation-service/Domain/Sensors/LastActiveSensor.cs index 07ef844..8bcfdc4 100644 --- a/hass-workstation-service/Domain/Sensors/LastActiveSensor.cs +++ b/hass-workstation-service/Domain/Sensors/LastActiveSensor.cs @@ -18,8 +18,7 @@ namespace hass_workstation_service.Domain.Sensors Device = this.Publisher.DeviceConfigModel, State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Icon = "mdi:clock-time-three-outline", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } diff --git a/hass-workstation-service/Domain/Sensors/LastBootSensor.cs b/hass-workstation-service/Domain/Sensors/LastBootSensor.cs index bda0e89..963e858 100644 --- a/hass-workstation-service/Domain/Sensors/LastBootSensor.cs +++ b/hass-workstation-service/Domain/Sensors/LastBootSensor.cs @@ -22,8 +22,7 @@ namespace hass_workstation_service.Domain.Sensors Device = this.Publisher.DeviceConfigModel, State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Icon = "mdi:clock-time-three-outline", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } diff --git a/hass-workstation-service/Domain/Sensors/MemoryUsageSensor.cs b/hass-workstation-service/Domain/Sensors/MemoryUsageSensor.cs index 998369f..6893d0a 100644 --- a/hass-workstation-service/Domain/Sensors/MemoryUsageSensor.cs +++ b/hass-workstation-service/Domain/Sensors/MemoryUsageSensor.cs @@ -44,8 +44,7 @@ namespace hass_workstation_service.Domain.Sensors State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Icon = "mdi:memory", Unit_of_measurement = "%", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } } diff --git a/hass-workstation-service/Domain/Sensors/MicrophoneActiveSensor.cs b/hass-workstation-service/Domain/Sensors/MicrophoneActiveSensor.cs index 7e78826..8a6a246 100644 --- a/hass-workstation-service/Domain/Sensors/MicrophoneActiveSensor.cs +++ b/hass-workstation-service/Domain/Sensors/MicrophoneActiveSensor.cs @@ -30,8 +30,7 @@ namespace hass_workstation_service.Domain.Sensors Device = this.Publisher.DeviceConfigModel, State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Icon = "mdi:microphone", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } diff --git a/hass-workstation-service/Domain/Sensors/NamedWindowSensor.cs b/hass-workstation-service/Domain/Sensors/NamedWindowSensor.cs index a852bf0..1a5dc64 100644 --- a/hass-workstation-service/Domain/Sensors/NamedWindowSensor.cs +++ b/hass-workstation-service/Domain/Sensors/NamedWindowSensor.cs @@ -25,8 +25,7 @@ namespace hass_workstation_service.Domain.Sensors Device = this.Publisher.DeviceConfigModel, State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Icon = "mdi:window-maximize", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } diff --git a/hass-workstation-service/Domain/Sensors/SessionStateSensor.cs b/hass-workstation-service/Domain/Sensors/SessionStateSensor.cs index 02efbc5..d043a76 100644 --- a/hass-workstation-service/Domain/Sensors/SessionStateSensor.cs +++ b/hass-workstation-service/Domain/Sensors/SessionStateSensor.cs @@ -44,8 +44,7 @@ namespace hass_workstation_service.Domain.Sensors Device = this.Publisher.DeviceConfigModel, State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Icon = "mdi:lock", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } diff --git a/hass-workstation-service/Domain/Sensors/UserNotificationStateSensor.cs b/hass-workstation-service/Domain/Sensors/UserNotificationStateSensor.cs index e566be6..793df7e 100644 --- a/hass-workstation-service/Domain/Sensors/UserNotificationStateSensor.cs +++ b/hass-workstation-service/Domain/Sensors/UserNotificationStateSensor.cs @@ -18,8 +18,7 @@ namespace hass_workstation_service.Domain.Sensors Device = this.Publisher.DeviceConfigModel, State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Icon = "mdi:laptop", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } diff --git a/hass-workstation-service/Domain/Sensors/WMIQuerySensor.cs b/hass-workstation-service/Domain/Sensors/WMIQuerySensor.cs index 1c2ff62..6304389 100644 --- a/hass-workstation-service/Domain/Sensors/WMIQuerySensor.cs +++ b/hass-workstation-service/Domain/Sensors/WMIQuerySensor.cs @@ -28,8 +28,7 @@ namespace hass_workstation_service.Domain.Sensors Unique_id = this.Id.ToString(), Device = this.Publisher.DeviceConfigModel, State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } diff --git a/hass-workstation-service/Domain/Sensors/WebcamActiveSensor.cs b/hass-workstation-service/Domain/Sensors/WebcamActiveSensor.cs index fc08ba3..205e467 100644 --- a/hass-workstation-service/Domain/Sensors/WebcamActiveSensor.cs +++ b/hass-workstation-service/Domain/Sensors/WebcamActiveSensor.cs @@ -32,8 +32,7 @@ namespace hass_workstation_service.Domain.Sensors Device = this.Publisher.DeviceConfigModel, State_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/{this.Name}/state", Icon = "mdi:webcam", - Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability", - Expire_after = 60 + Availability_topic = $"homeassistant/{this.Domain}/{Publisher.DeviceConfigModel.Name}/availability" }); } diff --git a/hass-workstation-service/Program.cs b/hass-workstation-service/Program.cs index 61f597d..d720614 100644 --- a/hass-workstation-service/Program.cs +++ b/hass-workstation-service/Program.cs @@ -67,11 +67,10 @@ namespace hass_workstation_service Log.CloseAndFlush(); } } - - } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureLogging((hostContext, loggingBuilder) => loggingBuilder.AddSerilog(dispose: true)) .ConfigureServices((hostContext, services) => diff --git a/hass-workstation-service/Worker.cs b/hass-workstation-service/Worker.cs index e91a9ca..dbbc448 100644 --- a/hass-workstation-service/Worker.cs +++ b/hass-workstation-service/Worker.cs @@ -44,7 +44,6 @@ namespace hass_workstation_service List sensors = _configurationService.ConfiguredSensors.ToList(); List commands = _configurationService.ConfiguredCommands.ToList(); _mqttPublisher.AnnounceAvailability("sensor"); - _mqttPublisher.AnnounceAvailability("switch"); foreach (AbstractSensor sensor in sensors) { sensor.PublishAutoDiscoveryConfigAsync(); @@ -55,7 +54,6 @@ namespace hass_workstation_service } while (!stoppingToken.IsCancellationRequested) { - sensors = _configurationService.ConfiguredSensors.ToList(); _logger.LogDebug("Worker running at: {time}", DateTimeOffset.Now); foreach (AbstractSensor sensor in sensors) @@ -69,6 +67,18 @@ namespace hass_workstation_service Log.Logger.Warning("Sensor failed: " + sensor.Name, ex); } + } + foreach (AbstractCommand command in commands) + { + try + { + await command.PublishStateAsync(); + } + catch (Exception ex) + { + Log.Logger.Warning("Command state failed: " + command.Name, ex); + } + } // announce autodiscovery every 30 seconds if (_mqttPublisher.LastConfigAnnounce < DateTime.UtcNow.AddSeconds(-30)) @@ -82,7 +92,6 @@ namespace hass_workstation_service command.PublishAutoDiscoveryConfigAsync(); } _mqttPublisher.AnnounceAvailability("sensor"); - _mqttPublisher.AnnounceAvailability("switch"); } await Task.Delay(1000, stoppingToken); } @@ -92,7 +101,6 @@ namespace hass_workstation_service public override async Task StopAsync(CancellationToken stoppingToken) { _mqttPublisher.AnnounceAvailability("sensor", true); - _mqttPublisher.AnnounceAvailability("switch", true); await _mqttPublisher.DisconnectAsync(); }