brussels_stib_mivb_updates.lua 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. -- SPDX-FileCopyrightText: Adam Evyčędo
  2. --
  3. -- SPDX-License-Identifier: AGPL-3.0-or-later
  4. function getUpdates(tripID, sequence, stopID, stopCode)
  5. local http = require("http")
  6. local json = require("json")
  7. error_struct = {
  8. httpResponseCode=0,
  9. message="",
  10. willNextRequestFail=false
  11. }
  12. response, error_message = http.get("https://stibmivb.opendatasoft.com/api/explore/v2.1/catalog/datasets/waiting-time-rt-production/records", {
  13. query="apikey={{.ApiKey}}&where=pointid%20%3D%20%22" .. stopID .. "%22&limit=20",
  14. timeout="30s"
  15. })
  16. if response == nil then
  17. error_struct.message = "while getting updates: " .. error_message
  18. error_json, _ = json.encode(error_struct)
  19. return "", error_json
  20. end
  21. if response.status_code ~= 200 then
  22. error_struct.message = "api returned code " .. response.status_code .. "; " .. response.body
  23. error_struct.httpResponseCode = response.status_code
  24. error_struct.willNextRequestFail = true
  25. error_json, _ = json.encode(error_struct)
  26. return "", error_json
  27. end
  28. struct, error_message = json.decode(response.body)
  29. if struct == nil then
  30. error_struct.message = "while decoding updates: " .. error_message
  31. error_json, _ = json.encode(error_struct)
  32. return "", error_json
  33. end
  34. updates = {
  35. areTripsInTimetable=false,
  36. updates={}
  37. }
  38. updates.updates[''] = {
  39. time="000000",
  40. stopID=stopID,
  41. delay=0,
  42. timetableRelationship=1,
  43. vehicleStatus={
  44. lineName="",
  45. headsign=""
  46. }
  47. }
  48. for i,entry in ipairs(struct.results) do
  49. times, error_message = json.decode(entry.passingtimes)
  50. if times == nil then
  51. error_struct.message = "while decoding times for stop " .. entry.pointid .. ", line " .. entry.lineid .. ": " .. error_message
  52. error_json, _ = json.encode(error_struct)
  53. return "", error_json
  54. end
  55. for i, time_entry in ipairs(times) do
  56. if time_entry.destination ~= nil then
  57. updates.updates[time_entry.expectedArrivalTime] = {
  58. time=string.sub(time_entry.expectedArrivalTime, 12, 13) .. string.sub(time_entry.expectedArrivalTime, 15, 16) .. string.sub(time_entry.expectedArrivalTime, 18, 19),
  59. stopID=stopID,
  60. delay=0,
  61. timetableRelationship=1,
  62. vehicleStatus={
  63. lineName=entry.lineid,
  64. headsign=time_entry.destination.fr
  65. }
  66. }
  67. end
  68. end
  69. end
  70. result, error_message = json.encode(updates)
  71. if result == nil then
  72. error_struct.message = "while encoding result: " .. error_message
  73. error_json, _ = json.encode(error_struct)
  74. return "", error_json
  75. end
  76. return result, ""
  77. end