User avatar
richiepp
Posts: 140
Joined: Wed Dec 19, 2012 4:56 pm

ds18b20 send multiple sensor data to Cosm

Sat Apr 13, 2013 6:40 pm

Hey All,
I've got a python script that reads a DS18b20 temp sensor and pushes it to cosm.com . I currently have multiple sensors installed but my script is only reading and pushing one of the sensors. How can I tweak this to send multiple sensor info? I know each sensor has a unique ID but the script I'm using doesn't ask for the ID it just points to the devices folder /sys/bus/w1/devices/

Here is the code I'm using that works with one sensor. How can I make it work with 2 or more?

#!/usr/bin/env python
# DS18B20 Temperature script derived from Adafruit http://learn.adafruit.com/adafruits-ras ... g/software
# json->cosm script from cosm.py Copyright 2012 Itxaka Serrano Garcia <itxakaserrano@gmail.com>
# licensed under the GPL2
# see the full license at http://www.gnu.org/licenses/gpl-2.0.txt
#
# This script will read your DS18B20 temperature then upload the data to cosm.com. It includes the CRC check to eliminate errors.
# You only need to add 2 things, YOUR_API KEY HERE and YOUR_FEED_NUMBER_HERE
# also, you can change your stream ids, in that case change the id names in the "data = json.dumps..." line

import os
import glob
import time
import json
import subprocess

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:]
# Read temp, set proper decimal place for C, then convert to F. Separate /1000 and * 1.8 + 32 if you want separate C and F readings
temp = float(temp_string) / 1000.0 * 1.8 + 32
# Round temp to 2 decimal points
temp = round(temp, 2)
return temp

while True:
# Uncomment print command to print output
#print(read_temp())

# Send the data to Cosm
temp = read_temp()
data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"Temperature","current_value":temp}]})

with open("temp.tmp", "w") as f:
f.write(data)

subprocess.call(['curl --request PUT --data-binary @temp.tmp --header "X-ApiKey: NOT_SHARING_THIS_HERE" http://api.cosm.com/v2/feeds/124439'], shell=True)

os.remove("temp.tmp")
break

timhoffman
Posts: 85
Joined: Sat Nov 05, 2011 11:31 pm

Re: ds18b20 send multiple sensor data to Cosm

Sun Apr 14, 2013 11:13 am

Hi

I log multiple arduino feeds via my raspi to cosm. I find it much easier to use eeml and post directly rather than shelling out to curl.

You can see example code here which is feeding multiple different temps. https://bitbucket.org/zutesmog/security ... ult#cl-158

You can see the cosm feed here https://cosm.com/feeds/54118

It is actually a twisted http server monitoring serial port of connected JeeNode (RF relay) so I can send commands to remote JeenNodes (turn lights on, monitor temp, water level, movement etc). The main thing is you define named feeds in cosm, then specify the names as part of an eeml document that you construct and then POST to cosm. I use the python requests lib which makes this much easier.

Twisted is particularly nice as it allows you to receive serial data as well as web requests without a busy/wait look.

Hope this helps

Cheers

Tim

User avatar
DeeJay
Posts: 2027
Joined: Tue Jan 01, 2013 9:33 pm
Location: East Midlands, UK

Re: ds18b20 send multiple sensor data to Cosm

Sun Apr 14, 2013 11:31 am

richiepp wrote:
Here is the code I'm using that works with one sensor. How can I make it work with 2 or more?


base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
I'd say the restriction is the line

Code: Select all

device_folder = glob.glob(base_dir + '28*')[0]
which is only giving you the first device that starts '28'

I reckon you need a loop that processes ALL the entries that match.
How To Ask Questions The Smart Way: http://www.catb.org/~esr/faqs/smart-questions.html
How to Report Bugs Effectively: http://www.chiark.greenend.org.uk/~sgtatham/bugs.html

User avatar
richiepp
Posts: 140
Joined: Wed Dec 19, 2012 4:56 pm

Re: ds18b20 send multiple sensor data to Cosm

Mon Apr 15, 2013 9:34 pm

Yeah that seems to be where I need to tweak the script.

