fix config corrution issue, unpublish autoconfig on sensor delete

pull/9/head
sleevezipper 4 years ago
parent db89b725de
commit de8c04f1cd

@ -7,6 +7,7 @@ using hass_workstation_service.Communication.Util;
using hass_workstation_service.Data; using hass_workstation_service.Data;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using MQTTnet; using MQTTnet;
using MQTTnet.Adapter;
using MQTTnet.Client; using MQTTnet.Client;
using MQTTnet.Client.Options; using MQTTnet.Client.Options;
using Serilog; using Serilog;
@ -101,7 +102,7 @@ namespace hass_workstation_service.Communication
} }
} }
public async Task PublishAutoDiscoveryConfig(AutoDiscoveryConfigModel config, bool clearPreviousConfig = false) public async Task AnnounceAutoDiscoveryConfig(AutoDiscoveryConfigModel config, bool clearConfig = false)
{ {
if (this._mqttClient.IsConnected) if (this._mqttClient.IsConnected)
{ {
@ -113,7 +114,7 @@ namespace hass_workstation_service.Communication
}; };
var message = new MqttApplicationMessageBuilder() var message = new MqttApplicationMessageBuilder()
.WithTopic($"homeassistant/sensor/{config.Name}/config") .WithTopic($"homeassistant/sensor/{config.Name}/config")
.WithPayload(clearPreviousConfig ? "" : JsonSerializer.Serialize(config, options)) .WithPayload(clearConfig ? "" : JsonSerializer.Serialize(config, options))
.WithRetainFlag() .WithRetainFlag()
.Build(); .Build();
await this.Publish(message); await this.Publish(message);
@ -129,10 +130,10 @@ namespace hass_workstation_service.Communication
{ {
await _mqttClient.ConnectAsync(options); await _mqttClient.ConnectAsync(options);
} }
catch (Exception ex) catch (MqttConnectingFailedException ex)
{ {
this._mqttClientMessage = ex.Message; this._mqttClientMessage = ex.ResultCode.ToString();
Log.Logger.Error("Could not connect to broker: " + ex.Message); Log.Logger.Error("Could not connect to broker: " + ex.ResultCode.ToString());
} }
} }

