Skip to content

Commit

Permalink
Merge pull request #889 from pkuehnel/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
pkuehnel authored Sep 18, 2023
2 parents d0d9655 + 262a458 commit f72783f
Show file tree
Hide file tree
Showing 16 changed files with 118 additions and 58 deletions.
6 changes: 6 additions & 0 deletions Plugins.SmaEnergymeter/Controllers/CurrentPowerController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,11 @@ public int GetPower()
{
return _currentPowerService.GetCurrentPower();
}

[HttpGet]
public SharedValues GetAllValues()
{
return _currentPowerService.GetAllValues();
}
}
}
10 changes: 8 additions & 2 deletions Plugins.SmaEnergymeter/Services/CurrentPowerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ public CurrentPowerService(ILogger<CurrentPowerService> logger, SharedValues sha
public int GetCurrentPower()
{
_logger.LogTrace("{method}()", nameof(GetCurrentPower));
return _sharedValues.Overage;
return _sharedValues.OverageW;
}
}

public SharedValues GetAllValues()
{
_logger.LogTrace("{method}()", nameof(GetAllValues));
return _sharedValues;
}
}
28 changes: 22 additions & 6 deletions Plugins.SmaEnergymeter/Services/EnergyMeterService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,37 @@ public void StartLogging()
var relevantValues = byteArray.Skip(28).Take(byteArray.Length - 27).ToArray();
var obisValues = ConvertArrayToObisDictionary(relevantValues);

var currentSupply =
Convert.ToDecimal(obisValues.First(v => v.Id == 1 && v.ValueType == ValueMode.Average).Value / 10.0);
var currentOverage =
Convert.ToDecimal(obisValues.First(v => v.Id == 2 && v.ValueType == ValueMode.Average).Value / 10.0);
var currentSupply =
Convert.ToDecimal(obisValues.First(v => v.Id == 1 && v.ValueType == ValueMode.Average).Value / 10.0);


var totalEnergyToGrid = Convert.ToDecimal(obisValues.First(v => v.Id == 2 && v.ValueType == ValueMode.Counter).Value / 3600.0);
var totalEnergyFromGrid = Convert.ToDecimal(obisValues.First(v => v.Id == 1 && v.ValueType == ValueMode.Counter).Value / 3600.0);

_sharedValues.PowerFromGridW = (int) currentSupply;
_sharedValues.PowerToGridW = (int) currentOverage;

_sharedValues.TotalEnergyToGridWh = totalEnergyToGrid;
_sharedValues.TotalEnergyFromGridWh = totalEnergyFromGrid;

_sharedValues.LastValuesFrom = DateTime.UtcNow;

_logger.LogTrace("current overage: {currentOverage} W", currentOverage);
_logger.LogTrace("current supply: {currentSupply} W", currentSupply);

_logger.LogTrace("current supply: {currentSupply}", currentSupply);
_logger.LogTrace("current overage: {currentOverage}", currentOverage);
_logger.LogTrace("Total energy to grid: {totalEnergyToGrid} W", totalEnergyToGrid);
_logger.LogTrace("Total energy from grid: {totalEnergyFromGrid} W", totalEnergyFromGrid);


if (currentSupply > 0)
{
_sharedValues.Overage = (int)-currentSupply;
_sharedValues.OverageW = (int)-currentSupply;
}
else
{
_sharedValues.Overage = (int)currentOverage;
_sharedValues.OverageW = (int)currentOverage;
}
}
}
Expand Down
15 changes: 13 additions & 2 deletions Plugins.SmaEnergymeter/SharedValues.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,16 @@

public class SharedValues
{
public int Overage { get; set; }
}
public int OverageW { get; set; }

public int PowerToGridW { get; set; }
public int PowerFromGridW { get; set; }

public decimal TotalEnergyToGridWh { get; set; }
public decimal TotalEnergyFromGridWh { get; set; }

public decimal TotalEnergyToGridkWh => TotalEnergyToGridWh / 1000;
public decimal TotalEnergyFromGridkWh => TotalEnergyFromGridWh / 1000;