Here are the IDs of my 2 sensors
28-000003608f6f
28-000003b7260f

could I do something like this?

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

base_dir_2 = '/sys/bus/w1/devices/'
device_folder_2 = glob.glob(base_dir_2 + '28*')[0]
device_file_2 = device_folder_2 + '/w1_slave'

Or perhaps something like this

device_file_1 = /sys/bus/w1/devices/28-000003608f6f
device_file_2 = /sys/bus/w1/devices/28-000003b7260f

From there I could add additional functions for each sensor? Seems kinda sloppy to do it this way. What are best practices?

Thanks
Rich

User avatar
DeeJay
Posts: 2027
Joined: Tue Jan 01, 2013 9:33 pm
Location: East Midlands, UK

Re: ds18b20 send multiple sensor data to Cosm

Tue Apr 16, 2013 7:07 am

With method 1 I think you always get the first sensor. Method 2 might work now, but then you have to rework it if you add a third sensor.

Why not fix it now for any number of sensors? I suggest looking up how to use a 'for' loop. It will introduce you to a python feature known as an iterator, which is very useful in cases like this.
How To Ask Questions The Smart Way: http://www.catb.org/~esr/faqs/smart-questions.html
How to Report Bugs Effectively: http://www.chiark.greenend.org.uk/~sgtatham/bugs.html

User avatar
richiepp
Posts: 140
Joined: Wed Dec 19, 2012 4:56 pm

Re: ds18b20 send multiple sensor data to Cosm

Wed Apr 17, 2013 1:23 pm

Ok, I've been reading up on for loops and iterations. Here's how I'm understanding it now. I have no idea if I'm on the right track or not.

Use a for loop to read the 2 sensors

for x in range (0,1)
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0] # what does this bracketed zero do?
device_file = device_folder + '/w1_slave'

From there I guess I need to iterate over the 2 functions
readTemp.__iter__() # this is the only line I've added to the functions
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:]
# Read temp, set proper decimal place for C, then convert to F. Separate /1000 and * 1.8 + 32 if you want separate C and F readings
temp = float(temp_string) / 1000.0 * 1.8 + 32
# Round temp to 2 decimal points
temp = round(temp, 2)
return temp

If the above is correct I need to send the 2 or more sensors info to the while loop. I have no idea how to do this.
while True:
# Send the data to Cosm
temp = read_temp()
data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"Temperature","current_value":temp}]})

with open("temp.tmp", "w") as f:
f.write(data)

subprocess.call(['curl --request PUT --data-binary @temp.tmp --header "X-ApiKey: zSKrL5GapHg7XjEuk0T-bqd6fqqSAKxyRU1WRTJqWk5HZz0g" http://api.cosm.com/v2/feeds/124439'], shell=True)

os.remove("temp.tmp")
break

User avatar
richiepp
Posts: 140
Joined: Wed Dec 19, 2012 4:56 pm

Re: ds18b20 send multiple sensor data to Cosm

Mon May 13, 2013 8:56 pm

Hey All,
I'm still trying to get this going and not getting very far. I've read up on for loops and loops in general but I'm still not able to put the pieces together.

My goal is to read multiple DS18b20's and send the data to Cosm. Here's what I think needs to be done.

The for loop will look for the devices in the /sys/bus/w1/devices/ folder. Right now this just returns the same device 2 times. How can I make it show the two sensors I have hooked up to my Pi? I'd like to have as many as 8 sensors

for sensors in range (2):
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
print device_file

From there I think I need to send the readings through the 2 functions and then to the while loop. How do I send multiple variables to the 2 functions in this script? From there I need to send the data to COSM. Looks like it needs something in the data line but I have no idea what.

Any and all help is appreciated.

Thx!

sprinkmeier
Posts: 410
Joined: Mon Feb 04, 2013 10:48 am
Contact: Website

Re: ds18b20 send multiple sensor data to Cosm

Mon May 13, 2013 9:35 pm

Can you re-post your code inside "code" tags?
indentation is kinda important in python :-)

The changes will probably start with something like

Code: Select all

    for device_folder = glob.glob(base_dir + '28*'):
        # do stuff.... (note the indent!)