@ -24,6 +24,9 @@ namespace hass_workstation_service.Data
public ICollection<AbstractSensor> ConfiguredSensors { get; private set; } public ICollection<AbstractSensor> ConfiguredSensors { get; private set; }
public Action<IMqttClientOptions> MqqtConfigChangedHandler { get; set; } public Action<IMqttClientOptions> MqqtConfigChangedHandler { get; set; }
public bool _brokerSettingsFileLocked { get; set; }
public bool _sensorsSettingsFileLocked { get; set; }
private readonly IsolatedStorageFile _fileStorage; private readonly IsolatedStorageFile _fileStorage;
public ConfigurationService() public ConfigurationService()
@ -31,18 +34,35 @@ namespace hass_workstation_service.Data
this._fileStorage = IsolatedStorageFile.GetUserStoreForApplication(); this._fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
ConfiguredSensors = new List<AbstractSensor>(); ConfiguredSensors = new List<AbstractSensor>();
if (!this._fileStorage.FileExists("mqttbroker.json"))
{
this._fileStorage.CreateFile("mqttbroker.json");
}
if (!this._fileStorage.FileExists("configured-sensors.json"))
{
this._fileStorage.CreateFile("configured-sensors.json");
}
} }
public async void ReadSensorSettings(MqttPublisher publisher) public async void ReadSensorSettings(MqttPublisher publisher)
{ {
while (this._sensorsSettingsFileLocked)
{
await Task.Delay(500);
}
this._sensorsSettingsFileLocked = true;
List<ConfiguredSensor> sensors = new List<ConfiguredSensor>(); List<ConfiguredSensor> sensors = new List<ConfiguredSensor>();
using (var stream = this._fileStorage.OpenFile("configured-sensors.json", FileMode.OpenOrCreate)) using (var stream = this._fileStorage.OpenFile("configured-sensors.json", FileMode.Open))
{ {
Log.Logger.Information($"reading configured sensors from: {stream.Name}"); Log.Logger.Information($"reading configured sensors from: {stream.Name}");
if (stream.Length > 0) if (stream.Length > 0)
{ {
sensors = await JsonSerializer.DeserializeAsync<List<ConfiguredSensor>>(stream); sensors = await JsonSerializer.DeserializeAsync<List<ConfiguredSensor>>(stream);
} }
stream.Close();
this._sensorsSettingsFileLocked = false;
} }
foreach (ConfiguredSensor configuredSensor in sensors) foreach (ConfiguredSensor configuredSensor in sensors)
@ -89,24 +109,37 @@ namespace hass_workstation_service.Data
/// <returns></returns> /// <returns></returns>
public async Task<ConfiguredMqttBroker> ReadMqttSettingsAsync() public async Task<ConfiguredMqttBroker> ReadMqttSettingsAsync()
{ {
while (this._brokerSettingsFileLocked)
{
await Task.Delay(500);
}
this._brokerSettingsFileLocked = true;
ConfiguredMqttBroker configuredBroker = null; ConfiguredMqttBroker configuredBroker = null;
using (IsolatedStorageFileStream stream = this._fileStorage.OpenFile("mqttbroker.json", FileMode.OpenOrCreate)) using (IsolatedStorageFileStream stream = this._fileStorage.OpenFile("mqttbroker.json", FileMode.Open))
{ {
Log.Logger.Information($"reading configured mqttbroker from: {stream.Name}"); Log.Logger.Information($"reading configured mqttbroker from: {stream.Name}");
if (stream.Length > 0) if (stream.Length > 0)
{ {
configuredBroker = await JsonSerializer.DeserializeAsync<ConfiguredMqttBroker>(stream); configuredBroker = await JsonSerializer.DeserializeAsync<ConfiguredMqttBroker>(stream);
} }
stream.Close();
} }
this._brokerSettingsFileLocked = false;
return configuredBroker; return configuredBroker;
} }
public async void WriteSettingsAsync() public async void WriteSettingsAsync()
{ {
while (this._sensorsSettingsFileLocked)
{
await Task.Delay(500);
}
this._sensorsSettingsFileLocked = true;
List<ConfiguredSensor> configuredSensorsToSave = new List<ConfiguredSensor>(); List<ConfiguredSensor> configuredSensorsToSave = new List<ConfiguredSensor>();
using (IsolatedStorageFileStream stream = this._fileStorage.OpenFile("configured-sensors.json", FileMode.OpenOrCreate)) using (IsolatedStorageFileStream stream = this._fileStorage.OpenFile("configured-sensors.json", FileMode.Open))
{ {
stream.SetLength(0);
Log.Logger.Information($"writing configured sensors to: {stream.Name}"); Log.Logger.Information($"writing configured sensors to: {stream.Name}");
foreach (AbstractSensor sensor in this.ConfiguredSensors) foreach (AbstractSensor sensor in this.ConfiguredSensors)
{ {
@ -114,7 +147,9 @@ namespace hass_workstation_service.Data
} }
await JsonSerializer.SerializeAsync(stream, configuredSensorsToSave); await JsonSerializer.SerializeAsync(stream, configuredSensorsToSave);
stream.Close();
} }
this._sensorsSettingsFileLocked = false;
} }
public void AddConfiguredSensor(AbstractSensor sensor) public void AddConfiguredSensor(AbstractSensor sensor)
@ -123,9 +158,10 @@ namespace hass_workstation_service.Data
WriteSettingsAsync(); WriteSettingsAsync();
} }
public void DeleteConfiguredSensor(Guid id) public async void DeleteConfiguredSensor(Guid id)
{ {
var sensorToRemove = this.ConfiguredSensors.FirstOrDefault(s => s.Id == id); var sensorToRemove = this.ConfiguredSensors.FirstOrDefault(s => s.Id == id);
await sensorToRemove.UnPublishAutoDiscoveryConfigAsync();
this.ConfiguredSensors.Remove(sensorToRemove); this.ConfiguredSensors.Remove(sensorToRemove);
WriteSettingsAsync(); WriteSettingsAsync();
} }
@ -142,8 +178,14 @@ namespace hass_workstation_service.Data
/// <param name="settings"></param> /// <param name="settings"></param>
public async void WriteMqttBrokerSettingsAsync(MqttSettings settings) public async void WriteMqttBrokerSettingsAsync(MqttSettings settings)
{ {
using (IsolatedStorageFileStream stream = this._fileStorage.OpenFile("mqttbroker.json", FileMode.OpenOrCreate)) while (this._brokerSettingsFileLocked)
{
await Task.Delay(500);
}
this._brokerSettingsFileLocked = true;
using (IsolatedStorageFileStream stream = this._fileStorage.OpenFile("mqttbroker.json", FileMode.Open))
{ {
stream.SetLength(0);
Log.Logger.Information($"writing configured mqttbroker to: {stream.Name}"); Log.Logger.Information($"writing configured mqttbroker to: {stream.Name}");
ConfiguredMqttBroker configuredBroker = new ConfiguredMqttBroker() ConfiguredMqttBroker configuredBroker = new ConfiguredMqttBroker()
@ -154,8 +196,9 @@ namespace hass_workstation_service.Data
}; };
await JsonSerializer.SerializeAsync(stream, configuredBroker); await JsonSerializer.SerializeAsync(stream, configuredBroker);
stream.Close();
} }
this._brokerSettingsFileLocked = false;
this.MqqtConfigChangedHandler.Invoke(await this.GetMqttClientOptionsAsync()); this.MqqtConfigChangedHandler.Invoke(await this.GetMqttClientOptionsAsync());
} }

@ -41,7 +41,11 @@ namespace hass_workstation_service.Domain.Sensors
} }
public async Task PublishAutoDiscoveryConfigAsync() public async Task PublishAutoDiscoveryConfigAsync()
{ {
await this.Publisher.PublishAutoDiscoveryConfig(this.GetAutoDiscoveryConfig()); await this.Publisher.AnnounceAutoDiscoveryConfig(this.GetAutoDiscoveryConfig());
}
public async Task UnPublishAutoDiscoveryConfigAsync()
{
await this.Publisher.AnnounceAutoDiscoveryConfig(this.GetAutoDiscoveryConfig(), true);
} }
} }

Loading…
Cancel
Save