Skip to content

Instantly share code, notes, and snippets.

@matthewtole
Created August 8, 2013 15:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewtole/6185636 to your computer and use it in GitHub Desktop.
Save matthewtole/6185636 to your computer and use it in GitHub Desktop.
The PHP API that powers my London Tube app for the Pebble Smartwatch. (http://matthewtole.com/pebble/#london-tube)
<?php
// Include my shared functions.
include_once($_SERVER['DOCUMENT_ROOT'] . '/utils.php');
// The URL of the Tube Status API.
$API_URL = 'http://api.tubeupdates.com/?method=get.status&format=json';
// Mapping between shortcode and line name.
$line_codes = array(
'BL' => 'bakerloo',
'CE' => 'central',
'CI' => 'circle',
'DI' => 'district',
'DL' => 'docklands',
'HC' => 'hammersmithcity',
'JL' => 'jubilee',
'ME' => 'metropolitan',
'NO' => 'northern',
'OV' => 'overground',
'PI' => 'piccadilly',
'VI' => 'victoria',
'WC' => 'waterloocity'
);
// Mapping between errors and numbers
$statuses = array(
'good service' => 1,
'part closure' => 2,
'minor delays' => 4,
'severe delays' => 8,
'part suspended' => 16
);
// Grab the tube status and the incoming payload.
$tube_data = json_decode(file_get_contents($API_URL), true);
$payload = get_payload();
$order = $payload['0'];
// Start building the response.
$response = array(
'0' => $order,
'1' => ''
);
// Split the ordering string into the 2 character line short codes.
$lines = str_split($order, 2);
foreach ($lines as $pos => $line) {
// Get the status for the line given its short code.
$status = get_status_by_id($line_codes[$line]);
// Do bitwise ORs on the status number to build it up
$status_number = 0;
foreach ($status as $st) {
$status_number = $status_number |= $statuses[$st];
}
// Append the status code to the response string.
$response['1'] .= str_pad($status_number, 2, ' ', STR_PAD_LEFT);
}
// Send the response.
send_response($response);
// Takes a line code (not shortcode) and returns an array of its current status.
function get_status_by_id($id) {
global $tube_data;
foreach ($tube_data['response']['lines'] as $index => $line) {
if ($line['id'] == $id) {
return explode(', ', $line['status']);
}
}
return NULL;
}
?>
function get_payload() {
return json_decode(file_get_contents('php://input'), true);
}
function send_response($data) {
$response = json_encode($data, JSON_FORCE_OBJECT);
header('Content-Type: application/json');
header('Content-Length: ' . strlen($response));
echo $response;
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment