Positions API String

CCPlusIT 9 years ago

I am using $positions=traccar::positions($deviceId,$from,$to,$cookie); to get the positions and using $positions->response get returned a data as below.

object(stdClass)[2]
  public 'responseCode' => int 200
  public 'error' => string '' (length=0)
  public 'response' => string 'accuracy;address;altitude;course;deviceId;deviceTime;fixTime;id;latitude;longitude;network;outdated;protocol;serverTime;speed;type;valid;attributes;
0.0;null;99.0;0.0;32;2017-04-03T03:15:34.000+01:00;2017-04-03T03:15:34.000+01:00;240604;55.130898;1.630918;false;watch;2017-04-03T03:15:49.000+01:00;0.0299676;null;false;sat:0 rssi:60 battery:40 steps:0 ip:208.80.156.8 distance:207568.79 totalDistance:2.935494597E7;
0.0;Oakdale, England, GB;2.0;0.0;32;2017-04-03T03:15:59.000+01:00;2017-04-03T03:15:59.000+01:0'... (length=12440)

My question is how can I pull data from this response string like latitude or longitude, I was expecting an array or json.

Anton Tananaev 9 years ago

You have to provide "Accept: application/json" header in the request. Otherwise it would return random format. In your case it's CSV.

CCPlusIT 9 years ago

Thank you, obvious really looking at code to long :-)

CCPlusIT 9 years ago

I am trying to use code below to get positions and I can use same ajax code format for get devices ok, but with positions I just get 400 Bad Request NullPointerException (... < DateUtil:65 < PositionResource:80 < ...)

What am I missing?

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>try traccar api</title>
  </head>
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js" charset="utf-8"></script>
    <script type="text/javascript">

	  var deviceId = "32";
	  var from = "2017-04-01";
	  var to = "2017-04-05";
	  
      $.ajax({
        type: 'GET',
        url: 'http://xxx.xx.xxx.xx:8082/api/positions/',
        headers: {
            "Authorization": "Basic " + btoa("admin@xxxxxxx.com:jxxxxxx5")
        },
		
		contentType:"application/json",
        data:JSON.stringify({			
        deviceId:deviceId,
        from:from,
	to:to
        }),
		
        success: function (response) {
            console.log(response);
        }
      });
    </script>
  </body>
</html>
Anton Tananaev 9 years ago

I already explained what you are missing. I still don't see "Accept" header anywhere in your code.

CCPlusIT 9 years ago

I have managed to get the positions in the correct format with using ajax, but still face the same issue with cURL being returned as csv. Using the same script I am able to get devices as json but positions will not. Below is script I have implemented taken from one of the blog posts. I just cannot work out why it will not return as json data and only returns csv.

I thank you in advance for your time and patients.

Screen shot returned consul data. https://www.screencast.com/t/drgsJDGnsMF

Script used below:

<!doctype html>
<html>
<head>
<meta charset="utf-8">

<title>Location</title>
</head>

<body>
<?php
$email=$_GET['email'];
$password=$_GET['password'];

class traccar {
	
    public static $host='http://xxx.xx.xxx.xx:8082';
    public static $cookie;
    private static $urlencoded='Content-Type: application/x-www-form-urlencoded';
    
     public static function login($email,$password) {
        $data='email='.$email.'&password='.$password;
        return self::curl('/api/session','POST','',$data,array(self::$urlencoded));
    }   
    
    public static function getdevices($deviceId,$userId,$alldevices,$cookie) {
        $data='deviceId='.$deviceId.'&all='.$alldevices.'&userId='.$userId;
        return self::curl('/api/devices?'.$data,'GET',$cookie ,'',array());
    } 
	 
	 public static function positions($deviceId,$from,$to,$cookie) {
        $data='deviceId='.$deviceId.'&from='.$from.'&to='.$to;
        return self::curl('/api/positions?'.$data,'GET',$cookie ,'',array());
    }
      
    public static function curl($task,$method,$cookie,$data,$header) {
        $res=new stdClass();
        $res->responseCode='';
        $res->error='';
		
	$header[]="Cookie: ".$cookie;  		
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::$host.$task);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HEADER, 1);	
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        if($method=='POST' || $method=='PUT' || $method=='DELETE') {
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
	curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        $data=curl_exec($ch);
        var_dump($data);
        $size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', substr($data, 0, $size), $c) == 1) self::$cookie = $c[1];
        $res->response = substr($data, $size);
        if(!curl_errno($ch)) {
        $res->responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        }
        else
		{
        $res->responseCode=400;
        $res->error= curl_error($ch);   
        }
        curl_close($ch);
        return $res;
        echo $res;
    }
}

$t=traccar::login($email,$password);		
    
    if($t->responseCode=='200') {
	$traccarCookie = traccar::$cookie;
    $cookie=$traccarCookie;
	
	$deviceId="32";
	$userId="";
	$alldevices="1";
    $from="2017-04-03";
    $to="2017-04-04";

$devices=traccar::getdevices($deviceId,$userId,$alldevices,$cookie);
echo '<pre>' . print_r( $devices->response, TRUE ) . '</pre>';

$positions=traccar::positions($deviceId,$from,$to,$cookie);
echo '<pre>' . print_r( $positions->response, TRUE ) . '</pre>';
 
}
?>

</body>
</html>
Anton Tananaev 9 years ago

It seems like you are completely ignoring my messages. Why are you even asking on the forum if you are not planning to listen to the answers?

CCPlusIT 9 years ago

I am not ignoring your answer I am trying to understand why it works ok with get device as json but not positions I would have presumed If accept was not included it would also get devices returned as CSV and not as JSON.

Anton Tananaev 9 years ago

If you don't explicitly provide "Accept" header, the result is undefined. You will randomly get JSON or CSV.

CCPlusIT 9 years ago

Thank you for clarification I did not realise it was a random return.