Non contento di Natalino (controllo delle luci dell’albero con Arduino) ho deciso di rendere il progetto più “intelligente”, utilizzando questa volta il mio fido Raspberry Pi.
L’obiettivo era accendere un alberino a led con un tweet. Ed in poco tempo direi che ci sono riuscito 🙂
Volete provare ad accenderlo anche voi?
Accendi XmasTreepi di @AleGrechi
Di seguito le spiegazioni tecniche.
Hardware
Gli “ingredienti” utilizzati sono:- Raspberry Pi modello B con Raspbian
- Striscia led RGB
- Scheda a 4 relè
Il collegamento è semplice, ho deciso di utilizzare il modulo relé che già avevo per semplificare, ma sarebbe possibile anche utilizzare un transistor per ogni colore.
Ciascun relé sarà collegato ad un GPIO che provvederà ad accendere e spegnere il colore collegato.
La scheda relè è alimentata tramite il pin GPIO che fornisce 5V.
Ovviamente il Raspberry è connesso alla rete tramite cavo ethernet.
Software
Per accendere le luci è sufficiente cambiare l’uscita dei GPIO (da alto a basso in questo caso), e questo nel raspberry si riduce semplicemente a qualcosa del tipo:
[code lang=”python”]import RPi.GPIO as GPIOGPIO.setmode(GPIO.BOARD)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
GPIO.output(22, 0)
GPIO.output(16, 0)
GPIO.output(12, 0)
[/code]
Dove ai pin 12, 16, 22 avevo ovviamente collegato i tre relé dei colori.
Per interfacciarmi con Twitter ho invece trovato e sperimentato una libreria Python davvero carina, Twython
Si installa semplicemente con
[code lang=”bash”]sudo apt-get install python-pipsudo pip install twython[/code]
Come unico prerequisito per poter leggere twittare è necessario creare un’applicazione ed ottenere le chiavi di accesso dalla pagina Twitter Developers (sono necessari: Consumer Key, Consumer Secret, Access Token, Access Token Secret).
Il codice Python esegue le seguenti operazioni:
- Si autentica con Twitter (ricordate di inserire le vostre chiavi ad inizio file!)
- Fa una ricerca nella stream timeline con l’hashtag #XmasTreePi
- Per ogni tweet che trova chiama la classe MyStreamer
- All’interno del tweet verifica la presenza degli hashtag #on o #off
- In caso vi sia #on scrive un tweet di risposta (twitter.update_status) e fa partire la funzione play() che esegue un semplice loop di colori
from twython import Twython, TwythonStreamer, TwythonError
import RPi.GPIO as GPIO
import time
#SETUP TWYTHON
TWITTER_APP_KEY = ‘ WRITE APP KEY HERE’
TWITTER_APP_KEY_SECRET = ‘WRITE APP KEY SECRET HERE’
TWITTER_ACCESS_TOKEN = ‘WRITE ACCESS TOKEN HERE’
TWITTER_ACCESS_TOKEN_SECRET = ‘WRITE ACCESS TOKEN SECRET HERE’
twitter = Twython(TWITTER_APP_KEY, TWITTER_APP_KEY_SECRET,TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET)
#SETUP GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
def led(color,status):
#MAP COLORS TO GPIO PINS
if color == "red":
if status == "on":
GPIO.output(22, 0)
return
else:
GPIO.output(22, 1)
return
elif color == "green":
if status == "on":
GPIO.output(12, 0)
return
else:
GPIO.output(12, 1)
return
elif color == "blue":
if status == "on":
GPIO.output(16, 0)
return
else:
GPIO.output(16, 1)
return
elif color == "yellow":
if status == "on":
GPIO.output(22, 0)
GPIO.output(12, 0)
return
else:
GPIO.output(22, 1)
GPIO.output(12, 1)
GPIO.output(16, 1)
return
elif color == "purple":
if status == "on":
GPIO.output(22, 0)
GPIO.output(16, 0)
return
else:
GPIO.output(22, 1)
GPIO.output(16, 1)
return
elif color == "cyan":
if status == "on":
GPIO.output(16, 0)
GPIO.output(12, 0)
return
else:
GPIO.output(16, 1)
GPIO.output(12, 1)
return
elif color == "all":
if status == "on":
GPIO.output(12, 0)
GPIO.output(16, 0)
GPIO.output(22, 0)
else:
GPIO.output(12, 1)
GPIO.output(16, 1)
GPIO.output(22, 1)
def play():
#SAMPLE LOOP
loop=0
while (loop<4):
led("all","off")
led("red","on")
time.sleep(0.5)
led("all","off")
led("green","on")
time.sleep(0.5)
led("all","off")
led("blue","on")
time.sleep(0.5)
led("all","off")
led("yellow","on")
time.sleep(0.5)
led("all","off")
led("purple","on")
time.sleep(0.5)
led("all","off")
led("cyan","on")
time.sleep(0.5)
led("all","on")
loop=loop+1
led("all","off")
return
class MyStreamer(TwythonStreamer):
#SEARCH FOR HASHTAG AND POST TWEETS
def on_success(self, data):
if ‘text’ in data:
print data[‘text’].encode(‘utf-8’)
USER = data[‘user’][‘screen_name’].encode(‘utf-8’)
TWEET_ID = data[‘id_str’].encode(‘utf-8’)
if (‘#on’ in data[‘text’].lower() and ‘#off’ in data[‘text’].lower()):
#TWEET HAS BOTH ON AND OFF, DO NOTHING
print "sia on che off, WTF!"
return
for hashtag in data[‘entities’][‘hashtags’]:
if hashtag[‘text’].lower() == ‘on’ :
#SWITCH ON !
print "albero acceso!"
try:
twitter.update_status(status=’@%s #XmasTreePi acceso. Grazie e Buon Natale!’ % (USER), in_reply_to_status_id=’%s’ % (TWEET_ID.encode(‘utf-8’)))
except TwythonError as error:
print "errore invio tweet ON: "
print error
play()
elif hashtag[‘text’].lower() == ‘off’ :
#SWITCH OFF
led("all","off")
print "albero spento!"
try:
twitter.update_status(status=’@%s Oh, mi hai spento #XmasTreePi :(‘ % (USER), in_reply_to_status_id=’%s’ % (TWEET_ID.encode(‘utf-8′)))
except TwythonError as error:
print "errore invio tweet OFF"
print error
def on_error(self, status_code, data):
print status_code
#READ TWITTER STREAM
stream = MyStreamer(TWITTER_APP_KEY, TWITTER_APP_KEY_SECRET,
TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET)
stream.statuses.filter(track=’#XmasTreePi’)
A questo punto lanciate lo script con
[code lang=”bash”]sudo python XmasTreePi.py[/code]e provate ad accendere i led inviando un tweet contenente gli hashtag #XmasTreePi e #On
Buon Natale a tutti 🙂






