Raspberry Pi + DS18B20 + Xively

#!/usr/bin/env python

import os
import xively
import subprocess
import time
import datetime
import requests

FEED_ID = "MY_FEED_ID"
API_KEY = "MY_API_KEY"

# initialize api client
api = xively.XivelyAPIClient(API_KEY)

# function to read the temperature from ds18b20 temperature sensor on i2c 
def read_temperature():
   tempfile = open("/sys/bus/w1/devices/28-000004b09c53/w1_slave")
   thetext = tempfile.read()
   tempfile.close()
   tempdata = thetext.split("\n")[1].split(" ")[9]
   temperature = float(tempdata[2:])
   temperature = temperature / 1000
   return temperature

# function to return a datastream object. This either creates a new datastream,
# or returns an existing one
def get_datastream(feed):
  try:
    datastream = feed.datastreams.get("DS18B20")
    return datastream
  except:
    datastream = feed.datastreams.create("DS18B20", tags="temperature")
    return datastream

# main program entry point - runs continuously updating our datastream with the
# latest temperature reading
def run():
  feed = api.feeds.get(FEED_ID)

  datastream = get_datastream(feed)
  datastream.max_value = None
  datastream.min_value = None

  while True:
    degreesCelcius = read_temperature()
    datastream.current_value = degreesCelcius
    datastream.at = datetime.datetime.utcnow()
    try:
      datastream.update()
    except requests.HTTPError as e:
      print "HTTPError({0}): {1}".format(e.errno, e.strerror)

    time.sleep(10)

run()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s