rather than

Code: Select all

    device_folder = glob.glob(base_dir + '28*')[0]
    # do stuff....

User avatar
richiepp
Posts: 140
Joined: Wed Dec 19, 2012 4:56 pm

Re: ds18b20 send multiple sensor data to Cosm

Mon May 13, 2013 10:29 pm

Code: Select all

import os
import glob
import time
import json
import subprocess

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

temp_sensors = 0

# The following is the only line of the script I've added.
# I need this to loop determine how many sensors are hooked up
# and then pass the variables to the functions and finally send
# the various sensor data to cosm.

for sensors in range (0,2):  
    base_dir = '/sys/bus/w1/devices/'
    device_folder = glob.glob(base_dir + '28*')[0]
    device_file = device_folder + '/w1_slave'
    print device_file


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:]
        # Read temp, set proper decimal place for C, then convert to F. Separate /1000 and * 1.8 + 32 if you want separate C and F readings
        temp = float(temp_string) / 1000.0 * 1.8 + 32
        # Round temp to 2 decimal points
        temp = round(temp, 2)
        return temp

while True:
        # Uncomment print command to print output
        #print(read_temp())

        # Send the data to Cosm
        temp = read_temp()
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"Temperature","current_value":temp}]})

        with open("temp.tmp", "w") as f:
            f.write(data)

        subprocess.call(['curl --request PUT --data-binary @temp.tmp --header "X-ApiKey: zSKrL5GapHg7XjEuk0T-bqd6fqqSAKxyRU1WRTJqWk5HZz0g" http://api.cosm.com/v2/feeds/124439'], shell=True)

        os.remove("temp.tmp")
	break



User avatar
richiepp
Posts: 140
Joined: Wed Dec 19, 2012 4:56 pm

Re: ds18b20 send multiple sensor data to Cosm SOLVED

Tue May 14, 2013 3:51 am

SOLVED
Ok, I kept playing, got some help and I now have it working!

Code: Select all

#!/usr/bin/env python
# DS18B20 Temperature script derived from Adafruit http://learn.adafruit.com/adafruits-raspberry-pi-lesson-11-ds18b20-temperature-sensing/software
# json->cosm script from cosm.py Copyright 2012 Itxaka Serrano Garcia <itxakaserrano@gmail.com>
# licensed under the GPL2
# see the full license at http://www.gnu.org/licenses/gpl-2.0.txt
#
# This script will read your DS18B20 temperature then upload the data to cosm.com. It includes the CRC check to eliminate errors.
# You only need to add 2 things, YOUR_API KEY HERE and YOUR_FEED_NUMBER_HERE
# also, you can change your stream ids, in that case change the id names in the "data = json.dumps..." line

import os
import glob
import time
import json
import subprocess

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

# add more sensor variables here based on your setup
temp_0 = 0
temp_1 = 0

for sensors in range (2): # change this number based on the number of sensors you're using.
    base_dir = '/sys/bus/w1/devices/'
    device_folder = glob.glob(base_dir + '28*')[sensors]
    device_file = device_folder + '/w1_slave'
    #print device_file


    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:]
        # Read temp, set proper decimal place for C, then convert to F. Separate /1000 and * 1.8 + 32 if you want separate C and F readings
            temp = float(temp_string) / 1000.0 * 1.8 + 32
        # Round temp to 2 decimal points
            temp = round(temp, 2)
            return temp

    if sensors == 0:
            temp_0 = read_temp()
            temp_1 = read_temp()
    else:
            temp_1 = read_temp()

            print temp_0
            print temp_1

while True:
        # Send the data to Cosm
        temp = read_temp()
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"Living_rm_temp","current_value":temp_0}]})
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"Outside","current_value":temp_1}]})

        with open("temp.tmp", "w") as f:
            f.write(data)

        subprocess.call(['curl --request PUT --data-binary @temp.tmp --header "X-ApiKey: YOUR_API_KEY_HERE" http://api.cosm.com/v2/feeds/124439'], shell=True)

        os.remove("temp.tmp")
	break


User avatar
richiepp
Posts: 140
Joined: Wed Dec 19, 2012 4:56 pm

Re: ds18b20 send multiple sensor data to Cosm

Wed May 15, 2013 1:41 pm

Ugh! the day after I got this working the company changed hands so Cosm, formerly Pachube, is now owned by Xively.
https://xively.com/?from_cosm=true

They have maintained legacy connections but now have a whole new interface. Not sure how well this script will work with the new system.... I'll keep working on it in the coming days and weeks....

R

eccentricdyslexic
Posts: 157
Joined: Thu Jul 18, 2013 6:13 am
Location: Uttoxeter, Staffordshire, UK

Re: ds18b20 send multiple sensor data to Cosm

Sun Aug 11, 2013 7:39 am

Hi Richiepp,

I thank you for your code, i have modified it to read my 10 sensors, but am having problems that you might be able to help me with. Here is the code-

Code: Select all

#!/usr/bin/env python#

import os
import glob
import time
import json
import subprocess

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

# add more sensor variables here based on your setup
temp_0 = 0
temp_1 = 0
temp_2 = 0
temp_3 = 0
temp_4 = 0
temp_5 = 0
temp_6 = 0
temp_7 = 0
temp_8 = 0
temp_9 = 0

for sensors in range (10): # change this number based on the number of sensors you're using.
    base_dir = '/sys/bus/w1/devices/'
    device_folder = glob.glob(base_dir + '28*')[sensors]
    device_file = device_folder + '/w1_slave'
    print device_file
    print sensors

    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:]
        # Read temp, set proper decimal place for C
            temp = float(temp_string) / 1000.0
        # Round temp to 2 decimal points
            temp = round(temp, 2)
            return temp
  
  if sensors == 0:
                temp_0 = read_temp()
    if sensors == 1:
                temp_1 = read_temp()
    if sensors == 2:
                temp_2 = read_temp()
    if sensors == 3:
                temp_3 = read_temp()
    if sensors == 4:
                temp_4 = read_temp()
    if sensors == 5:
                temp_5 = read_temp()
    if sensors == 6:
                temp_6 = read_temp()
    if sensors == 7:
                temp_7 = read_temp()
    if sensors == 8:
                temp_8 = read_temp()
    if sensors == 9:
                temp_9 = read_temp()

    print read_temp()

while True:
        # Send the data to Cosm
        temp = read_temp()
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"SolarFlow","current_value":temp_0}]})
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"SolarReturn","current_value":temp_1}]})
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"BufferIn","current_value":temp_2}]})
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"BufferOut","current_value":temp_3}]})
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"UFH_Flow","current_value":temp_4}]})
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"GSHP_Flow","current_value":temp_5}]})
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"GSHP_WellReturn","current_value":temp_6}]})
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"GSHP_LoopsReturn","current_value":temp_7}]})
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"HotWaterTank","current_value":temp_8}]})
        data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"HotWaterPreHeatTank","current_value":temp_9}]})

        with open("temp.tmp", "w") as f:
            f.write(data)

        subprocess.call(['curl --request PUT --data-binary @temp.tmp --header "X-ApiKey: AR4soQUW2udfgadgasdasdfsdsadsdsaddd" http://api.cosm.com/v2/feeds/2768467'], shell=True)

        os.remove("temp.tmp")
        break
This code seems to work now for me, but i cant seem to get Xively to pull in the new names and values? It seems to only have imported HotWaterPreHeatTank....

Any help apreciated!

Steve

sprinkmeier
Posts: 410
Joined: Mon Feb 04, 2013 10:48 am
Contact: Website

Re: ds18b20 send multiple sensor data to Cosm

Sun Aug 11, 2013 10:22 am

Rather than manually telling the program how many sensors, why not have it work that out for itself?

Code: Select all

base_dir = '/sys/bus/w1/devices/'

temps = {}
for device_folder = glob.glob(base_dir + '28*'):
    device_file = device_folder + '/w1_slave'
    device = os.path.split(device_folder)[1]

    def read_temp_raw():
        #...
    def read_temp():
        #...
    temps[device] = read_temp()

eccentricdyslexic
Posts: 157
Joined: Thu Jul 18, 2013 6:13 am
Location: Uttoxeter, Staffordshire, UK

