guyute74
Posts: 17
Joined: Thu Feb 07, 2013 5:05 pm

Viewing sensor data on webpage from pi

Thu Feb 28, 2013 8:28 pm

Disclaimer - New to this!

I have followed the adafruit tutorials on attaching a DS18B20 Digital temperature sensor and magnetic contact switches to the breadboard and pi cobbler (http://learn.adafruit.com/adafruits-ras ... g/overview - http://learn.adafruit.com/adafruits-ras ... g-movement) and am able to see the input running the simple python script attached to the lessons.

Now, I'd like to push that data out to a webpage?
But I'm not sure where to begin or even what to google.
I am reading up on python as that seems to be what is next but was hoping maybe someone could help point me in the right direction.

In the end, I would like to have the current temperature and an open/close indication embedded on a webpage.

Thanks and really excited to be learning something new.
Christopher

(I would be happy to provide any more information as I'm not sure what is relevant.)

Hoagie
Posts: 119
Joined: Sun Sep 23, 2012 7:19 pm

Re: Viewing sensor data on webpage from pi

Fri Mar 01, 2013 8:02 am

Here's how I would do it, with a lot of things to google in bold. Don't google AJAX first, or you may get scared off.

I'd do it with a mostly static web page containing a bit of AJAX to periodically fetch the sensor readings from a CGI program on the Pi.

mini-httpd works well as the web server. Type "apt-get install mini-httpd" to install it. You'll need to configure it too, but it's not too hard.

A CGI is just a program, anything it outputs to the console will be sent via the web server to the browser, you can write it in any language you like. Just output something like 20,open. This makes it dead easy to test this part of the system, just run it from a shell prompt. You can also just type the URL of it in the address bar of the browser to check the data gets sent over correctly.

The AJAX is just javascript to fetch data from the web server. It uses a XMLHttpRequest to fetch data in the background. Make your life easy to begin with, and stick the javascript in the header of the page. Don't bother with XML encoding the data will be available in the responseText. When the data comes back, it calls another javascript function to handle it. That function can put the data onto the page. I'd have a HTML div element with an ID set for each value and use getelementbyid to be able to set it's innerhtml to the text you want to display.

If you decide to make graphs of the data, check out RRDTool.

Regards,
Geoff.

Corentin
Posts: 7
Joined: Thu Feb 28, 2013 10:32 am

Re: Viewing sensor data on webpage from pi

Fri Mar 01, 2013 1:35 pm

You could also use http://www.controlmypi.com/, which seems to aim at providing such service (I haven't tried it out, but I really like the idea)

guyute74
Posts: 17
Joined: Thu Feb 07, 2013 5:05 pm

Re: Viewing sensor data on webpage from pi

Fri Mar 01, 2013 1:51 pm

Excellent! Thanks for the clues. I've been searching around for the last few days and following a few lessons online wasn't sure if I was going in the right direction. I'll hit Google up during the 3 year old nap time today.
Again. Thanks for getting me in the right direction.
I will certainly have more questions later.

Christopher

myminimonster
Posts: 33
Joined: Sun Dec 30, 2012 11:08 pm
Location: Midlands UK

Re: Viewing sensor data on webpage from pi

Fri Mar 01, 2013 10:34 pm

I have done something like what Hoagie said on my webpage.

Here it is if its any help.
I call ajax from my webpage, which calls my cpu temperture python script. The temperate is then passed back to a div on my page.

Here is where i call it from on my webpage

Code: Select all

<div id="swiss"><a href="javascript:cputemp2()">Click to display CPU Temp</a></div>
This is the called script

Code: Select all

function cputemp2()
{

    $.ajax(
    {
        type: "POST",
        url: "cgi-bin/cputemp.py",
        dataType: "html",
        success: function(msg)
        {
        document.getElementById('swiss').innerHTML = msg;
        },


    });
}
and finally the python script (cputemp.py)

Code: Select all

#!/usr/bin/python
import cgi;
import cgitb;
import time
cgitb.enable()
import commands
import sys
import string
print "Content-type: text/html\n\n";
mytemp1 = commands.getoutput('/opt/vc/bin/vcgencmd measure_temp | cut -d "=" -f2 | cut -f1')
output = "Pi CPU Temp is: " + mytemp1
print output
I see you wanted to do it automatically but hopefully this gives you something to work with.

Hope this helps

Adie
Newbie

guyute74
Posts: 17
Joined: Thu Feb 07, 2013 5:05 pm

Re: Viewing sensor data on webpage from pi

Sat Mar 02, 2013 4:58 am

Excellent! I will try that next. The pieces are slowly coming together.

Christopher

guyute74
Posts: 17
Joined: Thu Feb 07, 2013 5:05 pm

Re: Viewing sensor data on webpage from pi

Sat Mar 02, 2013 6:12 pm

I found a lesson online to have the pi send an email when the magnetic door switch is tripped.
I have everything running per the adafruit tutorial which runs a local python script when the door is triggered but having trouble with javascript on this other website.
When I run the code, I get an open indication email regardless of switch position.
I was hoping maybe someone could make sense of it.

Thanks!
Christopher

This is the website I'm using for help.
http://blog.chr1s.at/2013/02/my-door-se ... e-and.html

and here is the code I am using from his site. (I change only the pin number and email information)


var gpio = require('rpi-gpio');
var email = require("emailjs/email");
var doorpin = 7; //the GPIO port you connected to the cicruit
var server = email.server.connect({
user: "your.username",
password:"YourPassword",
host: "smtp.gmail.com",
ssl: true});
var laststate = 1;

gpio.setup(doorpin, gpio.DIR_IN,readInput);

function readInput()
{
gpio.read(doorpin, function(err, value){
if(laststate!=value)
{
console.log(translateStatus(value));
server.send({ //sending email
text: translateStatus(value),
from: "Door <[email protected]>",
to: "somebody <[email protected]>",
subject: translateStatus(value)
}, function(err, message) { console.log(err || message); });
}
laststate = value;
});

setTimeout(readInput,1000); //recheck door every second
}

function translateStatus(s){
if(s==0) return 'The door is now open! '+getTime();
else return 'The door is now closed! '+getTime();
}

function getTime(){
var h = new Date().getHours();
var m = new Date().getMinutes();
var s = new Date().getSeconds();
if(h <10) h = '0'+h;
if(m <10) m = '0'+m;
if(s <10) s = '0'+s;
return h+':'+m+':'+s;
}

bouncymat
Posts: 38
Joined: Thu Feb 28, 2013 8:24 am

Re: Viewing sensor data on webpage from pi

Sun Mar 03, 2013 8:51 pm

i know its not quite what you asked for but...
i have mine set up to send the temperatures off to a google spread sheet

i can post the code tomorrow if you are interested.

guyute74
Posts: 17
Joined: Thu Feb 07, 2013 5:05 pm

Re: Viewing sensor data on webpage from pi

Sun Mar 10, 2013 9:33 pm

I would love to see the code to send temp data to a spreadsheet. I'm thinking I could make a graph from that data once I get it logging.
Thanks!
Christopher

bouncymat
Posts: 38
Joined: Thu Feb 28, 2013 8:24 am

Re: Viewing sensor data on webpage from pi

Mon Mar 11, 2013 6:35 am

here it is then.
I have very very little experience at this sort of thing and cobbled this code together from
http://www.raspberrypi.org/phpBB3/viewt ... 0&p=292189
and
http://learn.adafruit.com/adafruits-ras ... re-sensing

the sensor side of the code can cope with as many temp sensors as you throw at it but the google spreadsheet part needs modifying to match your spreadsheet.

Code: Select all

import time
import gdata.spreadsheet.service
import os
import subprocess
import glob
#set up temp sensor stuff
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')

#counts number of sensors
numberof=len(device_folder)
#sets lists
device_file=[0]*numberof
temp_c=[0]*numberof

for i in range (0,numberof):
    device_file[i] = device_folder[i] + '/w1_slave'

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

def read_temp():
    for ii in range (0,numberof):
        lines = read_temp_raw(ii)
        while lines[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines = read_temp_raw(ii)
        equals_pos = lines[1].find('t=')
        if equals_pos != -1:
            temp_string = lines[1][equals_pos+2:]
            temp_c[ii] = float(temp_string) / 1000.0
    return temp_c

#set up the google bit
email = '*******************'    #this is your full gmail address
password = '******************'            #this is your gmail password

spreadsheet_key = '*****************************************************************' # Find this value in the spreadsheet url with 'key=XXX' and copy XXX below
worksheet_id = 'od6' #This is the worksheet ID not sure how this works I "borrowed" this from one of the examples
   
def main():

   spr_client = gdata.spreadsheet.service.SpreadsheetsService()
   spr_client.email = email
   spr_client.password = password
   spr_client.source = 'temperature recorder'   #name of spreadsheet 
   spr_client.ProgrammaticLogin()

   temptosheet=(read_temp())
   temp1=str(temptosheet[0])
   temp2=str(temptosheet[1])

   dict = {} #the headers in this dictionary need to match the headers in the spreadsheet exactly
   dict['date'] = time.strftime('%d/%m/%Y')
   dict['time'] = time.strftime('%H:%M:%S')
   dict['temp1'] = temp1
   dict['temp2'] = temp2
   
   print dict #print for debugging

   entry = spr_client.InsertRow(dict, spreadsheet_key, worksheet_id)
   if isinstance(entry, gdata.spreadsheet.SpreadsheetsList):
     print "Insert row succeeded."
   else:
      return 0

if __name__ == '__main__':
    while True:
        try:
#            temptosheet=read_temp()
            main()
            time.sleep(120)
        except:
            print "Insert Row Failed!"
            time.sleep(1)
(you will probably want to remove all of the print lines)

and here is a link to the sheet it populates
https://docs.google.com/spreadsheet/ccc ... sp=sharing

guyute74
Posts: 17
Joined: Thu Feb 07, 2013 5:05 pm

Re: Viewing sensor data on webpage from pi

Fri Mar 15, 2013 12:02 am

Excellent! Thanks. Working great now

chiebhir
Posts: 2
Joined: Fri Oct 09, 2015 4:57 pm

Re: Viewing sensor data on webpage from pi

Mon Dec 14, 2015 2:42 pm

i want to send data from raspberry to other raspberry, this step can be work too ? or any other step ? thanks for help

mtperlma
Posts: 1
Joined: Sun Jun 25, 2017 4:16 pm

Re: Viewing sensor data on webpage from pi

Sun Jun 25, 2017 4:18 pm

myminimonster

What location is the cputemp.py and the function cputemp2 stored?

Return to “Automation, sensing and robotics”