Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix warnings #933

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .clinerules
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
Test via `dotnet watch --project src`
Don't fix warnings and typescript issues unless it relates to your task
src/ui is svelete 5 please don't use old syntax
src/ui is svelete 4
4 changes: 2 additions & 2 deletions src/Controllers/HistoryController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using ESPresense.Models;
using ESPresense.Models;
using ESPresense.Services;
using Microsoft.AspNetCore.Mvc;

Expand All @@ -25,7 +25,7 @@ public HistoryController(ILogger<DeviceController> logger, DeviceSettingsStore d
public async Task<DeviceHistoryResponse> Get(string id)
{
var dh = await _databaseFactory.GetDeviceHistory();
var history = await dh.List(id);
var history = await dh.List(id) ?? new List<DeviceHistory>();
return new DeviceHistoryResponse(history);
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/Events/DeviceMessageEventArgs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace ESPresense.Events;

public class DeviceMessageEventArgs
{
public string DeviceId { get; set; }
public string NodeId { get; set; }
public DeviceMessage Payload { get; set; }
public string? DeviceId { get; set; }
public string? NodeId { get; set; }
public DeviceMessage? Payload { get; set; }
}
4 changes: 2 additions & 2 deletions src/Events/DeviceSettingsEventArgs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ namespace ESPresense.Events;

public class DeviceSettingsEventArgs
{
public DeviceSettings Payload { get; set; }
public string DeviceId { get; set; }
public DeviceSettings? Payload { get; set; }
public string? DeviceId { get; set; }
}
2 changes: 1 addition & 1 deletion src/Events/NodeStatusReceivedEventArgs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

public class NodeStatusReceivedEventArgs
{
public string NodeId { get; set; }
public string? NodeId { get; set; }
public bool Online { get; set; }
}
6 changes: 3 additions & 3 deletions src/Events/NodeTelemetryReceivedEventArgs.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using ESPresense.Models;
using ESPresense.Models;

namespace ESPresense.Events;

public class NodeTelemetryReceivedEventArgs
{
public string NodeId { get; set; }
public NodeTelemetry Payload { get; set; }
public string? NodeId { get; set; }
public NodeTelemetry? Payload { get; set; }
}
2 changes: 1 addition & 1 deletion src/Locators/NadarayaWatsonMultilateralizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace ESPresense.Locators;

public class NadarayaWatsonMultilateralizer(Device device, Floor floor, State state) : ILocate
public class NadarayaWatsonMultilateralizer(Device device, Floor floor) : ILocate
{
public bool Locate(Scenario scenario)
{
Expand Down
6 changes: 3 additions & 3 deletions src/Models/OptimizationSnapshot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,16 @@ public ILookup<OptNode, Measure> ByTx()

public class OptNode
{
public string Id { get; set; }
public string? Id { get; set; }
public string? Name { get; set; }
public Point3D Location { get; set; }
}

public class Measure
{
public bool Current { get; set; }
public OptNode Rx { get; set; }
public OptNode Tx { get; set; }
public OptNode Rx { get; set; } = new();
public OptNode Tx { get; set; } = new();
public double RefRssi { get; set; }
public double Rssi { get; set; }
public double Distance { get; set; }
Expand Down
11 changes: 7 additions & 4 deletions src/Models/Scenario.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,18 @@ public void UpdateLocation(Point3D newLocation)
UpdateStateTransitionMatrix(dt);

// Predict
_kalmanStateEstimate = _F! * _kalmanStateEstimate!;
_kalmanErrorCovariance = _F * _kalmanErrorCovariance! * _F.Transpose() + _Q!;
if (_F == null || _kalmanStateEstimate == null || _kalmanErrorCovariance == null || _H == null || _Q == null || _R == null)
return;

_kalmanStateEstimate = _F * _kalmanStateEstimate;
_kalmanErrorCovariance = _F * _kalmanErrorCovariance * _F.Transpose() + _Q;

// Update
var y = Matrix<double>.Build.DenseOfArray(new double[,] {
{ newLocation.X }, { newLocation.Y }, { newLocation.Z }
}) - _H! * _kalmanStateEstimate;
}) - _H * _kalmanStateEstimate;

var S = _H * _kalmanErrorCovariance * _H.Transpose() + _R!;
var S = _H * _kalmanErrorCovariance * _H.Transpose() + _R;
var K = _kalmanErrorCovariance * _H.Transpose() * S.Inverse();

_kalmanStateEstimate += K * y;
Expand Down
2 changes: 1 addition & 1 deletion src/Models/State.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public IEnumerable<Scenario> GetScenarios(Device device)

if (nadarayaWatson?.Enabled ?? false)
foreach (var floor in GetFloorsByIds(nadarayaWatson?.Floors))
yield return new Scenario(Config, new NadarayaWatsonMultilateralizer(device, floor, this), floor.Name);
yield return new Scenario(Config, new NadarayaWatsonMultilateralizer(device, floor), floor.Name);

if (nearestNode?.Enabled ?? false)
yield return new Scenario(Config, new NearestNode(device), "NearestNode");
Expand Down
7 changes: 4 additions & 3 deletions src/Optimizers/AbsorptionAvgOptimizer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using ESPresense.Models;
using ESPresense.Models;

namespace ESPresense.Optimizers;

Expand Down Expand Up @@ -32,8 +32,9 @@ public OptimizationResults Optimize(OptimizationSnapshot os)
if (pathLossExponents.Count > 0)
{
var absorption = pathLossExponents.Average();
if (absorption < _state.Config?.Optimization.AbsorptionMin) continue;
if (absorption > _state.Config?.Optimization.AbsorptionMax) continue;
var optimization = _state.Config?.Optimization;
if (absorption < (optimization?.AbsorptionMin ?? 2.0)) continue;
if (absorption > (optimization?.AbsorptionMax ?? 4.0)) continue;
results.RxNodes.Add(g.Key.Id, new ProposedValues { Absorption = absorption });
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/Optimizers/AbsorptionErrOptimizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ public OptimizationResults Optimize(OptimizationSnapshot os)
return error;
});

var initialGuess = Vector<double>.Build.DenseOfArray(new[] { (optimization?.AbsorptionMax - optimization?.AbsorptionMin) / 2 + optimization?.AbsorptionMin ?? 3d });
var initialGuess = Vector<double>.Build.DenseOfArray(new[] {
((optimization?.AbsorptionMax ?? 4.0) - (optimization?.AbsorptionMin ?? 2.0)) / 2 + (optimization?.AbsorptionMin ?? 2.0)
});

var solver = new NelderMeadSimplex(1e-4, 10000);
var result = solver.FindMinimum(obj, initialGuess);
Expand Down
5 changes: 3 additions & 2 deletions src/Optimizers/AbsorptionLineFitOptimizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@ public OptimizationResults Optimize(OptimizationSnapshot os)
var linearModel = Fit.Line(distances.ToArray(), rssiDiffs.ToArray());

double absorption = linearModel.Item2 / 10;
if (absorption < _state.Config?.Optimization.AbsorptionMin) continue;
if (absorption > _state.Config?.Optimization.AbsorptionMax) continue;
var optimization = _state.Config?.Optimization;
if (absorption < (optimization?.AbsorptionMin ?? 2.0)) continue;
if (absorption > (optimization?.AbsorptionMax ?? 4.0)) continue;
or.RxNodes.Add(g.Key.Id, new ProposedValues { Absorption = absorption });
}

Expand Down
4 changes: 2 additions & 2 deletions src/Optimizers/RxAdjRssiOptimizer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using ESPresense.Models;
using ESPresense.Models;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.Optimization;
using Serilog;
Expand All @@ -22,7 +22,7 @@ public OptimizationResults Optimize(OptimizationSnapshot os)
OptimizationResults or = new();
var optimization = _state.Config?.Optimization;

var absorption = ((optimization?.AbsorptionMax - optimization?.AbsorptionMin) / 2d) + optimization?.AbsorptionMin ?? 3d;
var absorption = ((optimization?.AbsorptionMax ?? 4.0) - (optimization?.AbsorptionMin ?? 2.0)) / 2d + (optimization?.AbsorptionMin ?? 2.0);

foreach (var g in os.ByRx())
{
Expand Down
10 changes: 5 additions & 5 deletions src/Services/DeviceTracker.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Threading.Channels;
using System.Threading.Channels;
using ESPresense.Controllers;
using ESPresense.Models;
using Serilog;
Expand All @@ -21,13 +21,13 @@
Log.Debug("Ignoring, component isn't device_tracker (" + arg.AutoDiscover.Component + ")");
return;
}
var deviceId = arg.AutoDiscover.Message.StateTopic.Split("/").Last();
bool isNode = deviceId.StartsWith("node:");
var deviceId = arg.AutoDiscover.Message?.StateTopic?.Split("/").Last() ?? string.Empty;
bool isNode = deviceId?.StartsWith("node:") ?? false;
if (isNode) return;

var device = state.Devices.GetOrAdd(deviceId, id =>

Check warning on line 28 in src/Services/DeviceTracker.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'key' in 'Device ConcurrentDictionary<string, Device>.GetOrAdd(string key, Func<string, Device> valueFactory)'.
{
var d = new Device(id, arg.AutoDiscover.DiscoveryId, TimeSpan.FromSeconds(state.Config?.Timeout ?? 30)) { Name = arg.AutoDiscover.Message.Name, Track = true, Check = true, LastCalculated = DateTime.UtcNow };

Check warning on line 30 in src/Services/DeviceTracker.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
foreach (var scenario in state.GetScenarios(d)) d.Scenarios.Add(scenario);
Log.Information("[+] Track: {Device} (disc)", d);
return d;
Expand All @@ -36,11 +36,11 @@

mqtt.DeviceMessageReceivedAsync += async arg =>
{
bool isNode = arg.DeviceId.StartsWith("node:");
bool isNode = !string.IsNullOrEmpty(arg.DeviceId) && arg.DeviceId.StartsWith("node:");

if (!state.Nodes.TryGetValue(arg.NodeId, out var rx))
if (string.IsNullOrEmpty(arg.NodeId) || !state.Nodes.TryGetValue(arg.NodeId, out var rx))
{
state.Nodes[arg.NodeId] = rx = new Node(arg.NodeId);

Check warning on line 43 in src/Services/DeviceTracker.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'key' in 'Node ConcurrentDictionary<string, Node>.this[string key]'.
if (tele.AddUnknownNode(arg.NodeId))
Log.Warning("Unknown node {nodeId}", arg.NodeId);
}
Expand Down
10 changes: 6 additions & 4 deletions src/Services/MqttCoordinator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,16 @@
await mqttClient.SubscribeAsync("homeassistant/device_tracker/+/config");
};

mqttClient.DisconnectedAsync += s =>
mqttClient.DisconnectedAsync += async s =>
{
Log.Information("MQTT disconnected");
return Task.CompletedTask;
await Task.CompletedTask;
};

mqttClient.ConnectingFailedAsync += s =>
mqttClient.ConnectingFailedAsync += async s =>
{
Log.Error("MQTT connection failed {@error}: {@inner}", new { primary = true }, s.Exception.Message, s.Exception?.InnerException?.Message);
return Task.CompletedTask;
await Task.CompletedTask;
};

mqttClient.ApplicationMessageReceivedAsync += OnMqttMessageReceived;
Expand All @@ -139,6 +139,8 @@

private async Task OnMqttMessageReceived(MqttApplicationMessageReceivedEventArgs arg)
{
if (arg.ApplicationMessage?.Topic == null) return;

var parts = arg.ApplicationMessage.Topic.Split('/');
var payload = arg.ApplicationMessage.ConvertPayloadToString();

Expand Down Expand Up @@ -310,7 +312,7 @@
});
}

private async Task ProcessDiscoveryMessage(string topic, string? payload)

Check warning on line 315 in src/Services/MqttCoordinator.cs

View workflow job for this annotation

GitHub Actions / build

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
{
try
{
Expand All @@ -322,7 +324,7 @@
if (!AutoDiscovery.TryDeserialize(topic, payload, out var msg))
throw new MqttMessageProcessingException("Failed to deserialize discovery message", topic, payload, "Discovery");

PreviousDeviceDiscovered?.Invoke(this, new PreviousDeviceDiscoveredEventArgs { AutoDiscover = msg });

Check warning on line 327 in src/Services/MqttCoordinator.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference assignment.
}
catch (Exception ex) when (ex is not MqttMessageProcessingException)
{
Expand Down
12 changes: 8 additions & 4 deletions src/Services/NodeSettingsStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,24 @@
{
try
{
var ns = Get(arg.NodeId);

Check warning on line 32 in src/Services/NodeSettingsStore.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'id' in 'NodeSettings NodeSettingsStore.Get(string id)'.
switch (arg.Setting)
{
case "absorption":
ns.Absorption = double.Parse(arg.Payload);
if (arg.Payload != null)
ns.Absorption = double.Parse(arg.Payload);
break;
case "rx_adj_rssi":
ns.RxAdjRssi = int.Parse(arg.Payload);
if (arg.Payload != null)
ns.RxAdjRssi = int.Parse(arg.Payload);
break;
case "tx_ref_rssi":
ns.TxRefRssi = int.Parse(arg.Payload);
if (arg.Payload != null)
ns.TxRefRssi = int.Parse(arg.Payload);
break;
case "max_distance":
ns.MaxDistance = double.Parse(arg.Payload);
if (arg.Payload != null)
ns.MaxDistance = double.Parse(arg.Payload);
break;
default:
return Task.CompletedTask;
Expand Down
58 changes: 58 additions & 0 deletions src/ui/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"@tailwindcss/forms": "^0.5.9",
"@types/d3": "^7.4.3",
"@types/node": "^22.9.1",
"@types/three": "^0.171.0",
"@typescript-eslint/eslint-plugin": "^8.15.0",
"@typescript-eslint/parser": "^8.15.0",
"autoprefixer": "^10.4.20",
Expand All @@ -40,6 +41,7 @@
"svelte-check": "^4.1.1",
"svelte-eslint-parser": "^0.43.0",
"svelte-table": "^0.6.3",
"three": "^0.171.0",
"tslib": "^2.8.1",
"typescript": "^5.7.2",
"typescript-eslint": "^8.18.2",
Expand Down
Loading
Loading