Raspberry Pi cible Smart (4 / 6 étapes)

Étape 4: Code

The Raspberry Pi tourne sens « sans tête », il n’y a pas besoin d’avoir un moniteur, clavier ou souris.  Afin de commencer les choses automatiquement une fois que j’ai connecté le RPI, j’ai utilisé un script d’initialisation de Linux (/ etc/init.d/target) pour démarrer le programme Java qui écoute d’action ainsi qu’un programme d’arrêt à l’écoute pour le bouton d’arrêt. Le script montre également l’adresse IP actuelle sur l’écran LCD lors du démarrage.

 #!/bin/bash #/etc/init.d/target export HOME case "$1" in start) if [ ! -e "/dev/ttyS1" ]; then ln /dev/ttyAMA0 /dev/ttyS1 fi /home/pi/lcd.py `ifconfig wlan2 | grep inet | awk '{print $2}' | sed 's/addr://'` java -cp .:/home/pi:/home/pi/lib/* Target >> /home/pi/target.log & /home/pi/shutdown-listener.py & ;; stop) LCD_PID=`ps auxwww | grep Target | head -1 | awk '{print $2}'` kill $LCD_PID ;; *) echo "Usage: /etc/init.d/target {start|stop}" exit 1 ;; esac exit 0 

Script d’arrêt

 #!/usr/bin/env python from time import sleep import os import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) OFF_SWITCH = 23 GPIO.setup(OFF_SWITCH, GPIO.IN) while True: if ( GPIO.input(23) == False ): os.system('/home/pi/lcd.py " Shutting down. Goodbye :)"') os.system('shutdown -h now') break sleep(1); print 'Shutting down' 

Script LCD Python l’écran LCD d’ioBridge au volant

 #!/usr/bin/env python import serial import string import sys test=serial.Serial("/dev/ttyAMA0",9600) test.open() line = sys.argv[1] byte = chr(0xFE) try: test.write(byte) test.write("B") test.write("9") test.write(byte) test.write("Z") test.write(line) test.write(byte) test.write("T") test.write("0") delay = chr(0x10) test.write(delay) except KeyboardInterrupt: pass # do cleanup here test.close() 

