1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
|
using System.Globalization;
using System.Text;
using Costasdev.Busurbano.Backend.Configuration;
using Costasdev.Busurbano.Backend.Services;
using Costasdev.Busurbano.Backend.Types;
using Costasdev.VigoTransitApi;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using static Costasdev.Busurbano.Backend.Types.StopArrivals.Types;
using SysFile = System.IO.File;
namespace Costasdev.Busurbano.Backend.Controllers;
[ApiController]
[Route("api/vigo")]
public partial class VigoController : ControllerBase
{
private readonly ILogger<VigoController> _logger;
private readonly VigoTransitApiClient _api;
private readonly AppConfiguration _configuration;
private readonly ShapeTraversalService _shapeService;
public VigoController(HttpClient http, IOptions<AppConfiguration> options, ILogger<VigoController> logger, ShapeTraversalService shapeService)
{
_logger = logger;
_api = new VigoTransitApiClient(http);
_configuration = options.Value;
_shapeService = shapeService;
}
[HttpGet("GetShape")]
public async Task<IActionResult> GetShape(
[FromQuery] string shapeId,
[FromQuery] int? startPointIndex = null,
[FromQuery] double? busLat = null,
[FromQuery] double? busLon = null,
[FromQuery] int? busShapeIndex = null,
[FromQuery] double? stopLat = null,
[FromQuery] double? stopLon = null,
[FromQuery] int? stopShapeIndex = null
)
{
var path = await _shapeService.GetShapePathAsync(shapeId, 0);
if (path == null)
{
return NotFound();
}
// Determine bus point
object? busPoint = null;
if (busShapeIndex.HasValue && busShapeIndex.Value >= 0 && busShapeIndex.Value < path.Count)
{
var p = path[busShapeIndex.Value];
busPoint = new { lat = p.Latitude, lon = p.Longitude, index = busShapeIndex.Value };
}
else if (busLat.HasValue && busLon.HasValue)
{
var idx = await _shapeService.FindClosestPointIndexAsync(shapeId, busLat.Value, busLon.Value);
if (idx.HasValue && idx.Value >= 0 && idx.Value < path.Count)
{
var p = path[idx.Value];
busPoint = new { lat = p.Latitude, lon = p.Longitude, index = idx.Value };
}
}
else if (startPointIndex.HasValue && startPointIndex.Value >= 0 && startPointIndex.Value < path.Count)
{
var p = path[startPointIndex.Value];
busPoint = new { lat = p.Latitude, lon = p.Longitude, index = startPointIndex.Value };
}
// Determine stop point
object? stopPoint = null;
if (stopShapeIndex.HasValue && stopShapeIndex.Value >= 0 && stopShapeIndex.Value < path.Count)
{
var p = path[stopShapeIndex.Value];
stopPoint = new { lat = p.Latitude, lon = p.Longitude, index = stopShapeIndex.Value };
}
else if (stopLat.HasValue && stopLon.HasValue)
{
var idx = await _shapeService.FindClosestPointIndexAsync(shapeId, stopLat.Value, stopLon.Value);
if (idx.HasValue && idx.Value >= 0 && idx.Value < path.Count)
{
var p = path[idx.Value];
stopPoint = new { lat = p.Latitude, lon = p.Longitude, index = idx.Value };
}
}
// Convert to GeoJSON LineString
var coordinates = path.Select(p => new[] { p.Longitude, p.Latitude }).ToList();
var geoJson = new
{
type = "Feature",
geometry = new
{
type = "LineString",
coordinates = coordinates
},
properties = new
{
busPoint,
stopPoint
}
};
return Ok(geoJson);
}
[HttpGet("GetConsolidatedCirculations")]
public async Task<IActionResult> GetConsolidatedCirculations(
[FromQuery] int stopId
)
{
// Use Europe/Madrid timezone consistently to avoid UTC/local skew
var tz = TimeZoneInfo.FindSystemTimeZoneById("Europe/Madrid");
var nowLocal = TimeZoneInfo.ConvertTime(DateTime.UtcNow, tz);
var realtimeTask = _api.GetStopEstimates(stopId);
var todayDate = nowLocal.Date.ToString("yyyy-MM-dd");
// Load both today's and tomorrow's schedules to handle night services
var timetableTask = LoadStopArrivalsProto(stopId.ToString(), todayDate);
// Wait for real-time data and today's schedule (required)
await Task.WhenAll(realtimeTask, timetableTask);
var realTimeEstimates = realtimeTask.Result.Estimates;
// Handle case where schedule file doesn't exist - return realtime-only data
if (timetableTask.Result == null)
{
_logger.LogWarning("No schedule data available for stop {StopId} on {Date}, returning realtime-only data", stopId, todayDate);
var realtimeOnlyCirculations = realTimeEstimates.Select(estimate => new ConsolidatedCirculation
{
Line = estimate.Line,
Route = estimate.Route,
Schedule = null,
RealTime = new RealTimeData
{
Minutes = estimate.Minutes,
Distance = estimate.Meters
}
}).OrderBy(c => c.RealTime!.Minutes).ToList();
return Ok(realtimeOnlyCirculations);
}
var timetable = timetableTask.Result.Arrivals
.Where(c => c.StartingDateTime(nowLocal.Date) != null && c.CallingDateTime(nowLocal.Date) != null)
.ToList();
var stopLocation = timetableTask.Result.Location;
var now = nowLocal.AddSeconds(60 - nowLocal.Second);
// Define the scope end as the time of the last realtime arrival (no extra buffer)
var scopeEnd = realTimeEstimates.Count > 0
? now.AddMinutes(Math.Min(realTimeEstimates.Max(e => e.Minutes) + 5, 75))
: now.AddMinutes(60); // If no estimates, show next hour of scheduled only
List<ConsolidatedCirculation> consolidatedCirculations = [];
var usedTripIds = new HashSet<string>();
foreach (var estimate in realTimeEstimates)
{
var estimatedArrivalTime = now.AddMinutes(estimate.Minutes);
var possibleCirculations = timetable
.Where(c =>
{
// Match by line number
if (c.Line.Trim() != estimate.Line.Trim())
return false;
// Match by route (destination) - compare with both Route field and Terminus stop name
// Normalize both sides: remove non-ASCII-alnum characters and lowercase
var estimateRoute = NormalizeRouteName(estimate.Route);
var scheduleRoute = NormalizeRouteName(c.Route);
var scheduleTerminus = NormalizeRouteName(c.TerminusName);
return scheduleRoute == estimateRoute || scheduleTerminus == estimateRoute;
})
.OrderBy(c => c.CallingDateTime(nowLocal.Date)!.Value)
.ToArray();
ScheduledArrival? closestCirculation = null;
// Matching strategy:
// 1) Filter trips that are not "too early" (TimeDiff <= 7).
// TimeDiff = Schedule - Realtime.
// If TimeDiff > 7, bus is > 7 mins early. Reject.
// 2) From the valid trips, pick the one with smallest Abs(TimeDiff).
// This handles "as late as it gets" (large negative TimeDiff) by preferring smaller delays if available,
// but accepting large delays if that's the only option (and better than an invalid early trip).
const int maxEarlyArrivalMinutes = 7;
var bestMatch = possibleCirculations
.Select(c => new
{
Circulation = c,
TimeDiff = (c.CallingDateTime(nowLocal.Date)!.Value - estimatedArrivalTime).TotalMinutes
})
.Where(x => x.TimeDiff <= maxEarlyArrivalMinutes)
.OrderBy(x => Math.Abs(x.TimeDiff))
.FirstOrDefault();
if (bestMatch != null)
{
closestCirculation = bestMatch.Circulation;
}
if (closestCirculation == null)
{
// No scheduled match: include realtime-only entry
_logger.LogWarning("No schedule match for realtime line {Line} towards {Route} in {Minutes} minutes (tried matching {NormalizedRoute})", estimate.Line, estimate.Route, estimate.Minutes, NormalizeRouteName(estimate.Route));
consolidatedCirculations.Add(new ConsolidatedCirculation
{
Line = estimate.Line,
Route = estimate.Route,
Schedule = null,
RealTime = new RealTimeData
{
Minutes = estimate.Minutes,
Distance = estimate.Meters
}
});
continue;
}
// Ensure each scheduled trip is only matched once to a realtime estimate
if (usedTripIds.Contains(closestCirculation.TripId))
{
_logger.LogInformation("Skipping duplicate realtime match for TripId {TripId}", closestCirculation.TripId);
continue;
}
var isRunning = closestCirculation.StartingDateTime(nowLocal.Date)!.Value <= now;
Position? currentPosition = null;
int? stopShapeIndex = null;
bool usePreviousShape = false;
// Calculate bus position for realtime trips
if (!string.IsNullOrEmpty(closestCirculation.ShapeId))
{
// Check if we are likely on the previous trip
// If the bus is further away than the distance from the start of the trip to the stop,
// it implies the bus is on the previous trip (or earlier).
double distOnPrevTrip = estimate.Meters - closestCirculation.ShapeDistTraveled;
usePreviousShape = !isRunning &&
!string.IsNullOrEmpty(closestCirculation.PreviousTripShapeId) &&
distOnPrevTrip > 0;
if (usePreviousShape)
{
var prevShape = await _shapeService.LoadShapeAsync(closestCirculation.PreviousTripShapeId);
if (prevShape != null && prevShape.Points.Count > 0)
{
// The bus is on the previous trip.
// We treat the end of the previous shape as the "stop" for the purpose of calculation.
// The distance to traverse backwards from the end of the previous shape is 'distOnPrevTrip'.
var lastPoint = prevShape.Points[prevShape.Points.Count - 1];
var result = _shapeService.GetBusPosition(prevShape, lastPoint, (int)distOnPrevTrip);
currentPosition = result.BusPosition;
stopShapeIndex = result.StopIndex;
}
}
else
{
// Normal case: bus is on the current trip shape
var shape = await _shapeService.LoadShapeAsync(closestCirculation.ShapeId);
if (shape != null && stopLocation != null)
{
var result = _shapeService.GetBusPosition(shape, stopLocation, estimate.Meters);
currentPosition = result.BusPosition;
stopShapeIndex = result.StopIndex;
}
}
}
consolidatedCirculations.Add(new ConsolidatedCirculation
{
Line = estimate.Line,
Route = estimate.Route == closestCirculation.TerminusName ? closestCirculation.Route : estimate.Route,
NextStreets = [.. closestCirculation.NextStreets],
Schedule = new ScheduleData
{
Running = isRunning,
Minutes = (int)(closestCirculation.CallingDateTime(nowLocal.Date)!.Value - now).TotalMinutes,
TripId = closestCirculation.TripId,
ServiceId = closestCirculation.ServiceId,
ShapeId = closestCirculation.ShapeId,
},
RealTime = new RealTimeData
{
Minutes = estimate.Minutes,
Distance = estimate.Meters
},
CurrentPosition = currentPosition,
StopShapeIndex = stopShapeIndex,
IsPreviousTrip = usePreviousShape,
PreviousTripShapeId = usePreviousShape ? closestCirculation.PreviousTripShapeId : null
});
usedTripIds.Add(closestCirculation.TripId);
}
// Add scheduled-only circulations between now and the last realtime arrival
if (scopeEnd > now)
{
var matchedTripIds = new HashSet<string>(usedTripIds);
var scheduledWindow = timetable
.Where(c => c.CallingDateTime(nowLocal.Date)!.Value >= now && c.CallingDateTime(nowLocal.Date)!.Value <= scopeEnd)
.OrderBy(c => c.CallingDateTime(nowLocal.Date)!.Value);
foreach (var sched in scheduledWindow)
{
if (matchedTripIds.Contains(sched.TripId))
{
continue; // already represented via a matched realtime
}
var minutes = (int)(sched.CallingDateTime(nowLocal.Date)!.Value - now).TotalMinutes;
if (minutes == 0)
{
continue;
}
consolidatedCirculations.Add(new ConsolidatedCirculation
{
Line = sched.Line,
Route = sched.Route,
Schedule = new ScheduleData
{
Running = sched.StartingDateTime(nowLocal.Date)!.Value <= now,
Minutes = minutes,
TripId = sched.TripId,
ServiceId = sched.ServiceId,
ShapeId = sched.ShapeId,
},
RealTime = null
});
}
}
// Sort by ETA (RealTime minutes if present; otherwise Schedule minutes)
var sorted = consolidatedCirculations
.OrderBy(c => c.RealTime?.Minutes ?? c.Schedule!.Minutes)
.Select(LineFormatterService.Format)
.ToList();
return Ok(sorted);
}
private async Task<StopArrivals?> LoadStopArrivalsProto(string stopId, string dateString)
{
var file = Path.Combine(_configuration.ScheduleBasePath, dateString, stopId + ".pb");
if (!SysFile.Exists(file))
{
_logger.LogWarning("Stop arrivals proto file not found: {File}", file);
return null;
}
var contents = await SysFile.ReadAllBytesAsync(file);
var stopArrivals = StopArrivals.Parser.ParseFrom(contents);
return stopArrivals;
}
private async Task<Shape> LoadShapeProto(string shapeId)
{
var file = Path.Combine(_configuration.ScheduleBasePath, shapeId + ".pb");
if (!SysFile.Exists(file))
{
throw new FileNotFoundException();
}
var contents = await SysFile.ReadAllBytesAsync(file);
var shape = Shape.Parser.ParseFrom(contents);
return shape;
}
private static string NormalizeRouteName(string route)
{
var normalized = route.Trim().ToLowerInvariant();
// Remove diacritics/accents first, then filter to alphanumeric
normalized = RemoveDiacritics(normalized);
return new string(normalized.Where(char.IsLetterOrDigit).ToArray());
}
private static string RemoveDiacritics(string text)
{
var normalizedString = text.Normalize(NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
foreach (var c in normalizedString)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
if (unicodeCategory != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
}
public static class StopScheduleExtensions
{
public static DateTime? StartingDateTime(this ScheduledArrival stop, DateTime baseDate)
{
return ParseGtfsTime(stop.StartingTime, baseDate);
}
public static DateTime? CallingDateTime(this ScheduledArrival stop, DateTime baseDate)
{
return ParseGtfsTime(stop.CallingTime, baseDate);
}
/// <summary>
/// Parse GTFS time format (HH:MM:SS) which can have hours >= 24 for services past midnight
/// </summary>
private static DateTime? ParseGtfsTime(string timeStr, DateTime baseDate)
{
if (string.IsNullOrWhiteSpace(timeStr))
{
return null;
}
var parts = timeStr.Split(':');
if (parts.Length != 3)
{
return null;
}
if (!int.TryParse(parts[0], out var hours) ||
!int.TryParse(parts[1], out var minutes) ||
!int.TryParse(parts[2], out var seconds))
{
return null;
}
// Handle GTFS times that exceed 24 hours (e.g., 25:30:00 for 1:30 AM next day)
var days = hours / 24;
var normalizedHours = hours % 24;
try
{
var dt = baseDate
.AddDays(days)
.AddHours(normalizedHours)
.AddMinutes(minutes)
.AddSeconds(seconds);
return dt.AddSeconds(60 - dt.Second);
}
catch
{
return null;
}
}
}
|