Sample PHP server code for receiving Btraced GPS

Forum / topics about Btraced protocol and webservice (uploading gps data) Also Btraced sample code.

Sample PHP server code for receiving Btraced GPS

Postby Btraced » Mon Apr 16, 2012 9:20 am

Below is a working PHP server sample file which stores all received Btraced datapoints in a Mysql database.
this code is very easy to read and shows exactly how the XML is handled

Code: Select all
<?php

// DB Info
$hostname = 'localhost';
$data = "databasename";
$username = "sql_username";
$password = "sql_password";

// Try to connect to the database, if fail, then send a JSON message
// to Btraced to report the error. Messages with ID over 900 are for custom messages
$conexion = mysql_connect($hostname, $username, $password) or die('{ "id":900, "error":true, "message":"Cant connect database", "valid":true }');
mysql_select_db($data, $conexion) or die('{ "id":901, "error":true, "message":"Cant open database", "valid":true }');

// Get the received data from the iPhone (XML data)
$body = @file_get_contents('php://input');

// Try to load the XML
$xml = simplexml_load_string($body);

// If there was an error report it...
if ($xml == false) {
   // Error loading XML..., send it back to the iPhone
   echo '{ "id":902, "error":true, "message":"Cant load XML", "valid":true }';
}
else {
   
   // Get username and password
   $username = $xml->username;
   $password = $xml->password;
   
   // Optional: You can check the username and password against your database
   // Uncomment for hardcoded testing
   // if (($username != 'user') && ($password != 'test')) {
   //   echo '{ "id":1, "error":true, "valid":true }';
   //  exit();
   //   }
   
   // Get device identification
   $deviceId = $xml->devId;
   
   // Prepare list of points
   $goodPointsList = "";
      
   // Start processing each travel
   foreach ($xml->travel as $travel) {
      
      // Get travel common information
      $travelId = $travel->id;
      $travelName = $travel->description;
      $travelLength = $travel->length;
      $travelTime = $travel->time;
      $travelTPoints = $travel->tpoints;
      
      // Prepare the succesful points
      $goodPointsList = '';
      
      // Process each point
      foreach ($travel->point as $point) {
         
         // Get all the information for this point
         $pointId = $point->id;
         $pointDate = date("Y-m-d H:i:s", trim($point->date));
         $pointLat = $point->lat;
         $pointLon = $point->lon;
         $pointSpeed = $point->speed;
         $pointCourse = $point->course;
         $pointHAccu = $point->haccu;
         $pointBatt = $point->bat;
         $pointVAccu = $point->vaccu;
         $pointAltitude = $point->altitude;
         $pointContinous = $point->continous;
         $pointTDist = $point->tdist;
         $pointRDist = $point->rdist;
         $pointTTime = $point->ttime;
         
         // Create SQL sentence
         $sql = "INSERT INTO tblBtracedTripsData (DevID, TripID, TripName, TripLength, TripTime, TripTotalPoints, PointID, PointDate, PointLat, PointLon, PointSpeed, PointCourse, PointHAccu, PointBatt, PointVAccu, PointAltitude, PointContinuos, PointTotalDistance, PointRelativeDistance, PointTotalTime) VALUES ('$deviceId','$travelId','$travelName','$travelLength','$travelTime','$travelTPoints','$pointId','$pointDate','$pointLat','$pointLon','$pointSpeed','$pointCourse','$pointHAccu','$pointBatt','$pointVAccu','$pointAltitude','$pointContinous','$pointTDist','$pointRDist','$pointTTime')";
      
         $insertResult = mysql_query($sql, $conexion);
         
         // Check if the Insert was succesful
         if ($insertResult != false) {
            // Add this point to the saved points
            $goodPointsList .= $pointId.",";
         }
         else {
            echo "SQL Error: ".mysql_error();   
         }
      }   
   }
   
   // Check if there was points
   if ($goodPointsList != "") {
      // Remove last comma
      $goodPointsList = substr($goodPointsList, 0, -1);


      // Send back the answer for the saved points
      echo '{"id":0, "tripid":'.$travelId.',"points":['.$goodPointsList.'],"valid":true}';
   } else {
      // Just OK, the code should never reach here as we always have points
      echo '{"id":0, "tripid":'.$travelId.',"valid":true}';      
   }
}

// Close SQL connection
mysql_close($conexion);

?>


MySQL Script for creating the Mysql Database

Code: Select all
-- phpMyAdmin SQL Dump
-- version 3.1.3.1
-- http://www.phpmyadmin.net
-- Version providor: 5.0.67
-- Version PHP: 5.2.9

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

