Files
traccar_animation/test_traccar_trip.py

80 lines
3.2 KiB
Python

import requests
def get_positions(server_url, token, device_id=None, from_time=None, to_time=None):
"""
Fetch position information from the Traccar server.
Args:
server_url (str): The URL of the Traccar server.
token (str): The authentication token.
device_id (int, optional): The ID of the device. If not provided, fetches positions for all devices.
from_time (str, optional): The start time in ISO 8601 format (e.g., '2024-04-05T00:00:00Z').
to_time (str, optional): The end time in ISO 8601 format (e.g., '2024-04-05T23:59:59Z').
Returns:
list: The position information.
"""
# Ensure the server_url has a valid scheme
if not server_url.startswith("http://") and not server_url.startswith("https://"):
server_url = f"https://{server_url}" # Default to https:// if no scheme is provided
# Set the Authorization header with the token
headers = {"Authorization": f"Bearer {token}"}
# API endpoint for fetching positions
url = f"{server_url}/positions"
# Request payload
payload = {}
if device_id:
payload["deviceId"] = device_id
if from_time and to_time:
payload["from"] = from_time
payload["to"] = to_time
try:
# Log the payload for debugging
print(f"Request Payload: {payload}")
# Make the API request
response = requests.get(url, params=payload, headers=headers)
# Log the response status and content for debugging
print(f"Response Status Code: {response.status_code}")
print(f"Response Content: {response.text}")
# Check if the response was successful
if response.status_code == 200:
positions = response.json()
print(f"Retrieved {len(positions)} positions:")
for position in positions:
print(position)
return positions
elif response.status_code == 400:
print("Bad Request: Please check the request payload and token.")
return None
else:
print(f"Failed to fetch positions: {response.status_code} - {response.reason}")
return None
except requests.exceptions.RequestException as e:
print(f"Error fetching positions: {str(e)}")
return None
# Test the function
if __name__ == "__main__":
# Manually enter the server URL and token
server_url = "https://gps.moto-adv.com/api"
token = "RjBEAiB69jflCQJ9HQwGyFdAHF8J5JPMwIIclglbWiKMWeX6PwIgdBWc-YllE_-RwoQi7zX25WxQJqQX_OTIKOHk9a3mmBN7InUiOjEsImUiOiIyMDI1LTA2LTA4VDIxOjAwOjAwLjAwMCswMDowMCJ9"
# Optional: Enter device ID and date range
device_id = input("Enter the device ID (leave blank for all devices): ").strip()
device_id = int(device_id) if device_id else None
from_time = input("Enter the start time (ISO 8601, e.g., 2024-04-05T00:00:00Z, leave blank for none): ").strip()
to_time = input("Enter the end time (ISO 8601, e.g., 2024-04-05T23:59:59Z, leave blank for none): ").strip()
positions = get_positions(server_url, token, device_id, from_time, to_time)
if positions:
print("Position data retrieved successfully!")
else:
print("No position data found or an error occurred.")