Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests - Expand single-statement guards and loops into braced blocks - Realign wrapped method arguments, chained calls and continuations - Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty` - Flatten the boiler config expression and reindent the remaining touched files
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -10,6 +12,8 @@ using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
@@ -108,6 +112,7 @@ public sealed class PowerMonitorInit
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error initializing PowerMonitor");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -129,17 +134,22 @@ public sealed class PowerMonitorInit
|
||||
if (string.IsNullOrWhiteSpace(_options.MainMeterEntityId))
|
||||
{
|
||||
_logger.LogWarning("MainMeterEntityId not configured, PowerMonitor will not react to power changes");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var meter = new Entity(_haContext, _options.MainMeterEntityId);
|
||||
meter.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State) return;
|
||||
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
meter.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
@@ -150,31 +160,33 @@ public sealed class PowerMonitorInit
|
||||
private void SubscribeToRediscoverButton()
|
||||
{
|
||||
var button = new Entity(_haContext, "button.powermonitor_rediscover_sensors");
|
||||
|
||||
button.StateChanges()
|
||||
.Subscribe(change =>
|
||||
{
|
||||
_logger.LogInformation("Re-discovery button pressed, scanning for power sensors");
|
||||
_ = HandleRediscoveryAsync();
|
||||
});
|
||||
.Subscribe(change =>
|
||||
{
|
||||
_logger.LogInformation("Re-discovery button pressed, scanning for power sensors");
|
||||
_ = HandleRediscoveryAsync();
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToLimitBreachDebugButton()
|
||||
{
|
||||
var button = new Entity(_haContext, "button.powermonitor_trigger_limit_breach");
|
||||
|
||||
button.StateChanges()
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
if (_enforcementService.IsLimitActive)
|
||||
{
|
||||
_logger.LogInformation("Limit breach debug button pressed while active, resetting breach");
|
||||
_enforcementService.ResetLimitBreach();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Limit breach debug button pressed, triggering fake breach");
|
||||
_enforcementService.TriggerLimitBreach();
|
||||
}
|
||||
});
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
if (_enforcementService.IsLimitActive)
|
||||
{
|
||||
_logger.LogInformation("Limit breach debug button pressed while active, resetting breach");
|
||||
_enforcementService.ResetLimitBreach();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Limit breach debug button pressed, triggering fake breach");
|
||||
_enforcementService.TriggerLimitBreach();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async Task HandleRediscoveryAsync()
|
||||
@@ -193,18 +205,22 @@ public sealed class PowerMonitorInit
|
||||
if (added.Count > 0)
|
||||
{
|
||||
await _entityService.CreateDeviceEntitiesAsync(added);
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Created entities for {Count} new sensors", added.Count);
|
||||
}
|
||||
}
|
||||
|
||||
if (removed.Count > 0) await RemoreDevicePriceEntities(removed);
|
||||
if (removed.Count > 0)
|
||||
{
|
||||
await RemoreDevicePriceEntities(removed);
|
||||
}
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)",
|
||||
newSensors.Count, added.Count, removed.Count);
|
||||
newSensors.Count, added.Count, removed.Count);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -229,11 +245,13 @@ public sealed class PowerMonitorInit
|
||||
try
|
||||
{
|
||||
var totalPower = ReadMainMeterPower();
|
||||
|
||||
if (totalPower is null)
|
||||
{
|
||||
_mainMeterConsecutiveFailures++;
|
||||
|
||||
_logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures,
|
||||
PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
|
||||
PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -251,8 +269,9 @@ public sealed class PowerMonitorInit
|
||||
var now = _timeProvider.GetLocalNow();
|
||||
|
||||
var elapsedSeconds = _lastPollTimestamp.HasValue
|
||||
? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10)
|
||||
: _options.PollIntervalSeconds;
|
||||
? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10)
|
||||
: _options.PollIntervalSeconds;
|
||||
|
||||
_lastPollTimestamp = now;
|
||||
|
||||
_costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime);
|
||||
@@ -261,18 +280,16 @@ public sealed class PowerMonitorInit
|
||||
|
||||
_anomalyStartTime = isAnomaly switch
|
||||
{
|
||||
true when _anomalyStartTime is null => now,
|
||||
false => null,
|
||||
_ => _anomalyStartTime
|
||||
true when _anomalyStartTime is null => now, false => null, _ => _anomalyStartTime
|
||||
};
|
||||
|
||||
var anomalyDuration = _anomalyStartTime.HasValue
|
||||
? now - _anomalyStartTime.Value
|
||||
: TimeSpan.Zero;
|
||||
? now - _anomalyStartTime.Value
|
||||
: TimeSpan.Zero;
|
||||
|
||||
var systemStatus = _mainMeterConsecutiveFailures >= PowerMonitorConsts.MainMeterMaxConsecutiveFailures
|
||||
? "warning"
|
||||
: "ok";
|
||||
? "warning"
|
||||
: "ok";
|
||||
|
||||
var context = new PowerUpdateContext
|
||||
{
|
||||
@@ -300,9 +317,9 @@ public sealed class PowerMonitorInit
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
|
||||
calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count,
|
||||
effectivePrice);
|
||||
"Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
|
||||
calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count,
|
||||
effectivePrice);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -318,10 +335,14 @@ public sealed class PowerMonitorInit
|
||||
if (state?.State is null or "unavailable" or "unknown")
|
||||
{
|
||||
_logger.LogDebug("NordPool price entity unavailable, using last known price");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0) return price;
|
||||
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0)
|
||||
{
|
||||
return price;
|
||||
}
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
@@ -340,11 +361,13 @@ public sealed class PowerMonitorInit
|
||||
case (true, false):
|
||||
_notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts);
|
||||
_highPowerNotificationActive = true;
|
||||
|
||||
break;
|
||||
|
||||
case (false, true):
|
||||
_notificationService.DismissHighPowerNotification();
|
||||
_highPowerNotificationActive = false;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -352,11 +375,15 @@ public sealed class PowerMonitorInit
|
||||
private double? ReadMainMeterPower()
|
||||
{
|
||||
var state = _haContext.GetState(_options.MainMeterEntityId);
|
||||
if (state?.State is null or "unavailable" or "unknown") return null;
|
||||
|
||||
if (state?.State is null or "unavailable" or "unknown")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)
|
||||
? value
|
||||
: null;
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
|
||||
private (IReadOnlyDictionary<string, double> readings, List<string> degraded) ReadDeviceSensors()
|
||||
@@ -367,19 +394,21 @@ public sealed class PowerMonitorInit
|
||||
foreach (var sensor in _discoveryService.CurrentDeviceSensors)
|
||||
{
|
||||
var state = _haContext.GetState(sensor.EntityId);
|
||||
|
||||
if (state?.State is null or "unavailable" or "unknown")
|
||||
{
|
||||
readings[sensor.EntityId] = 0;
|
||||
degraded.Add(sensor.EntityId);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var value))
|
||||
{
|
||||
var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit,
|
||||
StringComparison.OrdinalIgnoreCase)
|
||||
? value * PowerMonitorConsts.WattsPerKilowatt
|
||||
: value;
|
||||
StringComparison.OrdinalIgnoreCase)
|
||||
? value * PowerMonitorConsts.WattsPerKilowatt
|
||||
: value;
|
||||
|
||||
readings[sensor.EntityId] = powerWatts;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user