Skip to content

Commit

Permalink
Improve request time
Browse files Browse the repository at this point in the history
  • Loading branch information
JonasMH committed Jan 11, 2024
1 parent 25e1305 commit 40983a8
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 37 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
# Rejseplanen2Mqtt
# Rejseplanen2Mqtt
2 changes: 1 addition & 1 deletion src/Client/Models/Trip.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ public class Trip
public class TripResponse
{
public bool Cancelled { get; set; }
public List<TripLeg> Legs { get; set; } = new List<TripLeg>();
public List<TripLeg> Legs { get; set; } = [];
}
6 changes: 5 additions & 1 deletion src/Client/Models/TripRequestOptions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
namespace Rejseplanen2Mqtt.Client;
using NodaTime;

namespace Rejseplanen2Mqtt.Client;

public class TripRequestOptions
{
public string OriginId { get; set; } = null!;
public string DestId { get; set; } = null!;
public LocalDate? Date { get; set; }
public LocalTime? Time { get; set; }
}
30 changes: 27 additions & 3 deletions src/Client/RejseplanenClient.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
using System.Text.Json;
using System.Collections.Specialized;
using System.Text.Json;
using Microsoft.AspNetCore.Http.Extensions;
using NodaTime.Text;

namespace Rejseplanen2Mqtt.Client;

