Código de ejemplo de la Charla-Taller: Internet de las Cosas, RaspberryPi y Python en MediaLab-Prado (http://medialab-prado.es/article/iotraspberrypipython
Toda la información sobre este proyecto puedes encontrarla en https://www.carriots.com/tutorials/arduino_carriots/alert_system
#-*-coding:utf8-*-
import RPi.GPIO as GPIO, time
import urllib2
import time, datetime
import json
class Client(object):
api_url = 'http://api.carriots.com/streams'
def __init__ (self, api_key = None, client_type = 'json'):
self.client_type = client_type
self.api_key = api_key
self.content_type = 'application/vnd.carriots.api.v2+%s' % (self.client_type)
self.headers = {'User-Agent': 'Raspberry-Carriots',
'Content-Type': self.content_type,
'Accept': self.content_type,
'Carriots.apikey': self.api_key}
def send (self, data):
self.data = json.dumps(data)
request = urllib2.Request(Client.api_url, self.data, self.headers)
self.response = urllib2.urlopen(request)
return self.response
def RCtime(PiPin):
measurement = 0
GPIO.setup(PiPin, GPIO.OUT)
GPIO.output(PiPin, GPIO.LOW)
time.sleep(0.1)
GPIO.setup(PiPin, GPIO.IN)
while (GPIO.input(PiPin) == GPIO.LOW):
measurement += 1
return measurement
def main():
GPIO.setmode(GPIO.BCM)
ON = 1
OFF = 2
DEVICE = 'YOUR_DEVICE@YOUR_USERNAME'
APIKEY = 'YOUR_APIKEY'
lights=OFF
client_carriots = Client (APIKEY)
while True:
timestamp = int (time.mktime(datetime.datetime.utcnow().timetuple()))
if RCtime(4) > 600:
new_lights = OFF
else:
new_lights = ON
if lights is not new_lights
lights = new_lights
data = {'protocol':'v2','device':DEVICE,'at':timestamp,'data':{'light':('ON' if new_lights is ON else 'OFF')}}
carriots_response=client_carriots.send(data)
if __name__ == '__main__':
main()