public DateTime LastValuesFrom { get; set; }
}
4 changes: 3 additions & 1 deletion Plugins.SolarEdge/Services/CurrentValuesService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,9 @@ private void AddCloudApiValueToSharedValues(CloudApiValue cloudApiValue)
return null;
}
//If there are already values there and there is no relevant car, call API everytime reset minutes are over.
if (_sharedValues.CloudApiValues.Count > 0 && numberOfRelevantCars < 1 && _sharedValues.CloudApiValues.MaxBy(v => v.Key).Key > DateTime.UtcNow - solarEdgeTooManyRequestsResetTime)
if ((_sharedValues.CloudApiValues.Count > 0)
&& numberOfRelevantCars < 1
&& (_sharedValues.CloudApiValues.MaxBy(v => v.Key).Key > (DateTime.UtcNow - solarEdgeTooManyRequestsResetTime)))
{
_logger.LogDebug("Prevent calling SolarEdge API as relevantCarCount is {relevantCarCount}", numberOfRelevantCars);
return null;
Expand Down
2 changes: 1 addition & 1 deletion Plugins.Solax/Plugins.Solax.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.10" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.11" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.5" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.1" />
Expand Down
8 changes: 4 additions & 4 deletions TeslaSolarCharger.Model/TeslaSolarCharger.Model.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.4">
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.4">
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.4" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,8 @@ public async Task Dont_Plan_Charging_If_Min_Soc_Reached(ChargeMode chargeMode)
};

var chargeTimeCalculationService = Mock.Create<TeslaSolarCharger.Server.Services.ChargeTimeCalculationService>();
var chargingSlots = await chargeTimeCalculationService.PlanChargingSlots(car, currentDate).ConfigureAwait(false);
// ReSharper disable once UseConfigureAwaitFalse
var chargingSlots = await chargeTimeCalculationService.PlanChargingSlots(car, currentDate);

Assert.Empty(chargingSlots);
}
Expand Down Expand Up @@ -210,7 +211,8 @@ public async Task Calculate_Correct_ChargeTimes_Without_Stock_Prices(ChargeMode
};

var chargeTimeCalculationService = Mock.Create<TeslaSolarCharger.Server.Services.ChargeTimeCalculationService>();
var chargingSlots = await chargeTimeCalculationService.PlanChargingSlots(car, currentDate).ConfigureAwait(false);
// ReSharper disable once UseConfigureAwaitFalse
var chargingSlots = await chargeTimeCalculationService.PlanChargingSlots(car, currentDate);

Assert.Single(chargingSlots);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Autofac;
using System;
using System;
using TeslaSolarCharger.Shared.Contracts;
using TeslaSolarCharger.Shared.Dtos.Settings;
using TeslaSolarCharger.Shared.TimeProviding;
Expand All @@ -24,13 +23,10 @@ public void Correctly_Updates_LatestTimeToReachSoc(bool shouldIgnoreDate, DateTi
LatestTimeToReachSoC = configuredDate,
};

var currentTimeProvider = Mock.Create<FakeDateTimeProvider>(
new NamedParameter("dateTime", currentDate));
Mock.Provide<IDateTimeProvider>(currentTimeProvider);

var latestTimeToReachSocUpdateService = Mock.Create<TeslaSolarCharger.Server.Services.LatestTimeToReachSocUpdateService>();
_fake.Provide<IDateTimeProvider>(new FakeDateTimeProvider(currentDate));
var latestTimeToReachSocUpdateService = _fake.Resolve<TeslaSolarCharger.Server.Services.LatestTimeToReachSocUpdateService>();
latestTimeToReachSocUpdateService.UpdateCarConfiguration(carConfiguration);

Assert.Equal(expectedDate, carConfiguration.LatestTimeToReachSoC);
}

