get trip function

This commit is contained in:
Luiz Costa 2023-11-15 10:31:58 +00:00
parent 1f3dec4afc
commit c0978a63e7

View File

@ -1,7 +1,7 @@
from datetime import datetime
import frappe
import requests
from requests.auth import HTTPBasicAuth
def traccar_auth(ts):
"""authenticates on traccar server and returns cookies"""
@ -21,6 +21,7 @@ def traccar_auth(ts):
else:
frappe.throw(f"Authentication failed: {response.status_code}: {response.reason}<br />Dict ts: {ts.as_dict()}")
@frappe.whitelist()
def get_devices(doc=None):
"""fetches all devices the user has access to and stores them in Tracker Doctype
@ -64,5 +65,45 @@ def get_devices(doc=None):
def get_trips_for_device(device, start = None, end = None):
"""getches all trip for a device, stores them Trip Doctype and links them to the vehicle which is assigned to the device"""
pass
# get informations for authentication on traccar server
ts = frappe.get_last_doc('TraccarServer')
# get all trips from traccar server
try:
trips = requests.get(
f"http://{ts.traccar_server}:{ts.traccar_port}/api/reports/trips",
cookies = traccar_auth(ts),
params = {
'deviceId': device,
'from': start,
'to': end
}
)
except:
frappe.throw("Could not fetch trips from traccar server")
# Insert trips into Trip Doctype
for trip in trips.json():
if not frappe.db.exists('Trip', trip['id']):
frappe.get_doc({
'doctype': 'Trip',
'portal_id': trip['id'],
'device_id': trip['deviceId'],
'start': datetime.fromisoformat(trip['startTime']).strftime('%Y-%m-%d %H:%M:%S'),
'end': datetime.fromisoformat(trip['endTime']).strftime('%Y-%m-%d %H:%M:%S'),
'distance': trip['distance'],
'average_speed': trip['averageSpeed'],
'max_speed': trip['maxSpeed'],
'spent_fuel': trip['spentFuel'],
'start_address': trip['startAddress'],
'end_address': trip['endAddress'],
'duration': trip['duration'],
'driver_unique_id': trip['driverUniqueId'],
'vehicle': frappe.get_value('Tracker', trip['deviceId'], 'vehicle'),
}).insert()
# update db frappe
frappe.db.commit()