Yesterday I spent a few hours getting acquainted with my Raspberry Pi.

The mission, was to simply setup the Pi, create a simple script to write some output, to a text file. Then, to create a cron job to process that script every few minutes. After that, I would get acquainted with Python modules, firstly by getting the current time and outputting that to the log.

Finally, constructing a POST request to a 3rd party web service to send that timestamp to.

What we did:

Using Python version 2.7.3rc2 on a Raspberry Pi, running Raspian distribution of Linux.

We first got a simple python script writing to a text file, getting the current time using the python Time module and appending it to the file contents. 

import time

f = open('/path/to/folder/test/log', 'a')
# current_time = time.asctime( time.localtime(time.time()) )
current_time = time.strftime('%I:%M%p %Z on %b %d, %Y')
f.write(current_time + '\n')

f.close()


Then we created a cron script to run on boot of the Pi and then every 2 minutes, to run the python script. 

$ sudo crontab -e
# m h  dom mon dow   command
*/2 * * * * python /path/to/folder/test/add_note.py
@reboot python /path/to/folder/test/add_note.py

From there, we constructed a POST request to the nourish staging (old) Notes endpoint, firstly via the Python shell (IDLE) which comes with the Raspian distribution of Linux. 


Key here was the use of two further Python modules: urllib and urllib2 


import time
import urllib
import urllib2

url = "http://api.someservice.co.uk/api/v2/notes/?auth_token=XXXXXXXXXXXXX"

current_time = time.strftime('%I:%M%p %Z on %b %d, %Y')
date = current_time
post_data_dictionary = {'log[person_id]':12, 'log[user_id]':67, 'log[text]':current_time}
post_data_encoded = urllib.urlencode(post_data_dictionary)
request_object = urllib2.Request(url, post_data_encoded)
response = urllib2.urlopen(request_object)
html_string = response.read()

f = open('/path/to/file/test/log', 'a')
f.write(html_string + '\n')
f.close()

Note that in Python 3, urllib2 has been merged into urllib, so no need to declare both in that case. 

I then updated the cron to process this file and refactored the script a bit. 

Authentication just passes the auth token as a param, so need to improve there. 

Next step is to get the actual data via an analogue to digital converter, and interface to the Pi, via SPI. We want to end up with a self contained RJ45 which interfaces directly to a pressure sensor for bed or chair interactions. 

We also need to change the location that this data is sent to, either the existing mongodb or some other suitable data storage, which can then be interrogated and queried at will by a caffeine fuelled CEO.