Json live temperature update

Get temperature with DS18B20 and save live update with python+php+Json
You can buy DS18B20 from ebay, cost >1$ and you need RaspberryPi.
Full tutorial
temp.py
import os
import glob
import time

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c, temp_f
   
while True:
    print(read_temp())
    deg_c, deg_f = read_temp()
    msg='<?php echo json_encode(array( "author" => "razib","tweet" => "Temparature is: " . '+str(deg_c)+',"date" => date("l jS \of F Y h:i:s A"))); ?>'
    f = open('/var/www/python/feed.php','w')
    f.write(msg)
    f.close()
    time.sleep(1)

 


index.php
<html>
<head><title>Tweets</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<style>
#tweets {
    width: 500px;
    font-family: Helvetica, Arial, sans-serif;
}
#tweets li {
    background-color: #E5EECC;
    margin: 2px;
    list-style-type: none;
}
.author {
    font-weight: bold
}
.date {
    font-size: 10px;
}
</style>

<script>
jQuery(document).ready(function() {
    setInterval("showNewTweets()", 1000);
});

function showNewTweets() {
    $.getJSON("feed.php", null, function(data) {
        if (data != null) {
            $("#tweets").prepend($("<li><span class=\"author\">" + data.author + "</span> " +  data.tweet + "<br /><span class=\"date\">" + data.date + "</span></li>").fadeIn("slow"));
        }
    });
}
</script>

</head>
<body>

<ul id="tweets"></ul>

</body>
</html>

feed.php
<?php
echo json_encode(array( "author" => "razib",
                        "tweet" => "The time is: " . time(),
                        "date" => date('l jS \of F Y h:i:s A')));
?>

crontab -e

Just add to your crontab
* * * * * for i in {0..59};

No comments:

Post a Comment