<?php
class Temperature_Graph
{
public $image;
public $black;
public $white;
public $red;
public $blue;
public $green;
public $violet;
public $image_width = 800;
public $image_height = 800;
public function __construct()
{
$this->image = imagecreatetruecolor( $this->image_width, $this->image_height );
$this->black = imagecolorallocate( $this->image, 0, 0, 0 );
$this->white = imagecolorallocate( $this->image, 255, 255, 255 );
$this->red = imagecolorallocate( $this->image, 255, 50, 50 );
$this->blue = imagecolorallocate( $this->image, 50, 50, 255 );
$this->green = imagecolorallocate( $this->image, 50, 255, 50 );
$this->violet = imagecolorallocate( $this->image, 255, 50, 255 );
imagefill( $this->image, 0, 0, $this->white );
imagerectangle( $this->image, 0, 0, $this->image_width-1, $this->image_height-1, $this->black );
}
public function plot_sample( $column, $time, $mean, $std_dev, $min, $max )
{
$hi_temp_degrees_F = 150;
$lo_temp_degrees_F = -25;
$range_in_degrees_F = $hi_temp_degrees_F - $lo_temp_degrees_F;
$pixels_per_degree = $this->image_height / $range_in_degrees_F;
$zero = $hi_temp_degrees_F * $pixels_per_degree;
$x = $column * 10;
$y = $zero - ( $mean + $std_dev / 2 ) * $pixels_per_degree;
$x2 = $x + 5;
$y2 = $y + ( $mean + $std_dev ) * $pixels_per_degree;
imagefilledrectangle( $this->image, $x, $y, $x2, $y2, $this->red );
imagerectangle( $this->image, $x, $y, $x2, $y2, $this->black );
}
public function __destruct()
{
header( 'Content-Type: image/png' );
imagepng( $this->image );
imagedestroy( $this->image );
}
}
class Read_Database_Temperatures
{
public $mysqli;
public $selected;
public function __construct()
{
$db_name = "temperature";
//
// This program can be called with optional arguments:
// --database=foo the name of the database to use
//
$options = getopt( "", [ "database::" ] );
if( $options )
{
foreach( array_keys( $options ) as $key )
{
if( $key == "database" )
{
$db_name = $options[$key];
}
}
}
$this->mysqli = new mysqli( 'localhost', 'root', '', $db_name )
or die( 'Could not connect: ' . mysqli_error() );
$this->mysqli->select_db( $db_name )
or die( "Could not select database $db_name" );
$select =
"SELECT id, mean, std_dev, min, max, reg_date FROM temps"
. " WHERE reg_date >= (CURTIME() - INTERVAL 1 MINUTE)";
$this->selected = $this->mysqli->query( $select )
or die( 'Select failed: ' . $this->mysqli->error );
}
public function output()
{
$graph = new Temperature_Graph();
if( $this->selected->num_rows > 0 )
{
$graph->plot_sample( 0, 0, 75, 2, 72, 78);
$graph->plot_sample( 1, 0, 65, 1, 62, 68);
$graph->plot_sample( 2, 0, 55, 2, 52, 58);
$graph->plot_sample( 3, 0, 35, 5, 32, 38);
/*
$num = 0;
while( $row = $this->selected->fetch_assoc() )
{
$num++;
$graph->plot_sample( $num, $row["reg_date"],
$row["mean"], $row["std_dev"], $row["min"], $row["max"] );
}
*/
}
}
}
$db = new Read_Database_Temperatures();
$db->output();
?>