public class RejseplanenClient
{
private readonly HttpClient _httpClient;


public static LocalTimePattern TimePattern { get; } = LocalTimePattern.CreateWithInvariantCulture("HH:mm"); // 13:30
public static LocalDatePattern DatePattern { get; } = LocalDatePattern.CreateWithInvariantCulture("dd.MM.yy"); // 06.01.24

public RejseplanenClient(HttpClient httpClient, RejseplanenClientOptions options)
{
_httpClient = httpClient;
Expand All @@ -27,9 +34,26 @@ public async Task<DepartureBoardResponse> DepartureBoardAsync(DeparturBoardReque

public async Task<List<TripResponse>> TripAsync(TripRequestOptions options)
{
var request = new HttpRequestMessage()
var requestParameters = new QueryBuilder
{
{ "format", "json" },
{ "originId", options.OriginId },
{ "destId", options.DestId }
};

if(options.Date.HasValue)
{
requestParameters.Add("date", DatePattern.Format(options.Date.Value));
}

if(options.Time.HasValue)
{
requestParameters.Add("time", TimePattern.Format(options.Time.Value));
}

var request = new HttpRequestMessage()
{
RequestUri = new Uri($"/bin/rest.exe/trip?originId={options.OriginId}&destId={options.DestId}&format=json", UriKind.Relative)
RequestUri = new Uri($"/bin/rest.exe/trip" + requestParameters.ToString(), UriKind.Relative)
};
var response = await _httpClient.SendAsync(request);

Expand Down
8 changes: 8 additions & 0 deletions src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using MQTTnet.Client;
using OpenTelemetry.Metrics;
using Rejseplanen2Mqtt.Client;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using ToMqttNet;

Expand All @@ -15,6 +16,7 @@
options.TimestampFormat = "HH:mm:ss ";
});
builder.Services.AddOptions<MqttOptions>().BindConfiguration("MqttConnectionOptions");
builder.Services.AddOptions<RejseplanenToMqttOptions>().BindConfiguration("RejseplanenToMqttOptions");

builder.Services.AddHealthChecks();
builder.Services.AddOpenTelemetry()
Expand All @@ -32,6 +34,12 @@
{
var mqttConf = mqttConfI.Value;
options.NodeId = "rejseplanen";
options.OriginConfig = new HomeAssistantDiscoveryNet.MqttDiscoveryConfigOrigin
{
Name = "rejseplanen2mqtt",
SoftwareVersion = Assembly.GetExecutingAssembly().GetName().Version?.ToString(),
SupportUrl = "https://github.com/JonasMH/Rejseplanen2Mqtt"
};

var tcpOptions = new MqttClientTcpOptions
{
Expand Down
2 changes: 1 addition & 1 deletion src/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"profiles": {
"Rejseplanen2Mqtt": {
"commandName": "Project",
"launchBrowser": true,
"launchBrowser": false,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
Expand Down
57 changes: 27 additions & 30 deletions src/RejsePlanenToMqttBackgroundService.cs
Original file line number Diff line number Diff line change
@@ -1,40 +1,28 @@
// See https://aka.ms/new-console-template for more information
using HomeAssistantDiscoveryNet;
using Microsoft.Extensions.Options;
using MQTTnet;
using NodaTime;
using NodaTime.Text;
using Rejseplanen2Mqtt.Client;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using ToMqttNet;

namespace Rejseplanen2Mqtt.Client;

public class RejsePlanenToMqttBackgroundService(
ILogger<RejsePlanenToMqttBackgroundService> logger,
IOptions<RejseplanenToMqttOptions> options,
RejseplanenClient rejseplanenClient,
MqttConnectionService mqtt) : BackgroundService
{
private readonly ILogger<RejsePlanenToMqttBackgroundService> _logger = logger;
private readonly RejseplanenClient _rejseplanenClient = rejseplanenClient;
private readonly RejseplanenToMqttOptions options = options.Value;
private readonly RejseplanenClient _rejseplanenClient = rejseplanenClient;
private readonly MqttConnectionService _mqtt = mqtt;
private readonly List<TripToInform> _tripsToPublish = [
new TripToInform {
Name = "Aarhus to Hedensted",
OriginId = "8600053", // Aarhus H
DestId = "8600071", // Hedensted St.
},
new TripToInform {
Name = "Hedensted to Aarhus",
OriginId = "8600071", // Hedensted St.
DestId = "8600053", // Aarhus H
},
];

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
foreach (var trip in _tripsToPublish)
foreach (var trip in options.TripsToPublish)
{
var discoveryDoc = new MqttSensorDiscoveryConfig()
{
Expand All @@ -52,13 +40,26 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)

while (!stoppingToken.IsCancellationRequested)
{
foreach (var tripToPublish in _tripsToPublish)
foreach (var tripToPublish in options.TripsToPublish)
{
var response = await _rejseplanenClient.TripAsync(new TripRequestOptions
{
OriginId = tripToPublish.OriginId,
DestId = tripToPublish.DestId
});
var localTime = SystemClock.Instance.GetCurrentInstant().InZone(DateTimeZoneProviders.Tzdb.GetZoneOrNull("Europe/Copenhagen")!).LocalDateTime;
var requestOptions = new TripRequestOptions
{
OriginId = tripToPublish.OriginId,
DestId = tripToPublish.DestId
};

if(tripToPublish.Time != null)
{
requestOptions.Time = RejseplanenClient.TimePattern.Parse(tripToPublish.Time).Value;

if(requestOptions.Time.Value.PlusHours(3) < localTime.TimeOfDay) // We're far enough away from the request time that we should switch to the next day
{
requestOptions.Date = localTime.Date.PlusDays(1);
}
}

var response = await _rejseplanenClient.TripAsync(requestOptions);

var result = new TripMqttStatusUpdate
{
Expand All @@ -68,19 +69,14 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
}
};

// Filter out any trips with multiple legs
var localTime = SystemClock.Instance.GetCurrentInstant().InZone(DateTimeZoneProviders.Tzdb.GetZoneOrNull("Europe/Copenhagen")!).LocalDateTime;

foreach (var directTrip in response.Where(x => !x.Cancelled && x.Legs.Count == 1)) // Only show direct trips
{
var firstLeg = directTrip.Legs.First();
var tripStart = firstLeg.Origin;

var timePattern = LocalTimePattern.CreateWithInvariantCulture("HH:mm"); // 13:30
var datePattern = LocalDatePattern.CreateWithInvariantCulture("dd.MM.yy"); // 06.01.24

var nextDepatureTime = timePattern.Parse(tripStart.RealtimeTime ?? tripStart.Time).Value;
var nextDepatureDate = datePattern.Parse(tripStart.RealtimeDate ?? tripStart.Date).Value;
var nextDepatureTime = RejseplanenClient.TimePattern.Parse(tripStart.RealtimeTime ?? tripStart.Time).Value;
var nextDepatureDate = RejseplanenClient.DatePattern.Parse(tripStart.RealtimeDate ?? tripStart.Date).Value;

var nextDepature = nextDepatureTime.On(nextDepatureDate);

Expand Down Expand Up @@ -152,4 +148,5 @@ public class TripToInform
public string Name { get; set; } = null!;
public string OriginId { get; set; } = null!;
public string DestId { get; set; } = null!;
public string? Time { get; set; } = null!;
}
20 changes: 20 additions & 0 deletions src/RejseplanenToMqttOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// See https://aka.ms/new-console-template for more information
namespace Rejseplanen2Mqtt.Client;

public class RejseplanenToMqttOptions
{
public List<TripToInform> TripsToPublish { get; set; } = [
new TripToInform {
Name = "Aarhus to Hedensted",
OriginId = "8600053", // Aarhus H
DestId = "8600071", // Hedensted St.
Time = "13:30"
},
new TripToInform {
Name = "Hedensted to Aarhus",
OriginId = "8600071", // Hedensted St.
DestId = "8600053", // Aarhus H
Time = "6:50"
},
];
}

0 comments on commit 40983a8

Please sign in to comment.