Skip to content
Merged
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
81 changes: 81 additions & 0 deletions Network Monitor.Tests/RouterCheckTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Network_Monitor.Monitors;

namespace Network_Monitor.Tests;

public class RouterCheckTests
{
private const string Router = "192.168.1.1";

/// <summary>
/// Pings that finish when told to, so each test decides how the router answers.
/// </summary>
private readonly Queue<TaskCompletionSource<bool>> _pings = new();

private RouterCheck CreateCheck() => new(_ =>
{
var ping = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_pings.Enqueue(ping);
return ping.Task;
});

private async Task AnswerAsync(bool answered)
{
_pings.Dequeue().SetResult(answered);

// The reply is noted on another thread.
await Task.Delay(50);
}

[Fact]
public void Check_WithNoRouter_SaysNothing()
{
var check = CreateCheck();

Assert.Null(check.Check(null));
Assert.Empty(_pings);
}

[Fact]
public void Check_BeforeTheFirstReply_SaysItsChecking()
{
var check = CreateCheck();

Assert.Equal("Checking your router…", check.Check(Router)?.Note);
}

[Fact]
public async Task Check_WhenTheRouterAnswers_SaysTheProblemIsPastIt()
{
var check = CreateCheck();

check.Check(Router);
await AnswerAsync(true);

Assert.Equal("Your router is fine; the problem is past it", check.Check(Router)?.Note);
}

[Fact]
public async Task Check_WhenTheRouterDoesntAnswer_SaysSo()
{
var check = CreateCheck();

check.Check(Router);
await AnswerAsync(false);

Assert.Equal("Your router isn't answering", check.Check(Router)?.Note);
}

[Fact]
public void Check_WhileAPingIsWaiting_DoesntSendAnother()
{
var check = CreateCheck();

check.Check(Router);
check.Check(Router);
check.Check(Router);

Assert.Single(_pings);
}
}
39 changes: 37 additions & 2 deletions Network Monitor/Monitors/LatencyMonitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ public class LatencyMonitor : Monitor
/// </summary>
private readonly ConcurrentBag<Ping> _idlePings = new();

/// <summary>
/// Pings the router while the internet isn't answering, to tell whether an outage is on your own network or past it.
/// </summary>
private readonly RouterCheck _routerCheck;

private int _pingsOut;

/// <summary>
Expand All @@ -49,6 +54,11 @@ public class LatencyMonitor : Monitor
/// </summary>
private (DateTime Start, DateTime End)? _lastOutage;

/// <summary>
/// What the latest tick found out about the router, said along with the outage clock, or null.
/// </summary>
private (string Note, string Spoken)? _routerNote;

public LatencyMonitor(string host, TimeSpan timeout) : base(true)
{
Name = "Latency";
Expand All @@ -61,6 +71,7 @@ public LatencyMonitor(string host, TimeSpan timeout) : base(true)
_host = host;
_timeout = (int)timeout.TotalMilliseconds;
_maxPingsOut = (int)Math.Ceiling(timeout.TotalSeconds) + 2;
_routerCheck = new RouterCheck(timeout);
}

protected override string GetDisplayValue()
Expand All @@ -85,6 +96,7 @@ protected override string GetDisplayValue()
StartPing();
RememberOutage(view, snapshot.LastReplyAt, now);

_routerNote = CheckRouter(view);
_view = view;
IsStale = view.IsStale;
return view.Value;
Expand All @@ -107,6 +119,9 @@ protected override string GetDetails()
if (view.NoteLine is not null)
lines.Add(view.NoteLine);

if (_routerNote is var (routerNote, _))
lines.Add(routerNote);

if (successes.Length > 0)
lines.Add($"Min/Avg/Max: {FormatRoundtrip(successes.Min())} / {FormatRoundtrip((long)Math.Round(successes.Average(), MidpointRounding.AwayFromZero))} / {FormatRoundtrip(successes.Max())} ms");

Expand Down Expand Up @@ -157,6 +172,21 @@ private void RememberOutage(LatencyView view, DateTime? lastReplyAt, DateTime no
}
}

/// <summary>
/// Pings the router while the outage clock is up, and returns what it showed.
/// Not on a network that seems to block ping, where the internet never answers and the router would be pinged for good.
/// </summary>
private (string Note, string Spoken)? CheckRouter(LatencyView view)
{
if (!view.IsOutage)
{
_routerCheck.Stop();
return null;
}

return _routerCheck.Check(NetworkStatus.Router);
}

protected override IReadOnlyList<double?> GetHistory() =>
LatencyHistory.GetFinished(_history.GetSnapshot().Slots).Select(s => s >= 0 ? (double?)s : null).ToArray();

Expand Down Expand Up @@ -221,8 +251,13 @@ private async void SendPing(LatencyHistory.Ticket ticket)
}
}

