import requests import time import schedule last_known_location = { "lat": 0, "lon": 0} last_data_age = time.time() def query_ice_portal(): response = requests.get("https://iceportal.de/api1/rs/status") if response.status_code == 200: return response.json() else: return None def send_location(location_data): # Define the Traccar server URL traccar_url = "https://tracar.example.org" currentTime = time.time() # # format the time to the required format formattedTime = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(currentTime)) location_data["time"] = formattedTime # Make the HTTP request response = requests.get(traccar_url, params=location_data) # Check the response status code if response.status_code == 200: print("Location sent to Traccar server") else: # If the request was not successful, print the error message print("Error sending location: " + response.text) def update_train_locations(): global last_data_age, last_known_location # Create an instance of the custom device handler info = query_ice_portal() # Check if the response is not None if info is not None: # Check if the location has changed using the last known location if info["latitude"] == last_known_location["lat"] and info["longitude"] == last_known_location["lon"]: print("No new location data available") return # Update the last known location last_known_location["lat"] = info["latitude"] last_known_location["lon"] = info["longitude"] print(f'Last location update was {time.time() - last_data_age} seconds ago') print(info) location_data = { "id": "identifieryGoesHere", "lat": info["latitude"], "lon": info["longitude"], "valid": True, "speed": (info["speed"] / 1.875), # Speed in knots "timeSinceUpdate": time.time() - last_data_age, } send_location(location_data) last_data_age = time.time() update_train_locations() schedule.every(2).seconds.do(update_train_locations) # Run the scheduled task while True: schedule.run_pending() time.sleep(1)