Sunday, 23 December 2012

Tracking our Pi System status in Cosm is a service that allows you to push data to it or it retrieves data from a device/app/cat and will make some incredible nice graphs with it:

They have a nice API and they accept XML, JSON and CSV to update out data.

So it's a nice platform to control and build graphs for our Raspberry Pi system. With it we can control and track how our system behaves along time without accesing the device.

And with a few lines of python, we have a nice script which will upload cpu(in percentage), free hdd space (rootfs), free and used memory. You can see a couple of examples in the image attached.

Here is the code:
 # Copyrigth 2012 Itxaka Serrano Garcia <>  
 # licensed under the GPL2  
 # see the full license at  
 # 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 json, subprocess, os  
 hdd = subprocess.check_output(["df | grep rootfs | awk '{print $2,$4,$5}'"], shell=True)  
 hdd = hdd.split()  
 hdd = int(hdd[1]) / 1024  
 cpu = subprocess.check_output(["vmstat | awk '{print $13}'"], shell=True)  
 cpu = cpu.split()[1]  
 mem = subprocess.check_output(["cat /proc/meminfo | grep Mem | awk '{print $2}'"], shell=True)  
 mem = mem.split()  
 mem_total = int(mem[0]) / 1024  
 mem_free = int(mem[1]) / 1024  
 mem_used = mem_total - mem_free  
 data = json.dumps({"version":"1.0.0", "datastreams":[{"id":"hdd","current_value":hdd },{"id":"cpu","current_value":cpu},{"id":"free_mem","current_value":mem_free},{"id":"used_mem","current_value":mem_used}]})  
 with open("temp.tmp", "w") as f:  
     f.write(data)['curl --request PUT --data-binary @temp.tmp --header "X-ApiKey: YOUR_IP_KEY_HERE"'], shell=True)  

We can get this working in 4 steps.

1 - Copy the code and save it to a file in your Pi under whatever name you want (We will use in this example) and store it whenever you want, I usually put them in /home/pi/scripts/

2 - Add in the code your API key for cosm and your Feed name (Instructions on how to get an api key are in the page)

3 - Add a new entry in your crontab to run it every X minutes. In my case I run it every 10 minutes so my cron line is
 */10 * * * * python /home/pi/scripts/  

4 - Visit your feed page and wait for the results

There! That was easy wasn't it?

Be sure to check my feed