protected override string GetSpokenValue(string displayValue) =>
displayValue == _view.Value ? $"{Name}, {_view.Spoken}" : base.GetSpokenValue(displayValue);
protected override string GetSpokenValue(string displayValue)
{
if (displayValue != _view.Value)
return base.GetSpokenValue(displayValue);

return _routerNote is var (_, routerSpoken) ? $"{Name}, {_view.Spoken}, {routerSpoken}" : $"{Name}, {_view.Spoken}";
}

/// <summary>
/// Returns a latency reading as a screen reader should say it.
Expand Down
6 changes: 6 additions & 0 deletions Network Monitor/Monitors/NetworkStatus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,12 @@ public static bool IsReconnecting
}
}

/// <summary>
/// The IPv4 address of the router to ping when the internet stops answering, to tell a drop on your own network from one past it: the router of the adapter internet traffic leaves through.
/// Null when there isn't one, like with no route to the internet or on some mobile broadband.
/// </summary>
public static string Router => _currentNetwork.FirstOrDefault(x => x.IsIPv4)?.Gateway;

/// <summary>
/// Whether a ping has ever come back through the network internet traffic leaves through now.
/// If so, failing pings are an outage; if not, the network may just block ping, like many work VPNs and public Wi-Fi.
Expand Down
104 changes: 104 additions & 0 deletions Network Monitor/Monitors/RouterCheck.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
using System;
using System.Net.NetworkInformation;
using System.Threading.Tasks;

namespace Network_Monitor.Monitors;

/// <summary>
/// Pings the router during an outage, which tells whether a drop is on your own network or past it, like at your provider.
/// </summary>
/// <remarks>
/// Nothing is sent while the internet answers, and during an outage the router gets one ping at a time, at most one a second.
/// </remarks>
public sealed class RouterCheck
{
private readonly Func<string, Task<bool>> _ping;
private readonly object _lock = new();

/// <summary>
/// Whether the router's latest ping during this outage came back, or null if none has finished yet.
/// </summary>
private bool? _answered;

private bool _isOut;

/// <param name="timeout">How long to wait for each reply.</param>
public RouterCheck(TimeSpan timeout) : this(address => PingAsync(address, (int)timeout.TotalMilliseconds))
{
}

/// <param name="ping">Sends a ping and returns whether it came back, in place of a real one.</param>
public RouterCheck(Func<string, Task<bool>> ping)
{
_ping = ping;
}

/// <summary>
/// Pings <paramref name="router" /> unless it's still waiting for a reply, and returns a tooltip line about it and what a screen reader says.
/// Called on the clock tick during an outage.
/// </summary>
/// <param name="router">The IPv4 address of the router internet traffic leaves through, or null if there's none.</param>
/// <returns>Null when there's no router to check.</returns>
public (string Note, string Spoken)? Check(string router)
{
if (router is null)
return null;

lock (_lock)
{
if (!_isOut)
{
_isOut = true;
_ = SendAsync(router);
}

return _answered switch
{
// Not "the internet", since 8.8.8.8 itself may be what's down.
true => ("Your router is fine; the problem is past it", "your router is fine, the problem is past it"),
false => ("Your router isn't answering", "your router isn't answering"),
null => ("Checking your router…", "checking your router"),
};
}
}

/// <summary>
/// Forgets how the router answered during this outage, once the internet answers again, so the next one starts fresh.
/// </summary>
public void Stop()
{
lock (_lock)
_answered = null;
}

/// <summary>
/// Pings the router and notes how it went.
/// It never fails, so nothing waits for the task it returns.
/// </summary>
private async Task SendAsync(string router)
{
var answered = false;

try
{
answered = await _ping(router).ConfigureAwait(false);
}
catch
{
// A ping that can't be sent, like with no route to the router, got no answer.
}

lock (_lock)
{
_isOut = false;
_answered = answered;
}
}

private static async Task<bool> PingAsync(string address, int timeout)
{
using var ping = new Ping();
var reply = await ping.SendPingAsync(address, timeout).ConfigureAwait(false);
return reply.Status == IPStatus.Success;
}
}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Hover for a 60-second sparkline and the stats behind it: min/avg/max, jitter, pa
- **Sharp on every monitor:** stays crisp on monitors with different scaling, like a laptop beside a monitor.
- **Copy on demand:** double-click, or right-click → **Copy**, to grab the current numbers.
- **Starts with Windows:** optionally launch on sign-in, and check for updates in one click from the menu.
- **Honest outages:** when pings stop, a clock counts the time since the last reply; hover for when it started.
- **Honest outages:** a clock counts from the last reply, and hover says whether your router still answers.
- **Light on resources:** one tiny reading per second, published exactly when the system clock ticks.

## 🚀 Install
Expand Down