berlin_vbb_vehicles.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. -- SPDX-FileCopyrightText: Adam Evyčędo
  2. --
  3. -- SPDX-License-Identifier: AGPL-3.0-or-later
  4. ---@diagnostic disable-next-line: lowercase-global
  5. function getVehicles(north, west, south, east)
  6. local http = require("http")
  7. local json = require("json")
  8. local error_struct = {
  9. httpResponseCode=0,
  10. message="",
  11. willNextRequestFail=false
  12. }
  13. local response, error_message = http.get("https://v6.vbb.transport.rest/radar", {
  14. query="north=" .. north .. "&west=".. west .. "&south=".. south .. "&east=" .. east .."&polylines=false&frames=0&pretty=false",
  15. timeout="30s"
  16. })
  17. if response == nil then
  18. error_struct.message = "while getting vehicles: " .. error_message
  19. local error_json, _ = json.encode(error_struct)
  20. return "", error_json
  21. end
  22. if response.status_code ~= 200 then
  23. error_struct.message = "api returned code " .. response.status_code .. "; " .. response.body
  24. error_struct.httpResponseCode = response.status_code
  25. error_struct.willNextRequestFail = true
  26. local error_json, _ = json.encode(error_struct)
  27. return "", error_json
  28. end
  29. ---@diagnostic disable-next-line: redefined-local
  30. local struct, error_message = json.decode(response.body)
  31. if struct == nil then
  32. error_struct.message = "while decoding vehicles: " .. error_message
  33. local error_json, _ = json.encode(error_struct)
  34. return "", error_json
  35. end
  36. local updates = {}
  37. updates[''] = {
  38. vehicleID="",
  39. latitude=0,
  40. longitude=0,
  41. speed=0,
  42. bearing=0,
  43. lineID="",
  44. headsign="",
  45. tripID="",
  46. }
  47. for _, entry in ipairs(struct.movements) do
  48. updates[entry.tripId] = {
  49. headsign=entry.direction,
  50. lineID=entry.line.id,
  51. latitude=entry.location.latitude,
  52. longitude=entry.location.longitude
  53. }
  54. end
  55. ---@diagnostic disable-next-line: redefined-local
  56. local result, error_message = json.encode(updates)
  57. if result == nil then
  58. error_struct.message = "while encoding result: " .. error_message
  59. local error_json, _ = json.encode(error_struct)
  60. return "", error_json
  61. end
  62. return result, ""
  63. end