Skip to content

Instantly share code, notes, and snippets.

@smulube
Created October 31, 2012 23:29
Show Gist options
  • Save smulube/3990626 to your computer and use it in GitHub Desktop.
Save smulube/3990626 to your computer and use it in GitHub Desktop.
<?
// set some variables we'll use later
$timezone_offset = '-06'; // set to your local timezone offset from UTC
$raw_url = "http://urltoyourdata.xml"; // replace with actual path to your published raw data
$title = "data logger"; // the title for your Cosm feed
$feed_id = 83211;
$api_key = "insert_api_key"; // this api key needs to have 'update' access to your feed
// Get raw data
$raw_xml = simplexml_load_file($raw_url);
// Extract timestamp. Note all this messing about is to create an ISO8601
// formatted string in the correct time zone, as this is what Cosm expects
$date_part = $raw_xml->xpath('/Devices/Device[@Name="Date"]');
$time_part = $raw_xml->xpath('/Devices/Device[@Name="Time"]');
$timestamp = strtotime($date_part[0]['Value'] . $time_part[0]['Value']);
$iso8601_timestamp = strftime('%Y-%m-%dT%H:%M:%S' . $timezone_offset, $timestamp);
// Construct xml for Cosm
$cosm_xml = new SimpleXMLElement('<eeml/>');
$cosm_xml->addAttribute('xmlns', 'http://www.eeml.org/xsd/0.5.1');
$cosm_xml->addAttribute('version', '0.5.1');
$environment = $cosm_xml->addChild('environment');
$environment->addChild('title', $title);
foreach ($raw_xml->Device as $device) {
// Don't publish Date/Time as separate datastreams
if($device['Name'] == 'Date' || $device['Name'] == 'Time') {
continue;
}
$datastream = $environment->addChild('data');
$datastream->addAttribute('id', $device['Name']);
$current_value = $datastream->addChild('current_value', $device['Value']);
$current_value->addAttribute('at', $iso8601_timestamp);
}
// Now we want to push the data into Cosm
$url = "https://api.cosm.com/v2/feeds/" . $feed_id . ".xml";
$update_xml = $cosm_xml->asXML(); // capture actual XML to be sent
// Set up curl handle to make the transfer
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, $title . " - http://www.3cubus.com"); // good practice to specify a user agent
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml','Content-Length: ' . strlen($update_xml)));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,$update_xml);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$ch_result = curl_exec($ch);
$ch_errno = curl_errno($ch);
$ch_error = curl_error($ch);
curl_close($ch);
if ($ch_errno) {
header("HTTP/1.0 500 Internal Server Error");
echo "Error pushing data to Cosm: " . $ch_error;
} else {
echo "OK";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment