Display sensor log data in PHP

Moderator: Telldus

Post Reply
atchoo
Posts: 21
Joined: Fri Mar 17, 2023 9:45 am
Location: Oslo, Norway
Contact:

Display sensor log data in PHP

Post by atchoo »

Hello,

I can´t figure out how to parse and use the sensor values returned with "sensor/history". The closest I´ve been is displaying a bunch of arrays that represents the different timestamps (json array: ts), but I can´t access or loop the "data" array or the "temp" value inside.

I need:
  • The Timestamp object (ts),
  • Value of "Temp" from each of the (ts) objects
  • Value of "humidity" from each of the (ts) objects.
When I have these, I can use them as graph objects in my script. Can anybody help me with PHP code to this particular case? I´ve attached an image of the JSON output from API explorer for reference.


Andreas

EDIT: I just figured out how to do it. Very improvised PHP code follows:

Code: Select all

<?php
$from = $_SERVER['REQUEST_TIME'] - (30 * 24 * 60 * 60);
                   // 30 days; 24 hours; 60 mins; 60 secs
$to =  $_SERVER['REQUEST_TIME'];
$history = $telldus_api->getHistory(SENSOR-ID HERE, $from, $to)->history;
foreach($history as $key => $history) 
{
$logTS = $history->ts;
$humi = $history->data[0]->value;
$temp = $history->data[1]->value;
?>
Logged: <?php echo date('d.m.Y',$logTS) ?><br />
Humidity: <?php print_r($humi); ?><br />
Temperature: <?php print_r($temp); ?><br /><br />
<?php } ?>

$telldus_api is a reference to the php file storing all the functions, where I have (related to this issue):

Code: Select all

 public function getHistory($id, $from, $to)
  {
        $params = array('id'=>$id,
				 'from'=>$from,
				 'to'=>$to
				 );
        return json_decode($this->consumer->sendRequest(constant('REQUEST_URI').'/sensor/history', $params, 'GET')->getBody());

  }
Output from the test code above:
Skjermbilde 2015-07-07 kl. 00.22.45.png
Skjermbilde 2015-07-07 kl. 00.22.45.png (108.44 KiB) Viewed 149131 times
I can see from the output that all the logs are timestamped today, which seems to be wrong, but at least I´m getting somewhere :)
F1dg1t
Posts: 3
Joined: Fri Mar 17, 2023 9:45 am

Re: Display sensor log data in PHP

Post by F1dg1t »

Nice exemple you got goin here.
I know you did this for a long time ago, but is there any chance you got this exemple saved?
Its exatly what I'm looking for to get started with my own personal homepage.
atchoo
Posts: 21
Joined: Fri Mar 17, 2023 9:45 am
Location: Oslo, Norway
Contact:

Re: Display sensor log data in PHP

Post by atchoo »

Hello F1dg1t,

I haven't seen your request before now, but here's my current attempt at answering your question, since I don't have that old code anymore (on second thought, I hope I never find it anyway :lol: )
This one is a bit tedious, but I guess it will do the job if you only need sensor values.

Edit: I just realized that I have to modify this a bit, to include the sensor history as well. I'll try to get back to that shortly.

"Short" PHP Example:

Code: Select all

<?php

// Get cURL resource
$ch = curl_init();

// Set url
curl_setopt($ch, CURLOPT_URL, 'https://api.telldus.com/json/sensors/list?includeIgnored&includeValues=1&includeScale&useAlternativeData=1');

// Set method
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

// Set options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Insert your API keys here 
$oauth_consumerKey = "YOUR PUBLIC KEY HERE";
$oauth_privateKey = "YOUR PRIVATE KEY HERE";
$oauth_token = "YOUR TOKEN HERE";
$oauth_tokenSecret = "YOUR TOKEN SECRET";

$oauth_signature = ($oauth_privateKey . "%26" . $oauth_tokenSecret);
$oauth_nonce = md5(uniqid(mt_rand(), true));
$oauth_timestamp = $_SERVER['REQUEST_TIME'];

// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [
  "Authorization: OAuth oauth_consumer_key=" . $oauth_consumerKey . ", oauth_nonce=" . $oauth_nonce . ", oauth_signature=" . $oauth_signature .", oauth_signature_method=\"PLAINTEXT\", oauth_timestamp=" . $oauth_timestamp . ", oauth_token=" . $oauth_token . ", oauth_version=\"1.0\"",
 ]
);

// Send the request & save response to $resp
$resp = curl_exec($ch);
$jsonResp = json_decode($resp, true);

$eachSensor = $jsonResp["sensor"];

// Close request
curl_close($ch);

foreach ($eachSensor as $sensor) {
?>
<br />
<h1><?php echo $sensor["name"]?></h1><br />
<h2><?php echo $sensor["temp"]?> ℃</h2>
<h3><?php if(!empty($sensor["humidity"])) { echo "Air Humidity: " . $sensor["humidity"]; } else { /* alternatively iterate through as many sensor values you need here...*/ } ?> </h3><hr>
<?php } ?>


Here's a "Bootstrapped" version of the same thing (working, but a bit sloppy):

Screenshot:
Image

Code: Select all

<?php

// Get cURL resource
$ch = curl_init();

// Set url
curl_setopt($ch, CURLOPT_URL, 'https://api.telldus.com/json/sensors/list?includeIgnored&includeValues=1&includeScale&useAlternativeData=1');

// Set method
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

// Set options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Insert your API keys here 
$oauth_consumerKey = "YOUR PUBLIC KEY HERE";
$oauth_privateKey = "YOUR PRIVATE KEY HERE";
$oauth_token = "YOUR TOKEN HERE";
$oauth_tokenSecret = "YOUR TOKEN SECRET";

$oauth_signature = ($oauth_privateKey . "%26" . $oauth_tokenSecret);
$oauth_nonce = md5(uniqid(mt_rand(), true));
$oauth_timestamp = $_SERVER['REQUEST_TIME'];

// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [
  "Authorization: OAuth oauth_consumer_key=" . $oauth_consumerKey . ", oauth_nonce=" . $oauth_nonce . ", oauth_signature=" . $oauth_signature .", oauth_signature_method=\"PLAINTEXT\", oauth_timestamp=" . $oauth_timestamp . ", oauth_token=" . $oauth_token . ", oauth_version=\"1.0\"",
 ]
);

// Send the request & save response to $resp
$resp = curl_exec($ch);
$jsonResp = json_decode($resp, true);

$eachSensor = $jsonResp["sensor"];

// Close request
curl_close($ch);

?>
<!doctype html>
<html>
<head>
<script src="https://use.fontawesome.com/4a8745b9db.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Telldus Sensors - Curl/PHP Example</title>
<link rel="stylesheet" href="css/sticky-footer.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

</head>
<body>
<div class="row">
<div class="container">
<div class="col-md-4">
<br />

<div class="card card-header bg-success text-white">
	<h2 class="card-title">Sensors</h2>
	</div>
	<div class="card card-block">
	<?php 
foreach ($eachSensor as $sensor) {
?>
<div class="row">
	<div class="col-md-8"><h4><?php echo $sensor["name"]?></h4	></div>
	<div class="col-md-4"><span class="badge badge-pill badge-default" style="font-size: 16px;"><?php echo $sensor["temp"]?> ℃</span></div>
	<?php if(!empty($sensor["humidity"])) { ?>
	<div class="col-md-8 text-right"><i class="fa fa-tint text-success" aria-hidden="true"></i></div>
	<div class="col-md-4"><span class="badge badge-pill badge-success" style="font-size: 16px;"><?php echo $sensor["humidity"]?> % </span></div><?php } ?><br /><br />
</div>
<?php } ?>
	</div>
	</div>
	</div>
	</div>
	<div class="footer text-sm-center">©2017 <a href="http://www.twitter.com/atchoodev/" target="_blank">Andreas Lorentsen</a><br />
<a href="http://telldus.se" target="_blank">Tellstick, Telldus Live! and Telldus Mobile</a> are registered trademarks of <a href="http://telldus.se/om-oss/" target="_blank">Telldus Technology Sweden AB</a></div>
</body>
</html>
Post Reply