Cale-Torino / Takcar

A small PHP script to take the lat & lon from Traccar and pipe them into the FreeTakServer.
MIT License
4 stars 0 forks source link

Display Traccar Device Name in TAK #1

Closed cookm678 closed 2 years ago

cookm678 commented 2 years ago

Great scripts and just what i've been looking for thanks. I'm not familiar with php scripting and would like to know a way to query Traccar for Devices and Positions using the API and then cross reference the two results before passing to the FreeTAKServer. In the Positions results, each device is referenced by 'deviceID'. This equates to the id field in the Devices query. In the example below, deviceID=4. I therefore want to return the name from id = 4 in the devices list.

Positions

http://:8082/api/positions?token=QsG { "id": 317351, "attributes": { "distance": 1.11, "totalDistance": 13685, "motion": false }, "deviceId": 4, "type": null, "protocol": "taip", "serverTime": "2022-01-14T16:57:14.267+00:00", "deviceTime": "2022-01-14T16:57:32.000+00:00", "fixTime": "2022-01-14T16:57:32.000+00:00", "outdated": false, "valid": true, "latitude": 52., "longitude": 0., "altitude": 0, "speed": 0, "course": 0, "address": null, "accuracy": 0, "network": null },

Devices

http://:8082/api/devices?token=QsG { "id": 4, "attributes": {}, "groupId": 1, "name": "MyName", "uniqueId": "MyID", "status": "online", "lastUpdate": "2022-01-14T17:00:14.268+00:00", "positionId": 317365, "geofenceIds": [], "phone": "", "model": "", "contact": "", "category": null, "disabled": false },

I want to run both queries and then send the Position details with the Name from the Devices list to the FreeTAKServer.

$postData = array( "uid" => $guid, "how" => "nonCoT", "name" => DeviceNamefromDeviceList, "longitude" => $longitude, "latitude" => $latitude, "role" => "Team Member", "team" => "<?php echo$Team;?>" );

Any help gratefully received.

Mark

Cale-Torino commented 2 years ago

In PHP you can run a nested foreach loop. By doing this you can get the id, lat, lon via the api/positions endpoint then use the ID to match the ID of api/devices if the match is true then get the name.

//Similar to this code as an example off the top of my head


$jdevices = json_decode($devices_endpoint);

$jpositions = json_decode($positions_endpoint);

foreach($jpositions as $key => $pitem){
  foreach($jdevices as $key => $ditem){
    if($pitem->id == $ditem->id)
    {
       echo "Name=".$ditem->name".ID=".$pitem->id."Lon=".$pitem->lon."Lat=".$pitem->lat;
     }
   }
}

You can also match the IDs via an array instead of a nested foreach loop.

Traccar API doc https://www.traccar.org/api-reference/#tag/Positions/paths/~1positions/get

cookm678 commented 2 years ago

Thanks for your help. I've amended the script and am now getting the following HTTP POST Internal Server Error: strict-origin-when-cross-origin

Here is the serverUpdater.php script i'm using. Maybe i've done something wrong.

`<?php //include config include_once("config.php");

//get the session cookie $session = json_encode(get_TraccarSession("$TraccarProtocol://$TraccarIP:$TraccarPort/api/session?token=$TraccarAPIToken"));

$api_result = json_decode($session, true); $JSESSIONID = $api_result['JSESSIONID'];

//get the Traccar devices $devicelist = get_TraccarDevices("$TraccarProtocol://$TraccarIP:$TraccarPort/api/devices?token=$TraccarAPIToken", $JSESSIONID);

//get the Traccar positions $positions = get_TraccarPosition("$TraccarProtocol://$TraccarIP:$TraccarPort/api/positions?token=$TraccarAPIToken", $JSESSIONID);

$jdevices = json_decode($devicelist); $jpositions = json_decode($positions);

//loop through the positions foreach($jpositions as $key => $pitem){ foreach($jdevices as $key => $ditem){ if($pitem->deviceId == $ditem->id){ //forward the positions to the FTS API endpoint $result = put_FTSAPI($ditem->name, $pitem->latitude, $pitem->longitude, $FTSProtocol, $FTSIP, $FTSAPIPort, $FTSAPIToken); else { //forward the positions to the FTS FTS API endpoint $result = put_FTSAPI($pitem->deviceId, $pitem->latitude, $pitem->longitude, $FTSProtocol, $FTSIP, $FTSAPIPort, $FTSAPIToken); $devices[] = $item->Id; } } } $markers[] = json_encode( array( 'result' => 0, 'guid' => $result, 'time' => date("Y-m-d h:i:sa") ) ); }

$JSON = json_encode( array( 'result' => 0, 'message' => $markers, 'time' => date("Y-m-d h:i:sa"), ) ); //return the JSON results echo '{"result":0,"euds":['.$JSON.']}'; flush(); die();

function get_TraccarSession($url) { file_get_contents($url);

$cookies = array();
//search for all cookies and return; we only need `JSESSIONID`
foreach ($http_response_header as $hdr) {
    if (preg_match('/^Set-Cookie:\s*([^;]+)/', $hdr, $matches)) {
        parse_str($matches[1], $tmp);
        $cookies += $tmp;
    }
}
return $cookies;

}

function get_TraccarDevices($url,$JSESSIONID) { //set the headers and cookie $opts = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "Cookie: JSESSIONID=$JSESSIONID\r\n" ) );

// Open the file using the HTTP headers set above $file = file_get_contents($url, false, stream_context_create($opts)); return $file; }

function get_TraccarPosition($url,$JSESSIONID) { //set the headers and cookie $opts = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "Cookie: JSESSIONID=$JSESSIONID\r\n" ) );

// Open the file using the HTTP headers set above $file = file_get_contents($url, false, stream_context_create($opts)); return $file; }

function put_FTSAPI($deviceId, $latitude, $longitude, $FTSProtocol, $FTSIP, $FTSAPIPort, $FTSAPIToken) {

//Json data to post
$postData = array(
    "uid" => $deviceId,
    "how" => "nonCoT",
    "name" => "ID_".$deviceId,
    "longitude" => $longitude,
    "latitude" => $latitude,
    "geoObject" => "Vehicle",
    "attitude" => "suspect"
);

$ch = curl_init("$FTSProtocol://$FTSIP:$FTSAPIPort/ManageGeoObject/postGeoObject");
//set cURL options
curl_setopt(
    $ch, 
    CURLOPT_HTTPHEADER, 
    array(
        'Content-Type: application/json',
        'Authorization: '.$FTSAPIToken
    )
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
//execute cURL call
$result = curl_exec($ch);
curl_close($ch);

return $result;

}

?>`

Cale-Torino commented 2 years ago

The code was just an example it won't work if copy pasted. I'll add the names to a new version later this week.

cookm678 commented 2 years ago

I didn't copy and paste. I amended the code as above so that the variables matched those in the other code. I think the error i am getting is because i opened a second session when i should've used only one session id. I'll amend my code and report back.

Thanks for your assistance.

Cale-Torino commented 2 years ago

I updated the script to show the name of the Traccar devices.

https://github.com/Cale-Torino/Takcar/releases/tag/V1.0.0.5

cookm678 commented 2 years ago

Thanks Cale. I'll give it a try.

Cale-Torino commented 2 years ago

Closed