DROP TABLE IF EXISTS `tblBtracedTripsData`;
CREATE TABLE IF NOT EXISTS `tblBtracedTripsData` (
  `ID` int(11) NOT NULL auto_increment COMMENT 'Local data ser reference ID',
  `DevID` varchar(100) NOT NULL COMMENT 'Device Identification',
  `TripID` int(11) NOT NULL COMMENT 'iPhone internal trip ID',
  `TripName` varchar(40) NOT NULL COMMENT 'Trip name',
  `TripLength` float NOT NULL COMMENT 'Trip length in meters at the time of this entry',
  `TripTime` bigint(20) NOT NULL COMMENT 'Trip total time in seconds at the time of this entry',
  `TripTotalPoints` int(11) NOT NULL COMMENT 'Total points of the trip at the time of this entry',
  `PointID` int(11) NOT NULL COMMENT 'iPhone point ID',
  `PointDate` date NOT NULL COMMENT 'Point date',
  `PointLat` double NOT NULL COMMENT 'Point latitude',
  `PointLon` double NOT NULL COMMENT 'Point longitude',
  `PointSpeed` double NOT NULL COMMENT 'Point speed in meters seconds',
  `PointCourse` double NOT NULL COMMENT 'Trip course in degrees',
  `PointHAccu` double NOT NULL COMMENT 'Horizontal accuracy in meters',
  `PointBatt` int(11) NOT NULL COMMENT 'Battery level percentage at this point',
  `PointVAccu` double NOT NULL COMMENT 'Vertical accuracy in meters',
  `PointAltitude` double NOT NULL COMMENT 'Altitude in meters',
  `PointContinuos` int(11) NOT NULL COMMENT 'If 0, this is the beginning of a new trip track',
  `PointTotalDistance` double NOT NULL COMMENT 'Total distance at this point in meters',
  `PointRelativeDistance` double NOT NULL COMMENT 'Distance from the previous point',
  `PointTotalTime` int(11) NOT NULL COMMENT 'Time in seconds at this point',
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=181 ;


BtracedPHP.zip
PHP btraced server software
(3.28 KiB) Downloaded 1747 times

For plotting all the points on googlemaps check this detailled explaination
https://developers.google.com/maps/arti ... sqlajax_v3
User avatar
Btraced
Site Admin
 
Posts: 60
Joined: Sat Dec 10, 2011 3:03 pm

Re: Sample PHP server code for receiving Btraced GPS

Postby bonza » Tue May 01, 2012 12:06 pm

Pieter/Santiago nice quick startup PHP code.

One comment, $point->bat is a float (at least in Btraced 1.0). In the MYSQL create script a double field should be used for table PointBatt;
Jeroen...
bonza
 
Posts: 4
Joined: Sat Mar 24, 2012 9:40 pm
Location: Herten (NL)

Re: Sample PHP server code for receiving Btraced GPS

Postby DJF3 » Sun May 20, 2012 3:39 pm

It's working!

Is there any code that allows you to visualize selected trips on a map?

DJ
DJF3
 
Posts: 2
Joined: Sun Mar 25, 2012 12:53 pm

Re: Sample PHP server code for receiving Btraced GPS

Postby Btraced » Sun May 20, 2012 6:26 pm

User avatar
Btraced
Site Admin
 
Posts: 60
Joined: Sat Dec 10, 2011 3:03 pm

Re: Sample PHP server code for receiving Btraced GPS

Postby walter » Sat Mar 09, 2013 3:33 pm

Hi,

I'm using the great Btraced app for connecting to my own Home-Control server using the PHP example provided here. I want to share some issues when i implemented the upload.php script.

1- Pieter/Santiago remarked:
One comment, $point->bat is a float (at least in Btraced 1.0). In the MYSQL create script a double field should be used for table PointBatt;
- This is true else you get only 0 or 1 for the batterystatus. By making it float you get the right info.

2- Changed this to get the correct time with timezone correction, and correct day/month/year format (for Netherland)
$pointDate = date("Y-m-d H:i:s", trim($point->date));
I
V
$pointDate = gmdate("d-m-Y H:i:s", trim($point->date));

3 - Change the datatype in the mysql create script so gmdate format is accepted.
Original, only date was stored but not the time.
`PointDate` date NOT NULL COMMENT 'Point date',
I
V
`PointDate` varchar(20) NOT NULL COMMENT 'Point date',

4 - When using userid and password autentication change following because it will match userid AND password, else it will autenticate only on userid OR password and not on both:
// Optional: You can check the username and password against your database
// Uncomment for hardcoded testing
if (($username != 'userid') && ($password != 'password)) {
I
V
// Optional: You can check the username and password against your database
// Uncomment for hardcoded testing
if (($username != 'userid') or ($password != 'password')) {

After making these changes the data is correctly inserted in my mysql database.
Now i'm busy and almost ready with creating a PHP script for displaying the trips.

Walter
walter
 
Posts: 2
Joined: Sat Mar 09, 2013 3:07 pm

Re: Sample PHP server code for receiving Btraced GPS

Postby smfunder » Mon Mar 11, 2013 8:01 pm

Hi Walter,

We appreciate those fixes and it is good to have them write down in case any other have the same issues.

Regarding the date it will depend on the server configuration. In my case it was in USA so I had to use that method and format so it is accepted. But nice to show it for other configurations too.

Regarding the date data type I prefer to use "Date" so we can then sort by date or any other queries using an actual date format and not text (that's also why I use Y-m-d to store dates).

And the username and password condition totally agree with you.

So thank you again to point your changes, that will help to all the people (and us) implementing the PHP script.

Santiago
smfunder
Site Admin
 
Posts: 17
Joined: Fri Mar 16, 2012 2:24 am

Re: Sample PHP server code for receiving Btraced GPS

Postby walter » Tue Mar 12, 2013 8:07 am

Hi Santiago,

I will post the upload script asap when its ready.
>>Regarding the date data type I prefer to use "Date" so we can then sort by date or any other queries using an actual date format and not text (that's also why I use Y-m-d to store dates).
Yes you are right concerning this. I changed the datatype back to 'date' and changed the upload.php script to use Y-m-d date format again.
I modified my display.php script which display the trip, and format the date/time with the %variables.
By the way, i will post the trip display.php script also when its ready. I have PERL programming experience but not that much PHP knowledge. Maybe more experienced PHP programmers can review the code?
Thanks.

Walter
walter
 
Posts: 2
Joined: Sat Mar 09, 2013 3:07 pm

Re: Sample PHP server code for receiving Btraced GPS

Postby Btraced » Thu Mar 14, 2013 10:29 am

Thanks Walter
Looking forward to it!
Regards Pieter
User avatar
Btraced
Site Admin
 
Posts: 60
Joined: Sat Dec 10, 2011 3:03 pm

Re: Sample PHP server code for receiving Btraced GPS

Postby insideout » Wed Jun 19, 2013 1:08 pm

Hi,

I've set a database on my server. in Btraced i've set my custom server link to the 'upload.php' file on my server.

http://www.insideoutdigital.com/btraced/upload.php

Get this error

Warning: mysql_connect() [function.mysql-connect]: Can't connect to local MySQL server through socket '/tmp/mysqld.sock' (2) in /homepages/43/d427716305/htdocs/btraced/upload.php on line 11
{ "id":900, "error":true, "message":"Cant connect database", "valid":true }

I'm clearly doing something wrong

How do i edit the php file so that it works on my server?

Thanks
insideout
 
Posts: 2
Joined: Wed Jun 19, 2013 12:59 pm

Re: Sample PHP server code for receiving Btraced GPS

Postby Btraced » Thu Jun 27, 2013 3:23 pm

insideout wrote:Hi,
I've set a database on my server. in Btraced i've set my custom server link to the 'upload.php' file on my server.
http://www.insideoutdigital.com/btraced/upload.php
Get this error
Warning: mysql_connect() [function.mysql-connect]: Can't connect to local MySQL server through socket '/tmp/mysqld.sock' (2) in /homepages/43/d427716305/htdocs/btraced/upload.php on line 11
{ "id":900, "error":true, "message":"Cant connect database", "valid":true }
I'm clearly doing something wrong
How do i edit the php file so that it works on my server?
Thanks

Hi

I think you did not edit this, you need a Mysql database on your webserver with the right autorization etc.
username and password below you must replace etc. Check google on how to do this.
or is this all in place?
$conexion = mysql_connect($hostname, $username, $password) or die('{ "id":900, "error":true, "message":"Cant connect database", "valid":true }');
User avatar
Btraced
Site Admin
 
Posts: 60
Joined: Sat Dec 10, 2011 3:03 pm

Next

Return to Btraced Webservice Protocol And Sample code etc.

Who is online

Users browsing this forum: No registered users and 1 guest

cron