Re: ds18b20 send multiple sensor data to Cosm

Sun Aug 11, 2013 10:39 am

Thanks for that, any simplfication is welcome! I will be adding more sensors soon too, so if some code was automatic, that's a good thing! Just need to match the rest of the code now.

Also need to sort issue with uploading though ;)

Steve

sprinkmeier
Posts: 410
Joined: Mon Feb 04, 2013 10:48 am
Contact: Website

Re: ds18b20 send multiple sensor data to Cosm

Mon Aug 12, 2013 9:00 pm

try:
subprocess.call(['curl',
'--request', 'PUT',
'--data-binary', '@temp.tmp',
'--header', 'X-ApiKey: AR4soQUW2udfgadgasdasdfsdsadsdsaddd',
'http://api.cosm.com/v2/feeds/2768467'], shell=True)

kkasberg
Posts: 3
Joined: Fri Jan 25, 2013 1:26 pm

Re: ds18b20 send multiple sensor data to Cosm

Tue Dec 17, 2013 6:00 pm

I worked on this a while, and what I ended up with was this. It looks for all sensor folders in the directory and prints out the datetime of the reading, the sensors folder name (serial number) and the temp readings. I hope that this is helpful to others out there.

Code: Select all

import os
import glob
import time
from datetime import datetime

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
device_folder = ''
evice_file = ''

def read_temps_multi():
        base_dir = '/sys/bus/w1/devices/'
        for device in glob.glob(base_dir + '28*'):
                global device_folder
                global device_file
                device_folder = device
                device_file = device_folder + '/w1_slave'
                print(read_temp())

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

def read_temp():
    lines = read_temp_raw()
    date = str(datetime.now())[:16]
    sensor = device_folder[-15:]
    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 date, sensor, temp_c, temp_f

while True:
        read_temps_multi()
        time.sleep(1)

HenrikN
Posts: 10
Joined: Fri Mar 15, 2013 5:49 pm

Re: ds18b20 send multiple sensor data to Cosm

Tue Dec 31, 2013 9:40 pm

Have anyone had any luck sending the data to xively(cosm) yet?

eccentricdyslexic
Posts: 157
Joined: Thu Jul 18, 2013 6:13 am
Location: Uttoxeter, Staffordshire, UK

Re: ds18b20 send multiple sensor data to Cosm

Wed Jan 01, 2014 7:12 am

Yes, I am reliably doing this for that last 6months or so. Will post my code shortly....

Steve

HenrikN
Posts: 10
Joined: Fri Mar 15, 2013 5:49 pm

Re: ds18b20 send multiple sensor data to Cosm

Wed Jan 01, 2014 11:10 pm

eccentricdyslexic wrote:Yes, I am reliably doing this for that last 6months or so. Will post my code shortly....

Steve
That would be very much appreciated!

eccentricdyslexic
Posts: 157
Joined: Thu Jul 18, 2013 6:13 am
Location: Uttoxeter, Staffordshire, UK

Re: ds18b20 send multiple sensor data to Cosm

Thu Jan 02, 2014 2:17 pm

Here you go-

Code: Select all

[/#!/usr/bin/env python#

import os
import glob
import time
import json
import subprocess
import eeml
import sys
import syslog

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

# add more sensor variables here based on your setup
temp_0 = 0
temp_1 = 0
temp_2 = 0
temp_3 = 0
temp_4 = 0
temp_5 = 0
temp_6 = 0
temp_7 = 0
temp_8 = 0
temp_9 = 0

for sensors in range (10): # change number of sensors based on your setup
    base_dir = '/sys/bus/w1/devices/'
    device_folder = glob.glob(base_dir + '28*')[sensors]
    device_file = device_folder + '/w1_slave'
    print device_file
    print sensors

    def read_temp_raw(): # gets the temps one by one
        f = open(device_file, 'r')
        lines = f.readlines()
        f.close()
        return lines

    def read_temp(): # checks the temp recieved for errors
        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:]
       # set proper decimal place for C
            temp = float(temp_string) / 1000.0
        # Round temp to 2 decimal points
            temp = round(temp, 1)
            return temp

 # ask for temps to be read and store each in a variable
    if sensors == 0:
                temp_0 = read_temp()
    if sensors == 1:
                temp_1 = read_temp()
    if sensors == 2:
                temp_2 = read_temp()
    if sensors == 3:
                temp_3 = read_temp()
    if sensors == 4:
                temp_4 = read_temp()
    if sensors == 5:
                temp_5 = read_temp()
    if sensors == 6:
                temp_6 = read_temp()
    if sensors == 7:
                temp_7 = read_temp()
    if sensors == 8:
                temp_8 = read_temp()
    if sensors == 9:
                temp_9 = read_temp()

    print read_temp()

