diff --git a/SmartTeslaAmpSetter.Tests/Services/GridService.cs b/SmartTeslaAmpSetter.Tests/Services/GridService.cs new file mode 100644 index 000000000..f019e85a7 --- /dev/null +++ b/SmartTeslaAmpSetter.Tests/Services/GridService.cs @@ -0,0 +1,26 @@ +using Xunit; +using Xunit.Abstractions; + +namespace SmartTeslaAmpSetter.Tests.Services; + +public class GridService : TestBase +{ + public GridService(ITestOutputHelper outputHelper) + : base(outputHelper) + { + } + + [Theory] + [InlineData("384.8746")] + [InlineData("384")] + [InlineData("384.0")] + [InlineData("384.147")] + public void Can_extract_Integers_From_String(string value) + { + var gridService = Mock.Create(); + var intValue = gridService.GetIntegerFromString(value); + + Assert.Equal(384, intValue); + } + +} \ No newline at end of file diff --git a/SmartTeslaAmpSetter/Server/Services/GridService.cs b/SmartTeslaAmpSetter/Server/Services/GridService.cs index 2bfe2bdf6..b94ac379f 100644 --- a/SmartTeslaAmpSetter/Server/Services/GridService.cs +++ b/SmartTeslaAmpSetter/Server/Services/GridService.cs @@ -1,4 +1,5 @@ -using Newtonsoft.Json.Linq; +using System.Globalization; +using Newtonsoft.Json.Linq; using SmartTeslaAmpSetter.Server.Contracts; namespace SmartTeslaAmpSetter.Server.Services; @@ -43,16 +44,26 @@ public async Task GetCurrentOverage() throw new InvalidOperationException("Extracted Json Value is null")).Value(); } - if (int.TryParse(result, out var overage)) + try { + var overage = GetIntegerFromString(result); if (_configuration.GetValue("CurrentPowerToGridInvertValue")) { overage = -overage; } - return overage; + return overage ; } + catch (Exception) + { + throw new InvalidCastException($"Could not parse result {result} from uri {requestUri} to integer"); + } + + } - throw new InvalidCastException($"Could not parse result {result} from uri {requestUri} to integer"); + internal int GetIntegerFromString(string? inputString) + { + _logger.LogTrace("{method}({param})", nameof(GetIntegerFromString), inputString); + return (int) double.Parse(inputString ?? throw new ArgumentNullException(nameof(inputString)), CultureInfo.InvariantCulture); } public async Task GetCurrentInverterPower() @@ -77,11 +88,13 @@ await _telegramService.SendMessage( } var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - if (int.TryParse(result, out var overage)) + try { - return overage; + return GetIntegerFromString(result); + } + catch (Exception) + { + throw new InvalidCastException($"Could not parse result {result} from uri {requestUri} to integer"); } - - throw new InvalidCastException($"Could not parse result {result} from uri {requestUri} to integer"); } } \ No newline at end of file