Jeśli udało nam się pomyślnie zainstalować i sprawdzić działanie termometru cyfrowego DS18B20 przy pomocy strony https://malinowo.secu.com.pl/raspberry-pi-cyfrowy-termometr-ds18b20/ możemy przejść do napisania skryptu w języku python służącego do cyklicznego zapisu temperatury do bazy MySQL. Wyniki zostaną zaprezentowane w postaci wykresów opartych o bibliotekę Highcharts.
Przygotowanie systemu
Instalacja serwera i klienta MySQL oraz obsługi w php:
1 2 3 4 |
sudo apt-get install mysql-server mysql-client php5-mysql sudo aptitude install php5-mysql php5-curl php5-gd php5-idn php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-mhash php5-ming php5-ps php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl php5-json |
Instalacja pythona:
1 2 |
sudo apt-get install python-dev apt-get install python-mysqldb |
Przygotowanie bazy MySQL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
sudo mysql -u root -p CREATE DATABASE pi_base; GRANT ALL ON pi_base.* to 'pi_user'@'localhost' IDENTIFIED BY 'HasloUsera'; FLUSH PRIVILEGES; select host, user, password from mysql.user; USE pi_base; CREATE TABLE temperature_monitor ( counter INT NOT NULL AUTO_INCREMENT, thermometer VARCHAR(45) NOT NULL, date DATETIME NOT NULL, temperature FLOAT NOT NULL, PRIMARY KEY (counter), UNIQUE INDEX counter_UNIQUE (counter ASC)); INSERT INTO temperature_monitor (counter,thermometer,date,temperature) VALUE (NULL,'28-000006bec4c5',NOW(),0.5); |
DS18B20TempMysql.py
skrypt pobiera aktualną temperaturę czujnika i zapisuje ją do bazy danych.Kolejne czujniki dodajemy po przecinku,w tablicy thermometer_list. W conn ustawiamy parametry połączenia z bazą danych MySQL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
#!/usr/bin/python import MySQLdb import os import time import datetime import glob from time import strftime """DS18B20TempMysql.py: Insert sensor temperature to MySQL database """ __author__ = "zbiros" __copyright__ = "Copyright 2015, Malinowo.net.pl" __credits__ = ["maros"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "zbiros" __email__ = "zbiros@malinowo.secu.com.pl" __status__ = "Development" # add another thermometer separated by a comma thermometers_list = ["28-000006bec4c5"] # reading a temperature value from a file def read_temp_from_file(thermometer): sensor_file = '/sys/bus/w1/devices/' + thermometer + '/w1_slave' t = open(sensor_file, 'r') lines = t.readlines() t.close() temp_output = lines[1].find('t=') if temp_output != -1: temp_string = lines[1].strip()[temp_output+2:] temp_c = float(temp_string)/1000.0 return float(round(temp_c,1)) # adds a record to the database def insert_temp_reading (thermometer,temperature): conn = MySQLdb.connect("localhost","pi_user","HasloUsera","pi_base" ) cursor = conn.cursor() params = [thermometer,temperature] try: cursor.execute("INSERT INTO temperature_monitor (counter,thermometer,date,temperature) VALUE (NULL,%s,NOW(),%s)",params) conn.commit() except MySQLdb.Error, e: print "An error has occurred. %s" %e finally: cursor.close() conn.close() # main section def main(): for id_thermometer in thermometers_list: current_temp = read_temp_from_file (id_thermometer) insert_temp_reading (id_thermometer,current_temp) print "Thermometer:" + id_thermometer + "|Value:" + `current_temp` if __name__ == '__main__': main() |
skrypt można dodać do crontaba i uruchamiać np. co 5 minut lub o dowolnej innej porze:
Po jego uruchomieniu w bazie danych pojawiają się rekordy zawierające zmiany temperatur.
show_temp.php
Prosta strona php wyświetlająca zapisane w bazie rekordy z odczytem temperatur.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<? error_reporting(E_ALL); ini_set('display_errors', 1); ?> <HTML> <HEAD> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <TITLE>Temperatura na zewnątrz</TITLE> <style type="text/css"> <!-- BODY { color: #353535; font-family: Tahoma, Verdana, MS Sans Serif, Arial CE, Arial, Helvetica; font-size: 9pt; background-color: #EEE; margin-left: 100; margin-top: 25; } table, th, td { border: 1px solid black; } td { padding: 10px; } --> </style> </HEAD> <BODY> <h2>Temperatura na zewnątrz</h2> <table border="0"> <tr> <td>LP</td> <td>CZUJNIK</td> <td>DATA</td> <td>TEMPERATURA</td> </tr> <? mysql_connect('localhost',"pi_user","HasloUsera"); @mysql_select_db("pi_base") or die( "Unable to select database"); $result = mysql_query ("SELECT * FROM temperature_monitor;") or die ("error select"); while ($record = mysql_fetch_array ($result)) { $counter = $record[0]; $thermometer = $record[1]; $date = $record[2]; $temperature = $record[3]; echo "<tr> <td> $counter </td> <td> $thermometer </td> <td> $date </td> <td> $temperature </td> </tr> "; } ?> </table> </BODY> </HTML> |
Wynik działania powyższej strony:
Czujnik do kupienia w:
http://botland.com.pl/czujniki-temperatury/165-cyfrowy-termometr-ds18b20-tht.html