def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()
    return(res.replace("temp=","").replace("'C\n",""))

# Log in data for Xively
API_KEY = 'your own key'
FEED = your feed number
API_URL = '/v2/feeds/{feednum}.xml' .format(feednum = FEED)

# Get cpu temp
CPU_temp = getCPUtemperature()

# open up your feed
pac = eeml.Pachube(API_URL, API_KEY)

#compile data

pac.update([eeml.Data("CPU_Temperature", CPU_temp, unit=eeml.Celsius())])
pac.update([eeml.Data("HotWaterPreHeatTank", temp_0, unit=eeml.Celsius())])
pac.update([eeml.Data("GSHP_WellReturn", temp_1, unit=eeml.Celsius())])
pac.update([eeml.Data("HotWaterTank", temp_2, unit=eeml.Celsius())])
pac.update([eeml.Data("BufferOut", temp_3, unit=eeml.Celsius())])
pac.update([eeml.Data("UFH_Flow", temp_4, unit=eeml.Celsius())])
pac.update([eeml.Data("SolarFlow", temp_5, unit=eeml.Celsius())])
pac.update([eeml.Data("SolarReturn", temp_6, unit=eeml.Celsius())])
pac.update([eeml.Data("GSHP_Flow", temp_7, unit=eeml.Celsius())])
pac.update([eeml.Data("GSHP_LoopsReturn", temp_8, unit=eeml.Celsius())])
pac.update([eeml.Data("BufferIn", temp_9, unit=eeml.Celsius())])

# send data to cosm
pac.put()
Steve
Last edited by eccentricdyslexic on Thu Jan 02, 2014 9:57 pm, edited 1 time in total.

HenrikN
Posts: 10
Joined: Fri Mar 15, 2013 5:49 pm

Re: ds18b20 send multiple sensor data to Cosm

Thu Jan 02, 2014 7:48 pm

Thank you so much! I had to modify it a bit and add some indents as they didnt make it to the post. Below Ive posted a complete guide on what I did to make it work. Hopefully it can help people in the future.

First update your raspberry pi by typing the following command in the terminal: "sudo apt-get install update"

Secondly you want to install some python software, follow this guide: http://learn.adafruit.com/send-raspberr ... y-packages I didn't get the "sudo easy_install -U distribute" command to work but it didn't affect anything.

After that you can copy the following text (credit goes to eccentricdyslexic). Do not forget to change the values and Xively data. Save the document as "xxxxxxxxx.py"

Code: Select all

#!/usr/bin/env python 2.7.3

import os
import glob
import time
import json
import subprocess
import eeml
import sys
import syslog

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

# add more sensor variables here based on your setup
temp_0 = 0
temp_1 = 0

for sensors in range (2): # change number of sensors based on your setup
	base_dir = '/sys/bus/w1/devices/'
	device_folder = glob.glob(base_dir + '28*')[sensors]
	device_file = device_folder + '/w1_slave'
	print device_file
	print sensors

	def read_temp_raw(): # gets the temps one by one
		f = open(device_file, 'r')
		lines = f.readlines()
		f.close()
		return lines

	def read_temp(): # checks the temp recieved for errors
		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:]
			# set proper decimal place for C
			temp = float(temp_string) / 1000.0
			# Round temp to 2 decimal points
			temp = round(temp, 1)
			return temp

