Saturday, 25 February 2012

apcupsd via Python to Pachube

In python, the 'default' URL accessing toolkit (urllib2) doesn't support PUT, however I've discovered requests which a) does and b) is in Fedora. So one apt-get install python-requests.noarch and you're off.

So - one trivial script (reusing much of the code for my MQTT variant) you get https://gist.github.com/1903259. The only minor niggle was working out how to prepend the minimum extra json content (version and datastreams) as I'd not used the json libs before.
#!/usr/bin/python
# Script to poll the UPS (via apcupsd) and publish interesting facts to
# pachube. You'll need to alter FEED_ID and insert your API key
# Published under GPL3+ by Andrew Elwell <Andrew.Elwell@gmail.com>
import subprocess # we scrape apcaccess output
import requests # CBA writing a pachube library
import json
interesting = ('linev', 'loadpct', 'battv', 'bcharge')
payload = []
# go and grab
res = subprocess.check_output("/sbin/apcaccess")
for line in res.split('\n'):
(key,spl,val) = line.partition(': ')
key = key.rstrip().lower()
if key in interesting: # just save what we want
val = val.strip()
val = val.split(' ',1)[0] # ignore anything after 1st space
payload.append({'id':key, 'current_value':val})
# set up pachube connection
API_KEY = "YOUR API KEY"
#jsonify it
stream = json.dumps({"version":"1.0.0","datastreams": payload})
r = requests.put("http://api.pachube.com/v2/feeds/FEED_ID", headers = {"X-PachubeApiKey": API_KEY}, data=stream)
view raw apc2pacube.py hosted with ❤ by GitHub
(Hmm yet another github toy - embeddable gists with syntax highlighting. Nice) Update now I have 24h worth of data - plot attached

1 comment:

radez said...

You could also use httplib2. We do Puts in the audrey agent (github.com/aeolusproject/audrey/). It uses the oauth library which uses httplib2 as the underlying http lib.

Too many buttons

 I have a standard ham licence (VK7HPC) and am currently poking at a Retevis RT95 (same as the Anytone AT-778UV). As I'd like to use it ...