Compare commits

...

3 Commits

12 changed files with 118 additions and 26 deletions

View File

@ -15,17 +15,17 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AntDesign.Charts" Version="0.5.6"/> <PackageReference Include="AntDesign.Charts" Version="0.5.6" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="7.0.20"/> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="7.0.20" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="7.0.20" PrivateAssets="all"/> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="7.0.20" PrivateAssets="all" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Shared\InverterMon.Shared.csproj"/> <ProjectReference Include="..\Shared\InverterMon.Shared.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ServiceWorker Include="wwwroot\service-worker.js" PublishedContent="wwwroot\service-worker.published.js"/> <ServiceWorker Include="wwwroot\service-worker.js" PublishedContent="wwwroot\service-worker.published.js" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -5,7 +5,7 @@
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "http://localhost:5238", "applicationUrl": "http://localhost:9000",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }

View File

@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net9.0-windows</TargetFramework> <TargetFramework>net7.0-windows7.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
@ -11,7 +11,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.3124.44"/> <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.3124.44" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -31,6 +31,7 @@ public class Endpoint : EndpointWithoutRequest<object>
{ {
while (!c.IsCancellationRequested && !AppLife.ApplicationStopping.IsCancellationRequested) while (!c.IsCancellationRequested && !AppLife.ApplicationStopping.IsCancellationRequested)
{ {
/*
if (Env.IsDevelopment()) if (Env.IsDevelopment())
{ {
var status = new InverterStatus var status = new InverterStatus
@ -51,6 +52,7 @@ public class Endpoint : EndpointWithoutRequest<object>
yield return status; yield return status;
} }
else else
*/
yield return Inverter.Status; yield return Inverter.Status;
await Task.Delay(2000, c); await Task.Delay(2000, c);

View File

@ -28,20 +28,30 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FastEndpoints.Generator" Version="5.35.0" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive"/> <Content Remove="nlog.config" />
<PackageReference Include="SerialPortLib" Version="1.1.2"/>
<PackageReference Include="FastEndpoints" Version="5.35.0"/>
<PackageReference Include="LiteDB" Version="5.0.21"/>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="7.0.20"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Client\InverterMon.Client.csproj"/> <PackageReference Include="FastEndpoints.Generator" Version="5.35.0" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive" />
<ProjectReference Include="..\Shared\InverterMon.Shared.csproj"/> <PackageReference Include="NLog.Web.AspNetCore" Version="6.0.4" />
<PackageReference Include="SerialPortLib" Version="1.1.2" />
<PackageReference Include="FastEndpoints" Version="5.35.0" />
<PackageReference Include="LiteDB" Version="5.0.21" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="7.0.20" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="../changelog.md" Link="changelog.md"/> <ProjectReference Include="..\Client\InverterMon.Client.csproj" />
<ProjectReference Include="..\Shared\InverterMon.Shared.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Include="../changelog.md" Link="changelog.md" />
<None Include="nlog.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties appsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions>
</Project> </Project>

View File

@ -2,10 +2,13 @@
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.IO.Ports; using System.IO.Ports;
using InverterMon.Shared.Models; using InverterMon.Shared.Models;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
namespace InverterMon.Server.InverterService; namespace InverterMon.Server.InverterService;
sealed class SettingsData sealed class SettingsData
{ {
public double BatteryCutOffVoltage { get; init; } public double BatteryCutOffVoltage { get; init; }
public double BatteryCvChargingVoltage { get; init; } public double BatteryCvChargingVoltage { get; init; }
@ -22,6 +25,11 @@ sealed class SettingsData
SuppressMessage("ReSharper", "MemberCanBeMadeStatic.Global")] SuppressMessage("ReSharper", "MemberCanBeMadeStatic.Global")]
public sealed class FelicitySolarInverter public sealed class FelicitySolarInverter
{ {
private readonly ILogger<FelicitySolarInverter> _logger;
public FelicitySolarInverter(ILogger<FelicitySolarInverter> logger)
{
_logger = logger;
}
public InverterStatus Status { get; } = new(); public InverterStatus Status { get; } = new();
const byte SlaveAddress = 0x01; const byte SlaveAddress = 0x01;
@ -159,6 +167,9 @@ public sealed class FelicitySolarInverter
// [Slave Address][Function Code 0x03][Start Address Hi][Start Address Lo][Quantity Hi][Quantity Lo][CRC Lo][CRC Hi] // [Slave Address][Function Code 0x03][Start Address Hi][Start Address Lo][Quantity Hi][Quantity Lo][CRC Lo][CRC Hi]
byte[] frame; byte[] frame;
using ILoggerFactory factory = LoggerFactory.Create(builder => builder.AddConsole());
ILogger logger = factory.CreateLogger("Felicity");
logger.LogInformation("ReadRegisters Logging");
var statusRequest = startAddress == StatusStartAddress && numberOfPoints == StatusRegisterCount; var statusRequest = startAddress == StatusStartAddress && numberOfPoints == StatusRegisterCount;
@ -181,6 +192,16 @@ public sealed class FelicitySolarInverter
_cachedStatusFrame = frame; _cachedStatusFrame = frame;
} }
// debug
string str = "";
for (int i = 0; i < 8; i++)
{
str += frame[i].ToString("X") + " ";
}
Debug.WriteLine("Request frame: " + str);
logger.LogInformation("Request frame: {str}", str);
// end of debug
var response = SendModbusRequest(frame); var response = SendModbusRequest(frame);
if (response.Length == 0) if (response.Length == 0)
@ -192,6 +213,16 @@ public sealed class FelicitySolarInverter
int byteCount = response[2]; int byteCount = response[2];
var expectedDataBytes = numberOfPoints * 2; var expectedDataBytes = numberOfPoints * 2;
// debug
str = "";
for (int i = 0; i < response.Length; i++)
{
str += response[i].ToString("X") + " ";
}
Debug.WriteLine("Response frame: " + str);
logger.LogInformation("Response frame: {str}", str);
// end of debug
if (byteCount != expectedDataBytes) if (byteCount != expectedDataBytes)
throw new InvalidDataException("Unexpected byte count in response!"); throw new InvalidDataException("Unexpected byte count in response!");
@ -199,6 +230,16 @@ public sealed class FelicitySolarInverter
for (var i = 0; i < numberOfPoints; i++) for (var i = 0; i < numberOfPoints; i++)
registers[i] = (short)((response[3 + i * 2] << 8) | response[3 + i * 2 + 1]); registers[i] = (short)((response[3 + i * 2] << 8) | response[3 + i * 2 + 1]);
// debug
str = "";
for (int i = 0; i < numberOfPoints; i++)
{
str += registers[i].ToString("X") + " ";
}
Debug.WriteLine("Registers: " + str);
logger.LogInformation("Registers: {str}", str);
// end of debug
return registers; return registers;
} }

View File

@ -6,6 +6,7 @@ using InverterMon.Server.BatteryService;
using InverterMon.Server.InverterService; using InverterMon.Server.InverterService;
using InverterMon.Server.Persistence; using InverterMon.Server.Persistence;
using InverterMon.Server.Persistence.Settings; using InverterMon.Server.Persistence.Settings;
using NLog.Extensions.Logging;
//avoid parsing issues with non-english cultures //avoid parsing issues with non-english cultures
var cultureInfo = new CultureInfo("en-US"); var cultureInfo = new CultureInfo("en-US");
@ -14,16 +15,23 @@ CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
var bld = WebApplication.CreateBuilder(); var bld = WebApplication.CreateBuilder();
_ = int.TryParse(bld.Configuration["LaunchSettings:WebPort"] ?? "80", out var port); _ = int.TryParse(bld.Configuration["LaunchSettings:WebPort"] ?? "9000", out var port);
bld.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Any, port)); bld.WebHost.ConfigureKestrel(o => o.Listen(IPAddress.Any, port));
bld.Services bld.Services
.AddSingleton<UserSettings>() .AddSingleton<UserSettings>()
.AddSingleton<Database>() .AddSingleton<Database>()
.AddSingleton<FelicitySolarInverter>() .AddSingleton<FelicitySolarInverter>()
.AddSingleton<JkBms>(); .AddSingleton<JkBms>()
.AddLogging(config =>
{
config.ClearProviders(); // Optional: Remove default providers
config.AddConsole();
config.AddDebug();
config.AddNLog();
});
if (!bld.Environment.IsDevelopment()) //if (!bld.Environment.IsDevelopment())
{ {
bld.Services bld.Services
.AddHostedService<StatusRetriever>(); .AddHostedService<StatusRetriever>();
@ -46,4 +54,5 @@ app.UseRouting()
c.Endpoints.RoutePrefix = "api"; c.Endpoints.RoutePrefix = "api";
c.Binding.ReflectionCache.AddFromInverterMonServer(); c.Binding.ReflectionCache.AddFromInverterMonServer();
}); });
app.Run(); app.Run();