# ask for temps to be read and store each in a variable
	if sensors == 0:
		temp_0 = read_temp()
		temp_1 = read_temp()
	if sensors == 1:
		temp_1 = read_temp()



		print temp_0
		print temp_1



# Log in data for Xively
API_KEY = '0UGFfZPRQYoevkeZ02wMrefjMF3jjEec7KkBK5p3muauK9sz'
FEED = 98727321
API_URL = '/v2/feeds/98727321.xml' .format(feednum = FEED)


# open up your feed
pac = eeml.Pachube(API_URL, API_KEY)

#compile data
pac.update([eeml.Data("Inne", temp_1, unit=eeml.Celsius())])
pac.update([eeml.Data("Ute", temp_0, unit=eeml.Celsius())])

# send data to cosm
pac.put()
You can then run the program by cd to the location where you saved the xxxxxx-py file. Then type "sudo python xxxxxxxxx.py" Done!

eccentricdyslexic
Posts: 157
Joined: Thu Jul 18, 2013 6:13 am
Location: Uttoxeter, Staffordshire, UK

Re: ds18b20 send multiple sensor data to Cosm

Thu Jan 02, 2014 9:49 pm

Glad to be of assistance! Not sure why my code didn't indent correctly though.

I have this program set to run every minute or two in a cron job. Also set a static IP address and can acces my Pi from here in the uk via SSH Putty if I ever need to make changes(which I haven't so far!). ( the Pi is instaled in my house in France)

Steve

jeremie03
Posts: 1
Joined: Mon Oct 03, 2016 8:56 am

Re: ds18b20 send multiple sensor data to Cosm

Mon Oct 03, 2016 9:02 am

Hi all,

This code did the work perfectly, I use 3 sensors as bellow (0) (1) (2) , you can add as many you want by increasing the last part "print" by the number of sensors.

Cheers !

Code: Select all

import os
import glob
import time

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

def read_temp_raw(i):
    base_dir = '/sys/bus/w1/devices/'
    device_folder = glob.glob(base_dir + '28*')[i]
    device_file = device_folder + '/w1_slave'
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp(i):
    lines = read_temp_raw(i)
    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(0))
    print(read_temp(1))
    print(read_temp(2))
    time.sleep(1)

eccentricdyslexic
Posts: 157
Joined: Thu Jul 18, 2013 6:13 am
Location: Uttoxeter, Staffordshire, UK

Re: ds18b20 send multiple sensor data to Cosm

Mon Oct 03, 2016 2:40 pm

The code still works well for me too. Although I recently had to re install due to sd card issues! Next I need to fit the rpi with a UPS for safe shut downs!

Steve

R-A
Posts: 50
Joined: Sun Sep 11, 2016 4:59 pm
Location: Johannesburg, South Africa
Contact: Website

Re: ds18b20 send multiple sensor data to Cosm

Mon Jan 23, 2017 5:57 am

kkasberg wrote:I worked on this a while, and what I ended up with was this. It looks for all sensor folders in the directory and prints out the datetime of the reading, the sensors folder name (serial number) and the temp readings. I hope that this is helpful to others out there.

Code: Select all

import os
import glob
import time
from datetime import datetime

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
device_folder = ''
evice_file = ''

def read_temps_multi():
        base_dir = '/sys/bus/w1/devices/'
        for device in glob.glob(base_dir + '28*'):
                global device_folder
                global device_file
                device_folder = device
                device_file = device_folder + '/w1_slave'
                print(read_temp())

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

def read_temp():
    lines = read_temp_raw()
    date = str(datetime.now())[:16]
    sensor = device_folder[-15:]
    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 date, sensor, temp_c, temp_f

while True:
        read_temps_multi()
        time.sleep(1)

How can I change this code to address each sensor by it's ID? i.e. my sensors are as follows:

Code: Select all

pi@raspberrypi:~ $ cat /sys/bus/w1/devices/w1_bus_master1/w1_master_slaves
28-000007a1ca78
28-00000740dc33
28-000007a0525e

How would I address each sensor by it's ID, so I know where that sensor is?
I'm using a Raspberry Pi 3 Model B with 7" LCD Touch screen and Mini USB Wireless Keyboard

Return to “Python”