Hallo Ruco,
kannst Du mal zeigen, wie die Highcharts nach Deiner Änderung jetzt ausschauen - bezüglich des Auswahlmenüs. Und wäre das Problem der leeren Chartdarstellung nach dem öffnen von Highcharts damit behoben?
Besten Dank
Hallo Ruco,
kannst Du mal zeigen, wie die Highcharts nach Deiner Änderung jetzt ausschauen - bezüglich des Auswahlmenüs. Und wäre das Problem der leeren Chartdarstellung nach dem öffnen von Highcharts damit behoben?
Besten Dank
Suche Programmierer. Datenbank auslesen und visualisieren per Highcharts.? Schau mal ob du hier fündig wirst!
Naja. Als ein Problem würde ich das mit der Chart-Darstellung nicht nennen.
Es wurde ja nur nichts angezeigt weil ja auch keine Zeitangabe mit übergeben wurde. (index.php?period=12h)
Das hattest du ja dann gemacht nachdem du auf einen entsprechenden Link geklickt hast
Könnte man aber noch ergänzen.
Und um auf die Frage zu Antworten. Ja, ist "gelöst".
Die Datenbank wird direkt mit einer Zeit aufgerufen. Kannste auch ändern wie du magst.
[code=php]<option value="index.php?period=12h">Schrank</option>[/php]
Wie das Auswahlmenü aussieht? So:
Hallo Ruco,
ok. Ich kann mit dem Original von meigrafd gut leben - werde eventuell die Namen der DB´s bei mir nochmal ändern.
Noch ne Frage: Habe mal versucht, den Namen der ausgewählten Datenbank(bei mir z.B."warmwasser") in die Kopfzeile neben "Temperature" einzufügen, so dass dann dort z.B. steht:"Temperature-Warmwasser of the last 2 hour". Leider ohne Erfolg.
Eine Idee vieleicht? Danke!
Zeig doch mal den Code.
So wie du es gerade schreibst kann ichs mir nicht vorstellen.
Und was genau war "ohne Erfolg"?
Hallo Ruco,
nachdem ich nun das halbe WE versucht hatte, den Namen der ausgewählten DB in die Kopfzeile der Highcharts zu bekommen, ging irgendwann nichts mehr. Habe mir dann die index.php aus dem meigrafd´s Github neu eingefügt und diese bezüglich der DB-Menüauswahl angepasst - ok - funktioniert erstmal wieder.
Bekomme jetzt leider die Chart-Darstellung nicht neben das Menü(Zeitfenster)
Hier mal der entsprechende Teil der index.php:[code=php] body {
font-size: 13pt;
color: black;
font-family: Verdana,arial,helvetica,serif;
margin: 0px;
background-color: #F5F5DC;
}
#header {
width: 100%;
min-height: 80px;
#menu {
font-size: 11pt;
color: #000;
float: left;
padding: 5px;
background-color: #F5F5DC;
margin: 0px 0px 0px 10px;
line-height: 20px;
min-width: 100px;
}
#content {
min-height: 840px;
margin-left: 140px;
width: 80%; body {
font-size: 13pt;
color: black;
font-family: Verdana,arial,helvetica,serif;
margin: 0px;
background-color: #F5F5DC;
}
#header {
width: 100%;
min-height: 80px;
#menu {
font-size: 11pt;
color: #000;
float: left;
padding: 5px;
background-color: #F5F5DC;
margin: 0px 0px 0px 10px;
line-height: 20px;
min-width: 100px;
}
#content {
min-height: 840px;
margin-left: 140px;
width: 80%;[/php]
[code=php]}
#tempchart {
margin-top: 0px;
}
#humchart {
margin-top: 20px;
}
#footer {
width: 100%;
min-height: 0px;
background-color: #F5F5DC;
text-align: center;
}
[/php]
Ist halt das original-setting - hatte da nie was verändert, aber sah eben mal anders aus - siehe ältere Threads.
Zum eigentlichen Wunsch meinerseits, den Chart-Text: "Temperatur der letzten 2 Stunden" um den DB-Namen(z.B. aussen) zu erweitern
(also"aussen-Temperatur der letzten 2 Stunden") ist mir bisher keine Lösung eingefallen. Habe gelesen und gelesen und ... - kein Erfolg.
Vielleicht hasst Du oder Ihr eine Idee oder eine Lösungsvorschlag
Du hast doch das Auswahlmenü eingefügt. Wo denn genau?
Sieht nämlich nach einen "Fehler" beim Einfügen aus.
Zeig bitte den ganzen Quellcode. Keinen Ausschnitt.
Hi Ruco,
leider ein kleiner Syntax-Fehler:
Vor #menu fehlte die geschlossene Klamme, welche zu #header gehört >>> jetzt stimmts wieder. Danke!
Hast Du zum DB-Namen noch ne Idee?
MfG - towi
Ich denk ich habs jetzt verstanden.
Du meinst sicher das:
[code=php]text: "<?php echo $database; ?> Temperatur <?php echo $Chart[$Period]; ?>"[/php]
Zeile 135 in der originalen Index.php ersetzen oder das vor "Temperatur" einfügen: <?php echo $database; ?>
Euer Problem hängt damit zusammen das in der index.php kein $database definiert wird und somit dort auch nicht verwendet werden kann - schaut mal in die /var/log/apache2/error.log da sollten einige Fehlermeldungen stehen.
Ich frag mich allerdings schon die Ganze Zeit was ihr da überhaupt vor habt. Als ich letzten Monat bei der Sache mit mehreren Datenbanken half dacht ich mir erst nichts böses, mehrere Datenbanken auf einer Webseite zu visualisieren ist ja noch Oke... Aber sofern ihr die ganze Zeit nur ein und den selben MySQL ansprecht muss ich mit dem Kopf schütteln.
In einer Datenbank kann man mehrere eigenständige Tabellen anlegen, welche wiederum mehrere Spalten haben. In der "measurements" ist bereits eine Spalte "locations" vorgesehen um Sensoren von verschiedenen Standorten zu bedienen. Wenn ihr also einen Sensor im Schlafzimmer, einem im Schrank und einen weiteren zum Testen habt, braucht ihr beim Eintragen in diese eine Datenbank nur eine andere "location" angeben.
Aber selbst wenn ihr mehrere voneinander getrennte Orte haben wollt, braucht ihr nur mehrere Tabellen anlegen - in ein und der selben Datenbank. Ihr braucht dann nur in der data.php die jeweilige Tabelle beim "FROM" Statement auswählen - derzeit steht das auf "data".
Also ich empfehle weiterhin die Verwendung von $_SESSION. Damit lässt es sich eigentlich recht leicht realisieren dass eine Einstellung einmal gesetzt und auch über einen reload hinweg behalten wird.
Man muss sich nur merken dass das ein eigener Cache ist auf dem alle Scripts zugreifen können müssten. Um das zu erreichen muss in jedem PHP Script als aller erstes session_start(); ausgeführt werden, aber eben nur dann wenn noch keine $_SESSION vorhanden ist... Das macht man wie gesagt am besten über die global.php da diese in unseren beiden PHP Dateien direkt als erstes eingebunden wird.
Bedeutet also, global.php bearbeiten und folgendes direkt unter <?php einfügen:
[code=php]if (!isset($_SESSION)) { session_start(); }[/php]
Desweiteren empfehle ich in die global.php aber auch noch folgendes einzufügen (unter obiger Zeile):
[code=php]$TIMEOUT = "3600";
ini_set("session.gc_maxlifetime", $TIMEOUT); // default: 1440 seconds or 24 minutes
session_cache_limiter($TIMEOUT);[/php]Wenn ihr also länger als 60 Minuten die Seite nicht verwendet habt, läuft die Session ab und der Cache verfällt.
Dann bearbeitet man die config.php und fügt dort folgende Zeile hinzu (in den MySQL Abschnitt da es dazu gehört)
[code=php]$tables = "Testlauf,Schlafzimmer,Wand/Schrank"; // one or more Tables, separated with ","[/php]
Nun erfolgt die Anpassung der index.php
..direkt unter den "Menue" Abschnitt einfügen:
[code=php]
//------------------------------------------------------
// Select Measurements Table
//------------------------------------------------------
$tablesArray = explode(",", $tables);
if (count($tablesArray) == 1) {
$table = $tables;
} else {
if (isset($_POST['table'])) { $table = $_POST['table']; }
echo "<form action='' method='POST'>\n";
echo " <select name='db' size='1' onChange='this.form.submit();'>\n";
foreach($tablesArray AS $key => $t) {
if (isset($table) AND $table == $t) { $Selected=" selected"; } else { $Selected=""; }
echo " <option value='".$t."'".$Selected.">".$t."</option>\n";
}
echo " </select>\n";
echo "</form>\n";
}
if (!isset($table)) {
if (isset($_SESSION['table'])) {
$table = $_SESSION['table'];
} else {
$table = $tablesArray[0];
}
}
$_SESSION['table'] = $table;
[/php]
..und dann die beiden bekannten Zeilen zur Übergabe an data.php ebenfalls wie folgt ersetzen/anpassen:
[code=php]
// Chart: Temperatures
$.getJSON("data.php?type=temp&period=<?php echo $Period; ?>&table=<?php echo $table; ?>", function(json) {
title: {
text: "<?php echo $table; ?> Temperatures <?php echo $Chart[$Period]; ?>"
},
// Chart: Humidity
$.getJSON("data.php?type=hum&period=<?php echo $Period; ?>&table=<?php echo $table; ?>", function(json) {
title: {
text: "<?php echo $table; ?> Humidity <?php echo $Chart[$Period]; ?>"
},
[/php]
Jetzt fehlt nur noch die data.php:
[code=php]
if (isset($_GET['type'])) {
if ($_GET['type'] == 'temp') {
$Type = 'temp';
} else {
$Type = 'hum';
}
if (isset($_GET['table']) AND !empty($_GET['table'])) { $table = $_GET['table']; }
$result = query("SELECT location FROM ".$table." GROUP BY location");
$result2 = query("SELECT location,timestamp,".$Type." FROM ".$table."
[/php]
Summa Summarum:
config.php
[code=php]
<?php
//------------------------------------------------------
// MySQL
//------------------------------------------------------
$dbhost = "localhost";
$dbport = 3306;
$dbuser = "root";
$dbpass = "passw0rd";
$database = "measurements";
$tables = "Testlauf,Schlafzimmer,Wand/Schrank"; // one or more Tables, separated with ","
/* create for each location a Table:
CREATE TABLE `Testlauf` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
`location` VARCHAR(255),
`timestamp` INT(11),
`temp` FLOAT(11),
`hum` FLOAT(11),
`vcc` FLOAT(11),
PRIMARY KEY (`id`),
KEY `location` (`location`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
*/
//------------------------------------------------------
// Selectable Chart Ranges.
// Format: $Chart['<period>'] = '<chart title>';
// Example: $Chart['12h'] = 'of the last 12 hours';
// Valid Units: s=second,mi=Minute,h=hour,d=day,w=week,m=month,y=year
//------------------------------------------------------
$Chart['30mi'] = 'of the last 30 minutes';
$Chart['1h'] = 'of the last 1 hour';
$Chart['2h'] = 'of the last 2 hours';
$Chart['3h'] = 'of the last 3 hours';
$Chart['6h'] = 'of the last 6 hours';
$Chart['12h'] = 'of the last 12 hours';
$Chart['24h'] = 'of the last 24 hours';
$Chart['2d'] = 'of the last 2 days';
$Chart['3d'] = 'of the last 3 days';
$Chart['1w'] = 'of the last week';
$Chart['2w'] = 'of the last 2 weeks';
$Chart['1m'] = 'of the last month';
$Chart['3m'] = 'of the last 3 months';
$Chart['6m'] = 'of the last 6 months';
$Chart['1y'] = 'of the last year';
//------------------------------------------------------
?>
[/php]
global.php
[code=php]
<?php
if (!isset($_SESSION)) { session_start(); }
$TIMEOUT = "3600";
ini_set("session.gc_maxlifetime", $TIMEOUT); // default: 1440 seconds or 24 minutes
session_cache_limiter($TIMEOUT);
$DEBUG=0;
$showqueries=0;
$Chart=array();
require_once("config.php");
require_once("functions.php");
?>
[/php]
index.php
[code=php]
<?php
//------------------------------------------------------
require_once('include/global.php');
//------------------------------------------------------
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="de">
<head>
<title>Sensor Charts</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="DISALLOW">
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/functions.js"></script>
<style type=text/css>
body {
font-size: 13pt;
color: black;
font-family: Verdana,arial,helvetica,serif;
margin: 0px;
background-color: #F5F5DC;
}
#header {
width: 100%;
min-height: 80px;
}
#menu {
font-size: 11pt;
color: #000;
float: left;
padding: 5px;
background-color: #F5F5DC;
margin: 0px 0px 0px 10px;
line-height: 20px;
min-width: 100px;
}
#content {
min-height: 840px;
margin-left: 140px;
width: 80%;
}
#tempchart {
margin-top: 0px;
}
#humchart {
margin-top: 20px;
}
#footer {
width: 100%;
min-height: 0px;
background-color: #F5F5DC;
text-align: center;
}
</style>
</head>
<body>
<div id='header'> </div>
<?php
//------------------------------------------------------
// Menue
//------------------------------------------------------
echo "<div id='menu'>\n";
foreach ($Chart AS $PERIOD => $DESCRIPTION) {
echo "• <a href='?period=".$PERIOD."' title='".$DESCRIPTION."'>Last ".$PERIOD."</a><br/>\n";
}
echo "</div>\n";
//------------------------------------------------------
// Select Measurements Table
//------------------------------------------------------
$tablesArray = explode(",", $tables);
if (count($tablesArray) == 1) {
$table = $tables;
} else {
if (isset($_POST['table'])) { $table = $_POST['table']; }
echo "<form action='' method='POST'>\n";
echo " <select name='db' size='1' onChange='this.form.submit();'>\n";
foreach($tablesArray AS $key => $t) {
if (isset($table) AND $table == $t) { $Selected=" selected"; } else { $Selected=""; }
echo " <option value='".$t."'".$Selected.">".$t."</option>\n";
}
echo " </select>\n";
echo "</form>\n";
}
if (!isset($table)) {
if (isset($_SESSION['table'])) {
$table = $_SESSION['table'];
} else {
$table = $tablesArray[0];
}
}
$_SESSION['table'] = $table;
//------------------------------------------------------
// Content / Charts
//------------------------------------------------------
echo "<div id='content'>\n";
echo " <div id='tempchart'> </div>\n";
echo " <div id='humchart'> </div>\n";
if (isset($_GET['period'])) {
$Period = $_GET['period'];
?>
<script src='highcharts/js/highcharts.js'></script>
<script src='highcharts/js/themes/grid.js'></script>
<script src='highcharts/js/modules/exporting.js'></script>
<script src='highcharts/js/modules/no-data-to-display.js'></script>
<script type='text/javascript'>
$(function() {
$(document).ready(function() {
// Global Chart Options
Highcharts.setOptions({
global: {
useUTC: false
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
},
xAxis: {
type: "datetime",
labels: {
style: {
"color":"#6D869F", "font-size":"10pt", "fontWeight":"bold"
}
}
},
legend: {
enabled: true
},
credits: {
enabled: false
},
colors: ["#4572A7", "#AA4643", "#89A54E", "#80699B", "#3D96AE", "#DB843D", "#92A8CD", "#A47D7C", "#B5CA92"]
});
// Chart: Temperatures
$.getJSON("data.php?type=temp&period=<?php echo $Period; ?>&table=<?php echo $table; ?>", function(json) {
var temp = new Highcharts.Chart({
series: json,
chart: {
type: "spline",
renderTo: "tempchart",
zoomType: 'x'
},
title: {
text: "<?php echo $table; ?> Temperatures <?php echo $Chart[$Period]; ?>"
},
tooltip: {
crosshairs: true,
useHTML: true,
valueDecimals: 2,
valueSuffix: ' °C'
},
yAxis: {
title: {
text: "Temperatures (°C)"
},
labels: {
formatter: function() {
return this.value +"°C"
},
style: {
"color":"#6D869F", "font-size":"10pt", "fontWeight":"bold"
}
}
},
plotOptions: {
series: {
lineWidth: 2,
marker: {
radius: 2
}
}
},
});
});
// Chart: Humidity
$.getJSON("data.php?type=hum&period=<?php echo $Period; ?>&table=<?php echo $table; ?>", function(json) {
var hum = new Highcharts.Chart({
series: json,
chart: {
type: "spline",
renderTo: "humchart",
zoomType: 'x'
},
title: {
text: "<?php echo $table; ?> Humidity <?php echo $Chart[$Period]; ?>"
},
tooltip: {
crosshairs: true,
useHTML: true,
valueDecimals: 2,
valueSuffix: ' %'
},
yAxis: {
title: {
text: "Humidity (%)"
},
labels: {
formatter: function() {
return this.value +"%"
},
style: {
"color":"#6D869F", "font-size":"10pt", "fontWeight":"bold"
}
}
},
plotOptions: {
series: {
lineWidth: 1,
marker: {
radius: 2
}
}
},
});
});
});
});
</script>
<?php
}
echo "</div>\n"; // END: content
//------------------------------------------------------
// Footer
//------------------------------------------------------
echo "\n<div id='footer'>\n";
echo "</div>\n";
?>
</body>
</html>
[/php]
data.php
[code=php]
<?php
//------------------------------------------------------
require_once('global.php');
//------------------------------------------------------
if (isset($_GET['type'])) {
if ($_GET['type'] == 'temp') {
$Type = 'temp';
} else {
$Type = 'hum';
}
if (isset($_GET['table']) AND !empty($_GET['table'])) { $table = $_GET['table']; }
if (isset($_GET['period'])) {
$Period = $_GET['period'];
// remove all numbers from period string (eg. from 12h so only h is left)
$PeriodUnit = preg_replace('/[0-9]+/', '', $Period);
// remove the Unit from period string so only numbers are left
$PeriodNum = str_replace($PeriodUnit, '', $Period);
} else {
$Period = '6h';
$PeriodUnit = preg_replace('/[0-9]+/', '', $Period);
$PeriodNum = str_replace($PeriodUnit, '', $Period);
}
$conid = mysql_con();
$db_selected = mysqli_select_db($conid, $database);
if (!$db_selected) { die('Cannot use Database '.$database.' : '.mysqli_error($conid)); }
// Get each "location"
$dataResult = array();
$result = query("SELECT location FROM ".$table." GROUP BY location");
while ($row = mysqli_fetch_array($result)) {
$data = array();
// Get Data from each "location"
$result2 = query("SELECT location,timestamp,".$Type." FROM ".$table."
WHERE location = '".$row['location']."'
AND timestamp >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL ".$PeriodNum." ".getPeriodUnit($Period)."))
AND timestamp <= UNIX_TIMESTAMP()
ORDER BY timestamp ASC
;");
while ($row2 = mysqli_fetch_array($result2)) {
if (!empty($row2[$Type])) {
$data['data'][] = array((float)($row2['timestamp']*1000), (float)$row2[$Type]);
}
}
if (isset($data['data'])) {
$data['name'] = $row['location'];
array_push($dataResult, $data);
}
}
mysqli_close($conid);
print json_encode($dataResult);
}
?>
[/php]
Euer Problem hängt damit zusammen das in der index.php kein $database definiert wird und somit dort auch nicht verwendet werden kann
Also bei mir klappt das mit dem $database. Siehe Anhang hier & Beitrag 62.
&database ist doch in der config.php definiert. Und die wird doch in der index.php eingebunden.
ZitatIch frag mich allerdings schon die Ganze Zeit was ihr da überhaupt vor habt. Als ich letzten Monat bei der Sache mit mehreren Datenbanken half dacht ich mir erst nichts böses, mehrere Datenbanken auf einer Webseite zu visualisieren ist ja noch Oke... Aber sofern ihr die ganze Zeit nur ein und den selben MySQL ...
Was towi macht weiss ich nicht.
Ich habe für jedes Projekt eine eigene Datenbank. Möchte auch nicht alle Projekt-Daten in einer DB haben.
Zudem gibt es bereits einen zweiten Pi zum Aufzeichnen. Da tut man sich mit einer einzigen DB etwas schwer.
Erfassungszeitraum pro Projekt geht bis zu 4 Monate. (Beitrag 1)
Zum Beispiel Projekt:
-Keller
-Dach
-Garage
-Werkstatt
-Wohnraum 1 bis x
Derzeit lasse ich es hier aber noch in der Wohnung laufen. Hab nicht damit gerechnet das es so informativ & interessant ist.
Du siehst, es passt es so wie es ist und ich es mir vorstellte :thumbs1:
Bis auf einen Haken den ich recht spät erkannte. Wenn ich mir die Daten aus einem, vor 4 Wochen, abgeschlossenem Projekt ansehen möchte, dann geht das nicht so einfach.
Ist kann z.B. die letzten 2/3 /7 Tage nicht sehen. (No Data for Display).
Weil ja von der realen/aktuellen Zeit ausgehen "abgefragt" wird. Und nicht vom letzten Eintrag aus. Tja, und je älter die Datenbank, um so problematischer.
Das konnte ich selbst noch nicht lösen. Darum hatte ich nachgefragt. :s
Oder wäre es gar besser das fertige Projekt als exl zu exportieren und da drauf zu zugreifen?
Naja, und das Sunset/Sunrice Geheimnis wird sich auch noch irgendwann mal lüften
Hallo zusammen,
danke erstmal - Arbeit fürs Wochenende, glaube ich.
Kurze Frage an meigrafd: Ich muss doch dann natürlich im 1.wire.py auch $Table definieren oder? Das ist ja momentan bei mir noch nicht geschehen.
Trotzdem schonmal vielen Dank
Bis auf einen Haken den ich recht spät erkannte. Wenn ich mir die Daten aus einem, vor 4 Wochen, abgeschlossenem Projekt ansehen möchte, dann geht das nicht so einfach.
Ist kann z.B. die letzten 2/3 /7 Tage nicht sehen. (No Data for Display).
Weil ja von der realen/aktuellen Zeit ausgehen "abgefragt" wird. Und nicht vom letzten Eintrag aus. Tja, und je älter die Datenbank, um so problematischer.
Die Auswahl des anzuzeigenden Zeitraums wird ja durch folgendes SQL Statement festgelegt:
[code=php]
AND timestamp >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL ".$PeriodNum." ".getPeriodUnit($Period)."))
AND timestamp <= UNIX_TIMESTAMP()
[/php]
Das macht also folgendes:
DATE_SUB(NOW(), INTERVAL ".$PeriodNum." ".getPeriodUnit($Period).")
^- Hier wird ein Datum Subtrahiert, NOW() gibt das jetzige Datum+Zeit (2014-11-22 13:23:44.657) zurück und das 2.Parameter wird davon dann abgezogen: $PeriodNum enthält zum Beispiel "12" und getPeriodUnit($Period) gibt zB "h" zurück - es würden dann also 12h abgezogen werden. Das alles dient dann als Parameter für UNIX_TIMESTAMP( und wandelt somit das Datum in einen timestamp um, damit die Auswahl "timestamp >=" funktioniert.
In der gezeigten 1.Zeile des SQL Statements werden also alle 'timestamp' Einträge größer-gleich dem abgezogenen Zeitraum von "jetzt" selektiert. In der 2.Zeile wiederum wird timestamp kleiner-gleich "jetzt" ausgewählt.
Hier müsste man dann also auch ansetzen und als Vergleichswert nicht "jetzt" verwenden sondern den letzten 'timestamp' Eintrag aus der Datenbank.
Man müsste also vorher bereits eine Abfrage machen um den gewünschten "ab wann"-Zeitraum aus der Datenbank raus zu fischen und dann die 1. Zeilen entsprechend anpassen. Dazu müsste es eigentlich reichen einfach den letzten 'timestamp' Eintrag aus der Datenbank-Tabelle raus zu ziehen:
[code=php]
// Get timestamp from last entry
$query = query("SELECT timestamp FROM data WHERE 1 ORDER BY timestamp DESC LIMIT 0,1");
$row = mysqli_fetch_assoc($query);
$lastTimestamp = $row["timestamp"];
if (empty($lastTimestamp)) { $lastTimestamp = time(); }
[/php]
Und dann die erste Zeile anpassen:
[code=php]
AND timestamp >= UNIX_TIMESTAMP(DATE_SUB(FROM_UNIXTIME(".$lastTimestamp."), INTERVAL ".$PeriodNum." ".getPeriodUnit($Period)."))
[/php]
Vollständig:
[code=php]
<?php
//------------------------------------------------------
require_once('global.php');
//------------------------------------------------------
if (isset($_GET['type'])) {
if ($_GET['type'] == 'temp') {
$Type = 'temp';
} else {
$Type = 'hum';
}
if (isset($_GET['db']) AND !empty($_GET['db'])) { $database = $_GET['db']; } else { end($DBhost); $database = key($DBhost); }
$dbhost = $DBhost[$database];
$dbport = $DBport[$database];
$dbuser = $DBuser[$database];
$dbpass = $DBpass[$database];
if (isset($_GET['period'])) {
$Period = $_GET['period'];
// remove all numbers from period string (eg. from 12h so only h is left)
$PeriodUnit = preg_replace('/[0-9]+/', '', $Period);
// remove the Unit from period string so only numbers are left
$PeriodNum = str_replace($PeriodUnit, '', $Period);
} else {
$Period = '6h';
$PeriodUnit = preg_replace('/[0-9]+/', '', $Period);
$PeriodNum = str_replace($PeriodUnit, '', $Period);
}
$conid = mysql_con();
$db_selected = mysqli_select_db($conid, $database);
if (!$db_selected) { die('Cannot use Database '.$database.' : '.mysqli_error($conid)); }
// Get timestamp from last entry
$query = query("SELECT timestamp,".$Type." FROM data WHERE 1 ORDER BY timestamp DESC LIMIT 0,1");
$row = mysqli_fetch_assoc($query);
$lastTimestamp = $row["timestamp"];
if (empty($lastTimestamp)) { $lastTimestamp = time(); }
// Get each "location"
$dataResult = array();
$result = query("SELECT location FROM data GROUP BY location");
while ($row = mysqli_fetch_array($result)) {
$data = array();
// Get Data from each "location"
$result2 = query("SELECT location,timestamp,".$Type." FROM data
WHERE location = '".$row['location']."'
AND timestamp >= UNIX_TIMESTAMP(DATE_SUB(FROM_UNIXTIME(".$lastTimestamp."), INTERVAL ".$PeriodNum." ".getPeriodUnit($Period)."))
AND timestamp <= UNIX_TIMESTAMP()
ORDER BY timestamp ASC
;");
while ($row2 = mysqli_fetch_array($result2)) {
if (!empty($row2[$Type])) {
$data['data'][] = array((float)($row2['timestamp']*1000), (float)$row2[$Type]);
}
}
if (isset($data['data'])) {
$data['name'] = $row['location'];
array_push($dataResult, $data);
}
}
mysqli_close($conid);
print json_encode($dataResult);
}
?>
[/php]...kann das aber grad nicht verifizieren...
//EDIT: Fehler gefunden, gefixt und verifiziert: http://RaspberryPi.RoXXs.org/charts2/
Aktuelle Dateien:
config.php
[code=php]
<?php
//------------------------------------------------------
// MySQL
//------------------------------------------------------
/*
if you have more than one Pi's whitch collect data and so
more than one database-server, add for each a setup.
*/
$DBhost["measurements"] = "localhost";
$DBport["measurements"] = 3306;
$DBuser["measurements"] = "root";
$DBpass["measurements"] = "passw0rd";
#$DBhost["Schlafzimmer"] = "localhost";
#$DBport["Schlafzimmer"] = 3306;
#$DBuser["Schlafzimmer"] = "root";
#$DBpass["Schlafzimmer"] = "passw0rd";
#$DBhost["Wand/Schrank"] = "localhost";
#$DBport["Wand/Schrank"] = 3306;
#$DBuser["Wand/Schrank"] = "root";
#$DBpass["Wand/Schrank"] = "passw0rd";
/*
CREATE TABLE `data` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
`location` VARCHAR(255),
`timestamp` INT(11),
`temp` FLOAT(11),
`hum` FLOAT(11),
`vcc` FLOAT(11),
PRIMARY KEY (`id`),
KEY `location` (`location`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
*/
//------------------------------------------------------
// Selectable Chart Ranges.
// Format: $Chart['<period>'] = '<chart title>';
// Example: $Chart['12h'] = 'of the last 12 hours';
// Valid Units: s=second,mi=Minute,h=hour,d=day,w=week,m=month,y=year
//------------------------------------------------------
$Chart['30mi'] = 'of the last 30 minutes';
$Chart['1h'] = 'of the last 1 hour';
$Chart['2h'] = 'of the last 2 hours';
$Chart['3h'] = 'of the last 3 hours';
$Chart['6h'] = 'of the last 6 hours';
$Chart['12h'] = 'of the last 12 hours';
$Chart['24h'] = 'of the last 24 hours';
$Chart['2d'] = 'of the last 2 days';
$Chart['3d'] = 'of the last 3 days';
$Chart['1w'] = 'of the last week';
$Chart['2w'] = 'of the last 2 weeks';
$Chart['1m'] = 'of the last month';
$Chart['3m'] = 'of the last 3 months';
$Chart['6m'] = 'of the last 6 months';
$Chart['1y'] = 'of the last year';
//------------------------------------------------------
?>
[/php]
global.php
[code=php]
<?php
if (!isset($_SESSION)) { session_start(); }
$TIMEOUT = "3600";
ini_set("session.gc_maxlifetime", $TIMEOUT); // default: 1440 seconds or 24 minutes
session_cache_limiter($TIMEOUT);
$DEBUG=0;
$showqueries=0;
error_reporting(E_ALL);
ini_set('track_errors', 1);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('memory_limit', '64M');
ini_set('max_execution_time', '30');
@ob_implicit_flush(true);
@ob_end_flush();
$Chart=array();
require_once("config.php");
require_once("functions.php");
?>
[/php]
data.php
[code=php]
<?php
//------------------------------------------------------
require_once('global.php');
//------------------------------------------------------
if (isset($_GET['type'])) {
if ($_GET['type'] == 'temp') {
$Type = 'temp';
} else {
$Type = 'hum';
}
if (isset($_GET['db']) AND !empty($_GET['db'])) { $database = $_GET['db']; } else { end($DBhost); $database = key($DBhost); }
$dbhost = $DBhost[$database];
$dbport = $DBport[$database];
$dbuser = $DBuser[$database];
$dbpass = $DBpass[$database];
if (isset($_GET['period'])) {
$Period = $_GET['period'];
// remove all numbers from period string (eg. from 12h so only h is left)
$PeriodUnit = preg_replace('/[0-9]+/', '', $Period);
// remove the Unit from period string so only numbers are left
$PeriodNum = str_replace($PeriodUnit, '', $Period);
} else {
$Period = '6h';
$PeriodUnit = preg_replace('/[0-9]+/', '', $Period);
$PeriodNum = str_replace($PeriodUnit, '', $Period);
}
$conid = mysql_con();
$db_selected = mysqli_select_db($conid, $database);
if (!$db_selected) { die('Cannot use Database '.$database.' : '.mysqli_error($conid)); }
// Get timestamp from last entry
$query = query("SELECT timestamp,".$Type." FROM data WHERE 1 ORDER BY timestamp DESC LIMIT 0,1");
$row = mysqli_fetch_assoc($query);
$lastTimestamp = $row["timestamp"];
if (empty($lastTimestamp)) { $lastTimestamp = time(); }
// Get each "location"
$dataResult = array();
$result = query("SELECT location FROM data GROUP BY location");
while ($row = mysqli_fetch_array($result)) {
$data = array();
// Get Data from each "location"
$result2 = query("SELECT location,timestamp,".$Type." FROM data
WHERE location = '".$row['location']."'
AND timestamp >= UNIX_TIMESTAMP(DATE_SUB(FROM_UNIXTIME(".$lastTimestamp."), INTERVAL ".$PeriodNum." ".getPeriodUnit($Period)."))
AND timestamp <= UNIX_TIMESTAMP()
ORDER BY timestamp ASC
;");
while ($row2 = mysqli_fetch_array($result2)) {
if (!empty($row2[$Type])) {
$data['data'][] = array((float)($row2['timestamp']*1000), (float)$row2[$Type]);
}
}
if (isset($data['data'])) {
$data['name'] = $row['location'];
array_push($dataResult, $data);
}
}
mysqli_close($conid);
print json_encode($dataResult);
}
?>
[/php]
index.php
[code=php]
<?php
//------------------------------------------------------
require_once('include/global.php');
//------------------------------------------------------
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="de">
<head>
<title>Sensor Charts</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="DISALLOW">
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/functions.js"></script>
<style type=text/css>
body {
font-size: 13pt;
color: black;
font-family: Verdana,arial,helvetica,serif;
margin: 0px;
background-color: #F5F5DC;
}
#header {
width: 100%;
min-height: 80px;
}
#menu {
font-size: 11pt;
color: #000;
float: left;
padding: 5px;
background-color: #F5F5DC;
margin: 0px 0px 0px 10px;
line-height: 20px;
min-width: 100px;
}
#content {
min-height: 840px;
margin-left: 140px;
width: 80%;
}
#tempchart {
margin-top: 0px;
}
#humchart {
margin-top: 20px;
}
#footer {
width: 100%;
min-height: 0px;
background-color: #F5F5DC;
text-align: center;
}
</style>
</head>
<body>
<div id='header'> </div>
<?php
//------------------------------------------------------
// Menue
//------------------------------------------------------
echo "<div id='menu'>\n";
foreach ($Chart AS $PERIOD => $DESCRIPTION) {
echo " • <a href='?period=".$PERIOD."' title='".$DESCRIPTION."'>Last ".$PERIOD."</a><br/>\n";
}
echo "</div>\n";
//------------------------------------------------------
// Content
//------------------------------------------------------
echo "<div id='content'>\n";
//------------------------------------------------------
// Select Measurements Database
//------------------------------------------------------
echo " <div id='selectDB'>\n";
if (isset($_SESSION['db'])) { $Database = $_SESSION['db']; }
if (isset($_POST['db'])) { $Database = $_POST['db']; }
echo " <form action='' method='POST'>\n";
echo " <select name='db' size='1' onChange='this.form.submit();'>\n";
foreach($DBhost AS $db => $data) {
if (isset($Database) AND $Database == $db) { $Selected=" selected"; } else { $Selected=""; }
echo " <option value='".$db."'".$Selected.">".$db."</option>\n";
}
echo " </select>\n";
echo " </form>\n";
echo " </div>\n";
if (!isset($Database)) {
if (isset($_SESSION['db'])) {
$Database = $_SESSION['db'];
} else {
end($DBhost);
$Database = key($DBhost);
}
}
$_SESSION['db'] = $Database;
//------------------------------------------------------
// Charts
//------------------------------------------------------
echo " <div id='tempchart'> </div>\n";
echo " <div id='humchart'> </div>\n";
if (isset($_GET['period'])) {
$Period = $_GET['period'];
?>
<script src='highcharts/js/highcharts.js'></script>
<script src='highcharts/js/themes/grid.js'></script>
<script src='highcharts/js/modules/exporting.js'></script>
<script src='highcharts/js/modules/no-data-to-display.js'></script>
<script type='text/javascript'>
$(function() {
$(document).ready(function() {
// Global Chart Options
Highcharts.setOptions({
global: {
useUTC: false
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
},
xAxis: {
type: "datetime",
labels: {
style: {
"color":"#6D869F", "font-size":"10pt", "fontWeight":"bold"
}
}
},
legend: {
enabled: true
},
credits: {
enabled: false
},
colors: ["#4572A7", "#AA4643", "#89A54E", "#80699B", "#3D96AE", "#DB843D", "#92A8CD", "#A47D7C", "#B5CA92"]
});
// Chart: Temperatures
$.getJSON("include/data.php?type=temp&period=<?php echo $Period; ?>&db=<?php echo $Database; ?>", function(json) {
var temp = new Highcharts.Chart({
series: json,
chart: {
type: "spline",
renderTo: "tempchart",
zoomType: 'x'
},
title: {
text: "<?php echo $Database; ?> Temperatures <?php echo $Chart[$Period]; ?>"
},
tooltip: {
crosshairs: true,
useHTML: true,
valueDecimals: 2,
valueSuffix: ' °C'
},
yAxis: {
title: {
text: "Temperatures (°C)"
},
labels: {
formatter: function() {
return this.value +"°C"
},
style: {
"color":"#6D869F", "font-size":"10pt", "fontWeight":"bold"
}
}
},
plotOptions: {
series: {
lineWidth: 2,
marker: {
radius: 2
}
}
},
});
});
// Chart: Humidity
$.getJSON("include/data.php?type=hum&period=<?php echo $Period; ?>&db=<?php echo $Database; ?>", function(json) {
var hum = new Highcharts.Chart({
series: json,
chart: {
type: "spline",
renderTo: "humchart",
zoomType: 'x'
},
title: {
text: "<?php echo $Database; ?> Humidity <?php echo $Chart[$Period]; ?>"
},
tooltip: {
crosshairs: true,
useHTML: true,
valueDecimals: 2,
valueSuffix: ' %'
},
yAxis: {
title: {
text: "Humidity (%)"
},
labels: {
formatter: function() {
return this.value +"%"
},
style: {
"color":"#6D869F", "font-size":"10pt", "fontWeight":"bold"
}
}
},
plotOptions: {
series: {
lineWidth: 1,
marker: {
radius: 2
}
}
},
});
});
});
});
</script>
<?php
}
echo "</div>\n"; // END: content
//------------------------------------------------------
// Footer
//------------------------------------------------------
echo "\n<div id='footer'>\n";
echo "</div>\n";
?>
</body>
</html>
[/php]
Naja, und das Sunset/Sunrice Geheimnis wird sich auch noch irgendwann mal lüften
irgend wann mal
Kurze Frage an meigrafd: Ich muss doch dann natürlich im 1.wire.py auch $Table definieren oder? Das ist ja momentan bei mir noch nicht geschehen.
Das habe ich letzte Nacht in der Tat nicht beachtet, aber ja in den Sensor-Scripts müsste man dann auch eine Tabelle angeben... mmh das is dann natürlich etwas doof.
Hallo zusammen,
so - nun ist es mir doch noch gelungen, wie Ruco es empfohlen hat und meigraft es im letzten Spoiler gezeigt hatte:
[code=php] text: " <?php echo $Database; ?> - Temperaturen <?php echo $Chart[$Period]; ?>"[/php]
Sieht dann schlussendlich so aus:
Damit kann ich prima leben besten Dank nochmals an Ruco und meigraft
Hallo und Frohe Weihnachten,
hab mir dies auch mal zum Gemüt geführt und versucht es nachzumachen.
Bin dazu auf Github -> https://github.com/meigrafd/HighCharts
Leider hakt es beim letzten Befehl:
sudo apt-get install python3-pip && sudo pip-3.2 install cymysql
Da bekomm ich ein "sudo: pip3.2: Kommando nicht gefunden" zurück.
Kann mir jemand helfen?
Karsten
Du hast denke ich eine andere Version von Python, und daher auch von pip. Welche Version hat er denn installiert? Kann man mit dpkg -L python3-pip nachschauen.
fürs schnelle reagieren!
Das ist die Ausgebe von dpkg -L python3-pip:
/.
/usr
/usr/share
/usr/share/doc
/usr/share/doc/python3-pip
/usr/share/doc/python3-pip/changelog.Debian.gz
/usr/share/doc/python3-pip/copyright
/usr/share/doc/python3-pip/changelog.gz
/usr/share/man
/usr/share/man/man1
/usr/share/man/man1/pip3.1.gz
/usr/lib
/usr/lib/python3
/usr/lib/python3/dist-packages
/usr/lib/python3/dist-packages/pip-1.5.6.egg-info
/usr/lib/python3/dist-packages/pip-1.5.6.egg-info/entry_points.txt
/usr/lib/python3/dist-packages/pip-1.5.6.egg-info/PKG-INFO
/usr/lib/python3/dist-packages/pip-1.5.6.egg-info/dependency_links.txt
/usr/lib/python3/dist-packages/pip-1.5.6.egg-info/not-zip-safe
/usr/lib/python3/dist-packages/pip-1.5.6.egg-info/top_level.txt
/usr/lib/python3/dist-packages/pip-1.5.6.egg-info/requires.txt
/usr/lib/python3/dist-packages/pip
/usr/lib/python3/dist-packages/pip/pep425tags.py
/usr/lib/python3/dist-packages/pip/basecommand.py
/usr/lib/python3/dist-packages/pip/index.py
/usr/lib/python3/dist-packages/pip/vcs
/usr/lib/python3/dist-packages/pip/vcs/subversion.py
/usr/lib/python3/dist-packages/pip/vcs/__init__.py
/usr/lib/python3/dist-packages/pip/vcs/git.py
/usr/lib/python3/dist-packages/pip/vcs/mercurial.py
/usr/lib/python3/dist-packages/pip/vcs/bazaar.py
/usr/lib/python3/dist-packages/pip/wheel.py
/usr/lib/python3/dist-packages/pip/commands
/usr/lib/python3/dist-packages/pip/commands/show.py
/usr/lib/python3/dist-packages/pip/commands/bundle.py
/usr/lib/python3/dist-packages/pip/commands/help.py
/usr/lib/python3/dist-packages/pip/commands/install.py
/usr/lib/python3/dist-packages/pip/commands/wheel.py
/usr/lib/python3/dist-packages/pip/commands/list.py
/usr/lib/python3/dist-packages/pip/commands/__init__.py
/usr/lib/python3/dist-packages/pip/commands/search.py
/usr/lib/python3/dist-packages/pip/commands/uninstall.py
/usr/lib/python3/dist-packages/pip/commands/completion.py
/usr/lib/python3/dist-packages/pip/commands/freeze.py
/usr/lib/python3/dist-packages/pip/commands/unzip.py
/usr/lib/python3/dist-packages/pip/commands/zip.py
/usr/lib/python3/dist-packages/pip/status_codes.py
/usr/lib/python3/dist-packages/pip/__init__.py
/usr/lib/python3/dist-packages/pip/locations.py
/usr/lib/python3/dist-packages/pip/__main__.py
/usr/lib/python3/dist-packages/pip/cmdoptions.py
/usr/lib/python3/dist-packages/pip/runner.py
/usr/lib/python3/dist-packages/pip/log.py
/usr/lib/python3/dist-packages/pip/backwardcompat
/usr/lib/python3/dist-packages/pip/backwardcompat/__init__.py
/usr/lib/python3/dist-packages/pip/baseparser.py
/usr/lib/python3/dist-packages/pip/exceptions.py
/usr/lib/python3/dist-packages/pip/req.py
/usr/lib/python3/dist-packages/pip/download.py
/usr/lib/python3/dist-packages/pip/util.py
/usr/bin
/usr/bin/pip3
Kannst du mir sagen wie es weiter gehen soll?
Grüße
Karsten
EDIT: es scheint zu funktionieren. Hab einfach mal ein sudo pip3 install cymysql abgesetzt...dann ging es.
Jetzt mal eine halbe Stunde warten und sehen ob sich die Chart füllt bzw. zeichnet.
*spendet ne Familienpackung Code Tags
Na, was sagt denn die Ausgabe? Es gibt genau *ein* Programm, naemlich /usr/bin/pip3. Versuch also das zu verwenden, statt pip3.4.
Hallo deets,
hab ich so gemacht siehe Post #77. Funktioniert! Danke.
Ein Problem hat sich aber noch aufgetan. Und zwar bekomm ich mein DHT22 nicht integriert. Es wird nichts in der zweiten Chart angezeigt.
Hab das Script dht.py, was in /usr/local/sbin liegt, mit dem Inhalt von meigraft angelegt.
#!/usr/bin/python3
# coding: utf-8
#
# Read DHT Sensors and write into MySQL Database for HighCharts
# 19.01.2016 Copyright (C) by meigrafd (meiraspi@gmail.com) published under the MIT License
#
# NOTE:
# Im using CyMySQL which is a fork of pymysql with speedups. See http://stackoverflow.com/a/25724855
#
#------------------------------------------------------------------------
import sys, time, os, re
#from decimal import Decimal, ROUND_HALF_UP
sensor_dict={}
#------------------------------------------------------------------------
#
#### CONFIG - START
# Specify Path to config.php File
phpConfigFile = '/var/www/html/charts/include/config.php' # angepasst
# DHT Sensor Type, GPIO pin and Place.
# Format: sensor_dict["<Place>"] = "<Type>;<GPIO>"
# E.g.: sensor_dict["Bath"] = "22;4"
# Types: 11 = DHT11 , 22 = DHT22 , 23 = AM2302
sensor_dict["Arbeitszimmer:DHT"] = "22;23" # angepasst
#### CONFIG - END
#
#------------------------------------------------------------------------
try:
import cymysql
except ImportError:
print("ERROR: You must install cymysql Module: sudo apt-get install python3-pip && sudo pip-3.2 install cymysql")
exit()
try:
import Adafruit_DHT
except ImportError:
print("ERROR: You must install Adafruit_DHT Python3 Module!")
exit()
# Try to read config.php to get mysql settings
# http://stackoverflow.com/questions/16881577/parse-php-file-variables-from-python-script
try:
pattern = re.compile(r"""(^)\$([a-z]*)\s*=\s*(.*?);$""")
php_config={}
with open(phpConfigFile) as fileObject:
for line in fileObject.readlines():
for match in pattern.finditer(line):
php_config[match.group(2)] = match.group(3).replace('"', '')
if php_config['dbhost']:
mysqlHost = php_config['dbhost']
else:
mysqlHost = "127.0.0.1"
if php_config['dbport']:
mysqlPort = php_config['dbport']
else:
mysqlPort = 3306
mysqlLogin = php_config['dbuser']
mysqlPass = php_config['dbpass']
mysqlDatabase = php_config['database']
except Exception as error:
print("Error reading config.php: %s" % str(error))
# This handles console colors used for print's
#http://misc.flogisoft.com/bash/tip_colors_and_formatting
class c:
ENDC='\33[0m'
DEFAULT='\33[39m'; BOLD='\33[1m'; DIM='\33[2m'
RESBOLD='\33[21m'; RESDIM='\33[22m'
RED='\33[31m'; GREEN='\33[32m'; YELLOW='\33[33m'; CYAN='\33[36m'
#https://github.com/liftoff/GateOne/blob/master/terminal/terminal.py#L358
def strtranslate(from_str):
translations = (
(u'\N{LATIN SMALL LETTER U WITH DIAERESIS}', u'ue'),
(u'\N{LATIN SMALL LETTER O WITH DIAERESIS}', u'oe'),
(u'\N{LATIN SMALL LETTER A WITH DIAERESIS}', u'ae'),
(u'\N{LATIN CAPITAL LETTER A WITH DIAERESIS}', u'Ae'),
(u'\N{LATIN CAPITAL LETTER O WITH DIAERESIS}', u'Oe'),
(u'\N{LATIN CAPITAL LETTER U WITH DIAERESIS}', u'Ue'),
(u'\N{LATIN SMALL LETTER SHARP S}', u'ss'),
# et cetera
)
out = from_str
for from_str, to_str in translations:
out = out.replace(from_str, to_str)
return out
class DhtSensorController():
def __init__(self, sensorType, gpioPin):
self.sensorType = sensorType
self.gpioPin = gpioPin
def readData(self):
if self.sensorType == 11:
sensor = Adafruit_DHT.DHT11
elif self.sensorType == 22:
sensor = Adafruit_DHT.DHT22
elif self.sensorType == 23:
sensor = Adafruit_DHT.AM2302
else:
self.readSuccess = False
raise Exception("Unknown sensor type. Use 11 for DHT11, 22 for DHT22 and 23 for AM2302")
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, self.gpioPin, retries=15, delay_seconds=2)
if humidity is not None and temperature is not None:
#temp = Decimal(temperature)
#hum = Decimal(humidity)
#self.temperature = Decimal(temp.quantize(Decimal('.01'), rounding=ROUND_HALF_UP))
#self.humidity = Decimal(hum.quantize(Decimal('.01'), rounding=ROUND_HALF_UP))
self.temperature = format(temperature, '.2f')
self.humidity = format(humidity, '.2f')
self.readSuccess = True
else:
self.readSuccess = False
print('Failed to get reading. Try again!')
def get_data():
for sensorPlace in sensor_dict:
sensorPlace = strtranslate(sensorPlace)
sensorType, sensorGPIO = sensor_dict.get(sensorPlace).split(';')
DHT = DhtSensorController(int(sensorType), int(sensorGPIO))
DHT.readData()
if DHT.readSuccess:
print('{0} -> {1}C , {2}%'.format(sensorPlace, DHT.temperature, DHT.humidity))
add_data(sensorPlace, DHT.temperature, DHT.humidity)
else:
print('{} -> None'.format(sensorPlace))
def add_data(Place, Temp, Hum):
Timestamp = int(time.time())
con = None
try:
con = cymysql.connect(host=mysqlHost, port=int(mysqlPort), user=mysqlLogin, passwd=mysqlPass)
cur = con.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS %s;" % mysqlDatabase)
cur.execute("USE %s;" % mysqlDatabase)
con.commit()
cur.execute("CREATE TABLE IF NOT EXISTS data (id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,location VARCHAR(255),timestamp INT(11),temp FLOAT(11),hum FLOAT(11),KEY location (location)) ENGINE=InnoDB DEFAULT CHARSET=utf8;")
con.commit()
cur.execute("INSERT INTO data (timestamp, location, temp, hum) VALUES (%s,%s,%s,%s);", (Timestamp, Place, Temp, Hum))
con.commit()
except Exception as err:
print(c.BOLD+c.RED+"MySQL Error: "+str(err)+c.ENDC)
except (KeyboardInterrupt, SystemExit):
sys.exit()
finally:
if con:
con.close()
if __name__ == '__main__':
try:
get_data()
except (KeyboardInterrupt, SystemExit):
print("\nSchliesse Programm..")
Alles anzeigen
Hab dann mein schon vorhandenen Adafruit_Python_DHT-Ordner in /usr/src/ kopiert und die setup.py dort ausgefürt und das dht.py ausführbar gemacht. Wenn ich es in der Konsole starte kommt:
Error reading config.php: 'dbhost'
Arbeitszimmer_DHT -> 14.90C , 53.60%
MySQL Error: name 'mysqlHost' is not defined
Weiß nicht wo ich da was Ändern muss, hab schon laut Fehlerausgabe versuche gestartet, aber ohne Erfolg.
Ich hoffe Ihr habt ne Idee und könnt helfen.
Karsten
Du hast noch kein Benutzerkonto auf unserer Seite? Registriere dich kostenlos und nimm an unserer Community teil!