Maintenant, voici la source Java. Notez que j’utilise la bibliothèque twiiter4j et rpi-gpio-java (http://code.google.com/p/rpi-gpio-java/)

 import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import java.io.OutputStream; import be.doubleyouit.raspberry.gpio.Boardpin; import be.doubleyouit.raspberry.gpio.Direction; import be.doubleyouit.raspberry.gpio.GpioGateway; import be.doubleyouit.raspberry.gpio.impl.GpioGatewayImpl; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; import javax.activation.MimetypesFileTypeMap; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.FileEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import twitter4j.StatusUpdate; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.conf.ConfigurationBuilder; import java.util.Random; public class Target { static OutputStream output; static GpioGateway gpio; static SerialPort port; static CommPortIdentifier portId; static HttpClient httpclient = new DefaultHttpClient(); static String replyURL; static String message; static boolean ready = true; static String dropcam = "https://nexusapi.dropcam.com/get_image?width=800&uuid=XXXX"; static String osnImg; public static Date now; static Random generator = new Random(); public static String[] messages = { "Lucky! Looks like you will be taking me home tonight!", "It paid off to stop by the OTN Lounge tonight.", "Looks like someone has been practicing.", "Not bad for your first try. Now go ahead and brag to your friends.", "I love hanging out at the OTN Lounge, but It looks like you will be taking me home tonight!", "That was nice. No go and tell your friends to stop by the OTN Lounge.", "I just love to scream and fly at the OTN Lounge.", "Roses are red and Oracle too. Now you can take me home too.", "I just wanna fly.", "Thanks for stopping by. Looks like you got lucky tonight.", "I just love to scream and fly at the OTN Lounge." }; public static void main(String[] args) throws Exception{ AddShutdownHookSample kill = new AddShutdownHookSample(); kill.attachShutDownHook(); try{ portId = CommPortIdentifier.getPortIdentifier("/dev/ttyS1"); port = (SerialPort)portId.open("Raspi LCD", 4000); output = port.getOutputStream(); port.setSerialPortParams(9600,SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); gpio = new GpioGatewayImpl(); gpio.unexport(Boardpin.PIN11_GPIO17); gpio.export(Boardpin.PIN11_GPIO17); gpio.setDirection(Boardpin.PIN11_GPIO17, Direction.IN); while (true){ brightness("9"); clear(); print(" Ready "); delayBacklight("0",5); int i = 0; //remove negation! while (!gpio.getValue(Boardpin.PIN11_GPIO17)){ i = 1; } if (ready){ //System.out.println("start"); ready = false; int rnd = generator.nextInt(10); Process proc = Runtime.getRuntime().exec(new String[]{"/usr/bin/mpg321", "-q","/home/pi/"+rnd+".mp3"}); brightness("9"); clear(); print(" Congratulations"); //Login downloadPicture(); uploadPicture(messages[rnd]); clear(); delayBacklight("0",5); Thread.sleep(2 * 5000); ready = true; //System.out.println("end"); } } }catch (Exception e){ System.out.println(e.toString()); } } public static void downloadPicture() throws IOException{ now = new Date(); String formatDate = new SimpleDateFormat("MMddyyyy-hhmmss").format(now); osnImg = "OTN-" + formatDate + ".jpeg"; HttpGet httpget = new HttpGet(dropcam); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); //System.out.println("downloadPicture: " +response.getStatusLine()); if (entity != null) { byte[] bytes = EntityUtils.toByteArray(entity); File file = new File("/var/www/" + osnImg); FileOutputStream fos = new FileOutputStream(file); fos.write(bytes); fos.close(); } EntityUtils.consume(entity); } public static void uploadPicture(String message) throws TwitterException { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey("XXXX"); cb.setOAuthConsumerSecret("XXXX"); cb.setOAuthAccessToken("XXXX"); cb.setOAuthAccessTokenSecret("XXXX"); StatusUpdate status = new StatusUpdate(message); File imageFile = new File ("/var/www/" + osnImg); status.setMedia(imageFile); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try { twitter.updateStatus(status); } catch ( Exception ex ) { ex.printStackTrace(); } } public static void delayBacklight(String level, int delay ) throws Exception{ startCommand(); output.write("T".getBytes()); output.write(level.getBytes()); output.write(delay); } public static void brightness(String level) throws Exception{ startCommand(); output.write("B".getBytes()); output.write(level.getBytes()); } public static void print(String message) throws Exception{ output.write(message.getBytes()); } public static void clear() throws Exception{ startCommand(); output.write("C".getBytes()); } public static void startCommand() throws Exception{ output.write(254); } } //http://www.javabeat.net/2010/11/runtime-addshutdownhook/ class AddShutdownHookSample { void attachShutDownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { public void run(){ try{ System.out.println("Shuting down target"); File file = new File("/var/lock/LCK..ttyS1"); Lcd.httpclient.getConnectionManager().shutdown(); if(file.delete()){ System.out.println(file.getName() + " is deleted!"); } }catch(Exception e){ e.printStackTrace(); } } }); //System.out.println("Shut Down Hook Attached."); } } 

Articles Liés

Raspberry Pi zéro clair de lune (contrôlé avec Smart Phone)

Raspberry Pi zéro clair de lune (contrôlé avec Smart Phone)

Bienvenue ! Voici comment construire un éclairage contrôlé de smartphone. J'ai trouvé une lampe très gentil « en forme de lune » chez Ikea - mais vraiment aucune lampe fera disposant d'une simple prise 2 broches.Ceci fonctionnera avec n'importe quel
Programmation Raspberry Pi avec CODESYS

Programmation Raspberry Pi avec CODESYS

SalutCette instructable est essentiellement un tutoriel pour obtenir vous aller en utilisant l'environnement CODESYS pour programmer un Pi de framboise.Cette instructable vise non pas tant pour les amateurs, mais plutôt de bourgeonnement contrôle/aut
Windows Ito et le Raspberry Pi : lire un bouton GrovePi

Windows Ito et le Raspberry Pi : lire un bouton GrovePi

Ce projet vous montre comment commencer à connecter un bouton à la GrovePi en utilisant Windows Ito, la Pi de la framboise et la GrovePi.Si vous êtes un passionné de Microsoft ou c#, il n'a jamais été plus facile de commencer avec theGrovePi + Kit In
Le Raspberry Pi-Arduino-SignalR Home Automation moyeu

Le Raspberry Pi-Arduino-SignalR Home Automation moyeu

Suite à un couple de mon prélude IBLEs publié ici et ici, ce projet prend la première étape vers la création d'une version de base d'un Home Automation Hub fonctionnelle.J'ai utilisé différentes technologies dans le but de comprendre comment je peux
Une Table d’Arcade bricolage propulsé par Raspberry Pi

Une Table d’Arcade bricolage propulsé par Raspberry Pi

Jeux avec les émulateurs existe depuis pas mal de temps, mais rien ne ramène la nostalgie de l'arcade vieux comme jouer avec un joystick vintage et ces gros boutons ronds. Comme beaucoup d'entre nous, j'ai toujours rêvé de posséder une machine de sta
ESP8266 + Raspberry Pi électricité moniteur

ESP8266 + Raspberry Pi électricité moniteur

J'ai toujours suivi mon mètres utilitaire dans la manière démodée. Tout d'abord je leur ai écrit vers le bas dans un petit livre (Ouais, je suis si vieux), plus tard, j'ai écrit une feuille de calcul pour elle et ces dernières années j'utilise l'appl
Raspberry Pi 2 NAS avec Owncloud, Samba et MiniDlna

Raspberry Pi 2 NAS avec Owncloud, Samba et MiniDlna

Pour commencer, c'est mon premier Instructable. La raison pour laquelle que je crée cette informatique pour aider les autres si tout va bien avec ce processus. IV a passé environ une semaine et de nombreuses heures à essayer différentes combinaisons
PiScope (Raspberry Pi en fonction Oscilloscope)

PiScope (Raspberry Pi en fonction Oscilloscope)

Un oscilloscope est un instrument de laboratoire couramment utilisé pour afficher et analyser la forme d'onde des signaux électroniques. En effet, le dispositif dessine un graphique de la tension du signal instantané en fonction du temps.Oscilloscope
Faire les Raspberry Pi périphérique à devenir un serveur Bluetooth Object Push profil (OPP)

Faire les Raspberry Pi périphérique à devenir un serveur Bluetooth Object Push profil (OPP)

IntroductionTéléphone Android fonctionne une pile de protocole bluetooth. Raspbian OS, le populaire système d'exploitation pour le Raspberry Pi gère également une implémentation de la pile de protocole Bluetooth. Cela suggère que la Pi de la frambois
Comment faire un Panel de médias Raspberry Pi (fka Digital Photo Frame)

Comment faire un Panel de médias Raspberry Pi (fka Digital Photo Frame)

L'objectif de ce projet était de créer un Panel de médias de Pi framboise faible coût--un bel écran à la recherche qui pourrait se tenir dans la salle de séjour ou attacher au réfrigérateur dans le but essentiel de streaming photo personnelle et cont
Arduino / Raspberry Pi Internet Radio

Arduino / Raspberry Pi Internet Radio

Il s'agit d'un projet pour Arduino et Raspberry Pi pour faire une Radio Internet, visant à un niveau intermédiaire. Quelque familiarité avec l'utilisation de Linux va être bénéfique (ou accès à quelqu'un qui peut dépanner si nécessaire).Raspberry Pi
Transformer le Raspberry Pi dispositif Bluetooth qui est détectable par bluetooth distant client

Transformer le Raspberry Pi dispositif Bluetooth qui est détectable par bluetooth distant client

IntroductionJ'ai un périphérique Bluetooth Radio USB qui cueillait des poussières lorsque je suis tombé sur elle. Alors j'ai pensé que je devrais mettre à profit avec Raspberry Pi. Cette instructable est sur mon parcours d'apprentissage de l'ajout d'
Raspberry Pi CD boîte Robot

Raspberry Pi CD boîte Robot

Anglais:Ce projet est un travail qui prend beaucoup de fins de semaine. Mon fils, Gabriel, regardé le film « Wall-E » et a proposé que nous avons construit un robot similaire. Je vois ce modèle en DX.com et laissez-vous inspirer par ce dernier.Nous u
Raspberry Pi Bluetooth LE contrôleur pour WS2812B (NeoPixels)

Raspberry Pi Bluetooth LE contrôleur pour WS2812B (NeoPixels)

Bluetooth Low Energy (aka BLE/Bluetooth 4.0/Bluetooth Smart) est la plus récente incarnation de Bluetooth technologie développée par le Bluetooth SIG (l'organisation qui maintient la spécification). Ce protocole de communication est conçu pour les ap