Expand Down
21 changes: 12 additions & 9 deletions TeslaSolarCharger.Tests/TeslaSolarCharger.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Autofac.Extras.Moq" Version="4.3.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.1" />
<PackageReference Include="Moq" Version="4.20.69" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.XUnit" Version="3.0.5" />
<PackageReference Include="xunit" Version="2.5.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.0">
<PackageReference Include="Autofac.Extras.FakeItEasy" Version="7.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.2" />
<PackageReference Include="Autofac.Extras.Moq" Version="6.1.1" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.11" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" />
<PackageReference Include="Moq" Version="4.20.69" />
<PackageReference Include="Moq.EntityFrameworkCore" Version="7.0.0.2" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.XUnit" Version="3.0.5" />
<PackageReference Include="xunit" Version="2.5.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
34 changes: 25 additions & 9 deletions TeslaSolarCharger.Tests/TestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using Autofac;
using Autofac.Extras.FakeItEasy;
using Autofac.Extras.Moq;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
Expand All @@ -12,6 +13,8 @@
using Serilog.Events;
using TeslaSolarCharger.Model.Contracts;
using TeslaSolarCharger.Model.EntityFramework;
using TeslaSolarCharger.Server.MappingExtensions;
using TeslaSolarCharger.Shared.Contracts;
using TeslaSolarCharger.Shared.TimeProviding;
using Xunit.Abstractions;

Expand All @@ -24,6 +27,7 @@ public class TestBase : IDisposable
protected readonly AutoMock Mock;

private readonly TeslaSolarChargerContext _ctx;
protected readonly AutoFake _fake;

protected ITeslaSolarChargerContext Context => _ctx;

Expand All @@ -44,16 +48,28 @@ protected TestBase(
{"ConfigFileLocation", "configs"},
{"CarConfigFilename", "carConfig.json"},
};

var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(configDictionary!)
.Build()
.AddInMemoryCollection(configDictionary!)
.Build()
;

Mock = AutoMock.GetLoose(cfg =>
{
cfg.RegisterType(typeof(FakeDateTimeProvider));
cfg.RegisterInstance(configuration).As<IConfiguration>();
});

var currentFakeTime = new DateTime(2023, 2, 2, 8, 0, 0);

_fake = new AutoFake();
_fake.Provide<IMapperConfigurationFactory, MapperConfigurationFactory>();
_fake.Provide<IDateTimeProvider>(new FakeDateTimeProvider(currentFakeTime));
_fake.Provide<IConfiguration>(configuration);

Mock = AutoMock.GetLoose(
b =>
{
b.Register((_, _) => Context);
b.Register((_, _) => _fake.Resolve<IMapperConfigurationFactory>());
b.Register((_, _) => _fake.Resolve<IConfiguration>());
b.RegisterType<FakeDateTimeProvider>();
//b.Register((_, _) => _fake.Resolve<IDateTimeProvider>());
});

// In-memory database only exists while the connection is open
var connection = new SqliteConnection("DataSource=:memory:");
Expand Down Expand Up @@ -88,7 +104,7 @@ protected TestBase(
//var autoMock = AutoMock.GetLoose(cfg => cfg.RegisterInstance(new TeslaSolarChargerContext(options)).As<ITeslaSolarChargerContext>());
//_ctx = (TeslaSolarChargerContext) autoMock.Create<ITeslaSolarChargerContext>();

_ctx = (TeslaSolarChargerContext)Mock.Provide<ITeslaSolarChargerContext>(new TeslaSolarChargerContext(options));
_ctx = _fake.Provide(new TeslaSolarChargerContext(options));
_ctx.Database.EnsureCreated();
//_ctx.InitContextData();
_ctx.SaveChanges();
Expand Down
2 changes: 1 addition & 1 deletion TeslaSolarCharger/Client/Pages/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ else
@if (car.ChargeInformation.Count > 0)
{
<p>
Car will @(car.HomeChargePower > 0 ? "stop" : "start") charging when following conditions are met:<br/>
Car will @((car.State == CarStateEnum.Charging && car.IsHome) ? "stop" : "start") charging when following conditions are met:<br/>
<ul>
@foreach (var chargeInfo in car.ChargeInformation)
{
Expand Down
4 changes: 2 additions & 2 deletions TeslaSolarCharger/Client/TeslaSolarCharger.Client.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
<ItemGroup>
<PackageReference Include="Blazored.Toast" Version="4.1.0" />
<PackageReference Include="Majorsoft.Blazor.Components.Collapse" Version="1.5.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="7.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="7.0.10" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="7.0.11" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="7.0.11" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
Expand Down
9 changes: 5 additions & 4 deletions TeslaSolarCharger/Server/Services/ApiServices/IndexService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public DtoPvValues GetPvValues()
HomeBatterySoc = _settings.HomeBatterySoc,
PowerBuffer = powerBuffer,
CarCombinedChargingPowerAtHome = _settings.Cars.Select(c => c.CarState.ChargingPowerAtHome).Sum(),
LastUpdated = _settings.LastPvValueUpdate,
};
}

Expand Down Expand Up @@ -136,7 +137,7 @@ private List<DtoChargeInformation> GenerateChargeInformation(Car enabledCar)
});
}

