mirror of
https://github.com/itsdave-de/fusionpbx_connect.git
synced 2025-05-06 15:45:15 +02:00
121 lines
4.5 KiB
Python
121 lines
4.5 KiB
Python
from datetime import datetime
|
|
import frappe
|
|
import requests
|
|
|
|
|
|
def traccar_auth(ts):
|
|
"""authenticates on traccar server and returns cookies"""
|
|
response = requests.post(
|
|
f"http://{ts.traccar_server}:{ts.traccar_port}/api/session",
|
|
data = {
|
|
'email': ts.traccar_username,
|
|
'password': frappe.utils.password.get_decrypted_password(
|
|
'Traccar Settings',
|
|
ts.name,
|
|
'traccar_password'
|
|
)
|
|
}
|
|
)
|
|
if response.status_code == 200:
|
|
return response.cookies
|
|
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
|
|
should also be able to be called frequently to update the status"""
|
|
|
|
# get informations for authentication on traccar server
|
|
ts = frappe.get_doc('Traccar Settings')
|
|
|
|
# get all devices from traccar server
|
|
try:
|
|
devices = requests.get(
|
|
f"http://{ts.traccar_server}:{ts.traccar_port}/api/devices",
|
|
cookies = traccar_auth(ts)
|
|
)
|
|
except:
|
|
frappe.throw("Could not fetch devices from traccar server")
|
|
|
|
# Insert devices into Tracker Doctype
|
|
for dev in devices.json():
|
|
if not frappe.db.exists('Tracker', int(dev['id'])):
|
|
frappe.get_doc({
|
|
'doctype': 'Tracker',
|
|
'portal_id': dev['id'],
|
|
'portal_name': dev['name'],
|
|
'unique_id': dev['uniqueId'],
|
|
'status': dev['status'],
|
|
'last_update': datetime.fromisoformat(dev['lastUpdate']).strftime('%Y-%m-%d %H:%M:%S'),
|
|
'position_id': dev['positionId'],
|
|
'group_id': dev['groupId'],
|
|
'phone': dev['phone'],
|
|
'model': dev['model'],
|
|
'contact': dev['contact'],
|
|
'categorie': dev['category'],
|
|
'disabled': dev['disabled'],
|
|
}).insert()
|
|
|
|
# update db frappe
|
|
frappe.db.commit()
|
|
|
|
|
|
@frappe.whitelist()
|
|
def get_trips_for_device(device_id, start=None, end=None):
|
|
"""
|
|
Fetches all trips for a device, stores them in Trip Doctype, and links them to the vehicle assigned to the device.
|
|
"""
|
|
# get information for authentication on traccar server
|
|
ts = frappe.get_doc('Traccar Settings')
|
|
|
|
# Define default start and end datetime if not provided
|
|
if not start:
|
|
start = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') # Adjust format as required by your Traccar API
|
|
if not end:
|
|
end = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') # Adjust format as required by your Traccar API
|
|
|
|
# get all trips from traccar server
|
|
try:
|
|
trips_response = requests.get(
|
|
f"http://{ts.traccar_server}:{ts.traccar_port}/api/reports/trips",
|
|
cookies=traccar_auth(ts),
|
|
params={
|
|
'deviceId': device_id,
|
|
'from': start,
|
|
'to': end
|
|
}
|
|
)
|
|
trips_response.raise_for_status() # This will raise an error for HTTP error codes
|
|
except requests.HTTPError as e:
|
|
frappe.throw(f"HTTP error occurred: {e}")
|
|
except Exception as e:
|
|
frappe.throw(f"Error fetching trips: {e}")
|
|
|
|
# Insert trips into Trip Doctype
|
|
for trip in trips_response.json():
|
|
# Assuming 'id' is unique identifier for the trip from Traccar API response
|
|
if not frappe.db.exists('Trip', {'portal_id': trip['id']}):
|
|
trip_doc = 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')
|
|
})
|
|
trip_doc.insert(ignore_permissions=True) # Use ignore_permissions if needed
|
|
|
|
# commit the transaction
|
|
frappe.db.commit()
|
|
|