You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

344 lines
12 KiB

  1. <?php
  2. namespace App\Jobs;
  3. use DB;
  4. use Log;
  5. use Quartz;
  6. use p3k\Multipart;
  7. use App\Jobs\Job;
  8. use Illuminate\Contracts\Bus\SelfHandling;
  9. use Illuminate\Contracts\Queue\ShouldQueue;
  10. use DateTime, DateTimeZone;
  11. class TripComplete extends Job implements SelfHandling, ShouldQueue
  12. {
  13. private $_dbid;
  14. private $_data;
  15. public function __construct($dbid, $data) {
  16. $this->_dbid = $dbid;
  17. $this->_data = $data;
  18. }
  19. public function handle() {
  20. // echo "Job Data\n";
  21. // echo json_encode($this->_data)."\n";
  22. if(!is_array($this->_data)) return;
  23. $db = DB::table('databases')->where('id','=',$this->_dbid)->first();
  24. Log::info("Starting job for ".$db->name);
  25. Log::debug(json_encode($this->_data));
  26. if(!$db->micropub_endpoint) {
  27. Log::info('No micropub endpoint configured for database ' . $db->name);
  28. return;
  29. }
  30. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'r');
  31. // Load the data from the start and end times
  32. $start = new DateTime($this->_data['properties']['start']);
  33. $end = new DateTime($this->_data['properties']['end']);
  34. $results = $qz->queryRange($start, $end);
  35. $features = [];
  36. foreach($results as $id=>$record) {
  37. if(!property_exists($record->data->properties, 'action')) {
  38. $record->data->properties = array_filter((array)$record->data->properties, function($k){
  39. // Remove some of the app-specific tracking keys
  40. return !in_array($k, ['locations_in_payload','desired_accuracy','significant_change','pauses','deferred']);
  41. }, ARRAY_FILTER_USE_KEY);
  42. $features[] = $record->data;
  43. }
  44. }
  45. // Build the GeoJSON for this trip
  46. $geojson = [
  47. 'type' => 'FeatureCollection',
  48. 'features' => $features
  49. ];
  50. $file_path = tempnam(sys_get_temp_dir(), 'compass');
  51. file_put_contents($file_path, json_encode($geojson));
  52. // If there are no start/end coordinates in the request, use the first and last coordinates
  53. if(count($features)) {
  54. if(!array_key_exists('start-coordinates', $this->_data['properties'])) {
  55. $this->_data['properties']['start-coordinates'] = $features[0]->geometry->coordinates;
  56. }
  57. if(!array_key_exists('end-coordinates', $this->_data['properties'])) {
  58. $this->_data['properties']['end-coordinates'] = $features[count($features)-1]->geometry->coordinates;
  59. }
  60. }
  61. $startAdr = false;
  62. if(array_key_exists('start-coordinates', $this->_data['properties'])) {
  63. // Reverse geocode the start and end location to get an h-adr
  64. $startAdr = [
  65. 'type' => 'h-adr',
  66. 'properties' => [
  67. 'latitude' => $this->_data['properties']['start-coordinates'][1],
  68. 'longitude' => $this->_data['properties']['start-coordinates'][0],
  69. ]
  70. ];
  71. Log::info('Looking up start location');
  72. $start = self::geocode($this->_data['properties']['start-coordinates'][1], $this->_data['properties']['start-coordinates'][0]);
  73. if($start) {
  74. $startAdr['properties']['locality'] = $start->locality;
  75. $startAdr['properties']['region'] = $start->region;
  76. $startAdr['properties']['country'] = $start->country;
  77. Log::info('Found start: '.$start->full_name.' '.$start->timezone);
  78. }
  79. } else {
  80. $start = false;
  81. }
  82. $endAdr = false;
  83. if(array_key_exists('end-coordinates', $this->_data['properties'])) {
  84. $endAdr = [
  85. 'type' => 'h-adr',
  86. 'properties' => [
  87. 'latitude' => $this->_data['properties']['end-coordinates'][1],
  88. 'longitude' => $this->_data['properties']['end-coordinates'][0],
  89. ]
  90. ];
  91. Log::info('Looking up end location');
  92. $end = self::geocode($this->_data['properties']['end-coordinates'][1], $this->_data['properties']['end-coordinates'][0]);
  93. if($end) {
  94. $endAdr['properties']['locality'] = $end->locality;
  95. $endAdr['properties']['region'] = $end->region;
  96. $endAdr['properties']['country'] = $end->country;
  97. Log::info('Found end: '.$end->full_name.' '.$end->timezone);
  98. }
  99. } else {
  100. $end = false;
  101. }
  102. // Set the timezone of the dates based on the location
  103. $startDate = new DateTime($this->_data['properties']['start']);
  104. if($start && $start->timezone) {
  105. $startDate->setTimeZone(new DateTimeZone($start->timezone));
  106. }
  107. $endDate = new DateTime($this->_data['properties']['end']);
  108. if($end && $end->timezone) {
  109. $endDate->setTimeZone(new DateTimeZone($end->timezone));
  110. }
  111. $params = [
  112. 'h' => 'entry',
  113. 'created' => $endDate->format('c'),
  114. 'trip' => [
  115. 'type' => 'h-trip',
  116. 'properties' => [
  117. 'mode-of-transport' => $this->_data['properties']['mode'],
  118. 'start' => $startDate->format('c'),
  119. 'end' => $endDate->format('c'),
  120. 'route' => 'route.json'
  121. // TODO: avgpace for runs
  122. // TODO: avgspeed for bike rides
  123. // TODO: avg heart rate if available
  124. ]
  125. ]
  126. ];
  127. if($startAdr) {
  128. $params['trip']['properties']['start-location'] = $startAdr;
  129. }
  130. if($endAdr) {
  131. $params['trip']['properties']['end-location'] = $endAdr;
  132. }
  133. if(array_key_exists('distance', $this->_data['properties'])) {
  134. $params['trip']['properties']['distance'] = [
  135. 'type' => 'h-measure',
  136. 'properties' => [
  137. 'num' => round($this->_data['properties']['distance']),
  138. 'unit' => 'meter'
  139. ]
  140. ];
  141. }
  142. if(array_key_exists('duration', $this->_data['properties'])) {
  143. $params['trip']['properties']['duration'] = [
  144. 'type' => 'h-measure',
  145. 'properties' => [
  146. 'num' => round($this->_data['properties']['duration']),
  147. 'unit' => 'second'
  148. ]
  149. ];
  150. }
  151. if(array_key_exists('cost', $this->_data['properties'])) {
  152. $params['trip']['properties']['cost'] = [
  153. 'type' => 'h-measure',
  154. 'properties' => [
  155. 'num' => round($this->_data['properties']['cost'], 2),
  156. 'unit' => 'USD'
  157. ]
  158. ];
  159. }
  160. // If there is trip data, recalculate the distance and duration based on the actual data
  161. if(count($features)) {
  162. $startTime = strtotime($features[0]->properties['timestamp']);
  163. $endTime = strtotime($features[count($features)-1]->properties['timestamp']);
  164. $duration = $endTime - $startTime;
  165. $params['trip']['properties']['duration']['properties']['num'] = $duration;
  166. Log::debug("Overriding duration to $duration");
  167. $points = array_map(function($f){
  168. return $f->geometry->coordinates;
  169. }, $features);
  170. $simple = $this->_ramerDouglasPeucker($points, 0.0001);
  171. $last = false;
  172. $distance = 0;
  173. foreach($simple as $p) {
  174. if($last) {
  175. $distance += $this->_gc_distance($p[1], $p[0], $last[1], $last[0]);
  176. }
  177. $last = $p;
  178. }
  179. if($distance) {
  180. $params['trip']['properties']['distance']['properties']['num'] = $distance;
  181. Log::debug("Overriding distance to $distance");
  182. }
  183. }
  184. // echo "Micropub Params\n";
  185. // print_r($params);
  186. $multipart = new Multipart();
  187. $multipart->addArray($params);
  188. $multipart->addFile('route.json', $file_path, 'application/json');
  189. $httpheaders = [
  190. 'Authorization: Bearer ' . $db->micropub_token,
  191. 'Content-type: ' . $multipart->contentType()
  192. ];
  193. Log::info('Sending to the Micropub endpoint: '.$db->micropub_endpoint);
  194. // Post to the Micropub endpoint
  195. $ch = curl_init($db->micropub_endpoint);
  196. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  197. curl_setopt($ch, CURLOPT_POST, true);
  198. curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
  199. curl_setopt($ch, CURLOPT_POSTFIELDS, $multipart->data());
  200. curl_setopt($ch, CURLOPT_HEADER, true);
  201. $response = curl_exec($ch);
  202. Log::info("Done!");
  203. Log::info($response);
  204. // echo "========\n";
  205. // echo $response."\n========\n";
  206. //
  207. // echo "\n";
  208. }
  209. public static function geocode($lat, $lng) {
  210. $ch = curl_init(env('ATLAS_BASE').'api/geocode?latitude='.$lat.'&longitude='.$lng);
  211. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  212. curl_setopt($ch, CURLOPT_TIMEOUT, 8);
  213. $response = curl_exec($ch);
  214. if($response) {
  215. return json_decode($response);
  216. }
  217. }
  218. // TODO: move this to a library p3k/Geo
  219. // http://www.loughrigg.org/rdp/
  220. //The author has placed this work in the Public Domain, thereby relinquishing all copyrights.
  221. //You may use, modify, republish, sell or give away this work without prior consent.
  222. //This implementation comes with no warranty or guarantee of fitness for any purpose.
  223. //=========================================================================
  224. //An implementation of the Ramer-Douglas-Peucker algorithm for reducing
  225. //the number of points on a polyline
  226. //see http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
  227. //=========================================================================
  228. //Finds the perpendicular distance from a point to a straight line.
  229. //The coordinates of the point are specified as $ptX and $ptY.
  230. //The line passes through points l1 and l2, specified respectively with their
  231. //coordinates $l1x and $l1y, and $l2x and $l2y
  232. public function _perpendicularDistance($ptX, $ptY, $l1x, $l1y, $l2x, $l2y)
  233. {
  234. $result = 0;
  235. if ($l2x == $l1x)
  236. {
  237. //vertical lines - treat this case specially to avoid divide by zero
  238. $result = abs($ptX - $l2x);
  239. }
  240. else
  241. {
  242. $slope = (($l2y-$l1y) / ($l2x-$l1x));
  243. $passThroughY = (0-$l1x)*$slope + $l1y;
  244. $result = (abs(($slope * $ptX) - $ptY + $passThroughY)) / (sqrt($slope*$slope + 1));
  245. }
  246. return $result;
  247. }
  248. //RamerDouglasPeucker
  249. //Reduces the number of points on a polyline by removing those that are closer to the line
  250. //than the distance $epsilon.
  251. //The polyline is provided as an array of arrays, where each internal array is one point on the polyline,
  252. //specified by easting (x-coordinate) with key "0" and northing (y-coordinate) with key "1".
  253. //It is assumed that the coordinates and distance $epsilon are given in the same units.
  254. //The result is returned as an array in a similar format.
  255. //Each point returned in the result array will retain all its original data, including its E and N
  256. //values along with any others.
  257. public function _ramerDouglasPeucker($pointList, $epsilon)
  258. {
  259. if(count($pointList) == 0)
  260. return array();
  261. // Find the point with the maximum distance
  262. $dmax = 0;
  263. $index = 0;
  264. $totalPoints = count($pointList);
  265. for ($i = 1; $i < ($totalPoints - 1); $i++)
  266. {
  267. $d = $this->_perpendicularDistance($pointList[$i][0], $pointList[$i][1],
  268. $pointList[0][0], $pointList[0][1],
  269. $pointList[$totalPoints-1][0], $pointList[$totalPoints-1][1]);
  270. if ($d > $dmax)
  271. {
  272. $index = $i;
  273. $dmax = $d;
  274. }
  275. }
  276. $resultList = array();
  277. // If max distance is greater than epsilon, recursively simplify
  278. if ($dmax >= $epsilon)
  279. {
  280. // Recursive call
  281. $recResults1 = $this->_ramerDouglasPeucker(array_slice($pointList, 0, $index + 1), $epsilon);
  282. $recResults2 = $this->_ramerDouglasPeucker(array_slice($pointList, $index, $totalPoints - $index), $epsilon);
  283. // Build the result list
  284. $resultList = array_merge(array_slice($recResults1, 0, count($recResults1) - 1),
  285. array_slice($recResults2, 0, count($recResults2)));
  286. }
  287. else
  288. {
  289. $resultList = array($pointList[0], $pointList[$totalPoints-1]);
  290. }
  291. // Return the result
  292. return $resultList;
  293. }
  294. function _gc_distance($lat1, $lng1, $lat2, $lng2) {
  295. return ( 6378100 * acos( cos( deg2rad($lat1) ) * cos( deg2rad($lat2) ) * cos( deg2rad($lng2) - deg2rad($lng1) ) + sin( deg2rad($lat1) ) * sin( deg2rad($lat2) ) ) );
  296. }
  297. }