View File

@ -5,7 +5,7 @@
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "http://localhost:80", "applicationUrl": "http://localhost:9000",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }

View File

@ -1,12 +1,19 @@
{ {
"LaunchSettings": { "LaunchSettings": {
"DeviceAddress": "COM3", "DeviceAddress": "COM5",
"JkBmsAddress": "/dev/ttyUSB0", "JkBmsAddress": "/dev/ttyUSB0",
"WebPort": 80 "WebPort": 9000
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information" "Default": "Debug",
"Microsoft": "Error"
}
},
"EventLog": {
"LogLevel": {
"Default": "Warning",
"Microsoft": "Warning"
} }
} }
} }

23
src/Server/nlog.config Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8" ?>
<!-- https://www.youtube.com/watch?v=o5u4fE0t79k -->
<!-- https://github.com/NLog/NLog/wiki/Configuration-file -->
<nlog xmlns="https://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target name="logfile1" xsi:type="File" fileName="c:\temp\InverterMonServer-${shortdate}-1.log" />
<target name="logfile2" xsi:type="File" fileName="c:\temp\InverterMonServer-${shortdate}-2.log" />
<target name="logconsole" xsi:type="Console" />
<target name="ds" xsi:type="OutputDebugString"/>
</targets>
<!-- rules to map from logger name to target -->
<rules>
<logger name="FelicitySolarInverter.*" minlevel="Debug" writeTo="logconsole" />
<target name="FelicitySolarInverter.*" minlevel="Debug" writeTo="ds"/>
<logger name="FelicitySolarInverter.*" minlevel="Trace" writeTo="logfile1" />
<logger name="Felicity*" minlevel="Trace" writeTo="logfile2" />
</rules>
</nlog>

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
@ -11,7 +11,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<SupportedPlatform Include="browser"/> <SupportedPlatform Include="browser" />
</ItemGroup> </ItemGroup>
</Project> </Project>

BIN
win-x64.zip Normal file

Binary file not shown.