if (enabledCar.CarState.State != CarStateEnum.Charging
if ((!(enabledCar.CarState.State == CarStateEnum.Charging && enabledCar.CarState.IsHomeGeofence == true))
&& enabledCar.CarState.EarliestSwitchOn != null
&& enabledCar.CarState.EarliestSwitchOn > _dateTimeProvider.Now())
{
Expand All @@ -147,7 +148,7 @@ private List<DtoChargeInformation> GenerateChargeInformation(Car enabledCar)
});
}

if (enabledCar.CarState.State != CarStateEnum.Charging
if ((!(enabledCar.CarState.State == CarStateEnum.Charging && enabledCar.CarState.IsHomeGeofence == true))
&& enabledCar.CarState.EarliestSwitchOn == null)
{
result.Add(new DtoChargeInformation()
Expand All @@ -157,7 +158,7 @@ private List<DtoChargeInformation> GenerateChargeInformation(Car enabledCar)
});
}

if (enabledCar.CarState.State == CarStateEnum.Charging
if ((enabledCar.CarState.State == CarStateEnum.Charging && enabledCar.CarState.IsHomeGeofence == true)
&& enabledCar.CarState.EarliestSwitchOff != null
&& enabledCar.CarState.EarliestSwitchOff > _dateTimeProvider.Now())
{
Expand All @@ -168,7 +169,7 @@ private List<DtoChargeInformation> GenerateChargeInformation(Car enabledCar)
});
}

if (enabledCar.CarState.State != CarStateEnum.Charging
if ((!(enabledCar.CarState.State == CarStateEnum.Charging && enabledCar.CarState.IsHomeGeofence == true))
&& (enabledCar.CarState.SocLimit - enabledCar.CarState.SoC) < (_constants.MinimumSocDifference + 1))
{
result.Add(new DtoChargeInformation()
Expand Down
3 changes: 2 additions & 1 deletion TeslaSolarCharger/Server/Services/PvValueService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public PvValueService(ILogger<PvValueService> logger, ISettings settings,
public async Task UpdatePvValues()
{
_logger.LogTrace("{method}()", nameof(UpdatePvValues));
_settings.LastPvValueUpdate = _dateTimeProvider.DateTimeOffSetNow();

var gridRequestUrl = _configurationWrapper.CurrentPowerToGridUrl();
var frontendConfiguration = _configurationWrapper.FrontendConfiguration();
HttpRequestMessage? originGridRequest = default;
Expand Down Expand Up @@ -184,6 +184,7 @@ public async Task UpdatePvValues()

_settings.HomeBatteryPower = homeBatteryPower;
}
_settings.LastPvValueUpdate = _dateTimeProvider.DateTimeOffSetNow();
}

private async Task<int?> GetValueByHttpResponse(HttpResponseMessage? httpResponse, string? jsonPattern, string? xmlPattern,
Expand Down
12 changes: 6 additions & 6 deletions TeslaSolarCharger/Server/TeslaSolarCharger.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,21 @@

<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="7.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.4">
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="7.0.11" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.11" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.5" />
<PackageReference Include="MinVer" Version="4.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="MQTTnet" Version="4.2.1.781" />
<PackageReference Include="MQTTnet" Version="4.3.1.873" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.4" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
<PackageReference Include="Quartz" Version="3.7.0" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.1" />
Expand Down

0 comments on commit f72783f

Please sign in to comment.