0% found this document useful (0 votes)
39 views

Scroll Yuv-Arduino

This sketch configures the WiFi and provides information for an Arduino Yún or Yún Shield. It scans for available wireless networks, displays them to the user, and allows the user to select one and enter credentials like the SSID, password, and encryption type. It then configures the Yún/Shield with the provided information, sets the hostname and root password, and indicates when the device has connected to the wireless network by displaying the IP address.

Uploaded by

Guspelin Lin Lin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Scroll Yuv-Arduino

This sketch configures the WiFi and provides information for an Arduino Yún or Yún Shield. It scans for available wireless networks, displays them to the user, and allows the user to select one and enter credentials like the SSID, password, and encryption type. It then configures the Yún/Shield with the provided information, sets the hostname and root password, and indicates when the device has connected to the wireless network by displaying the IP address.

Uploaded by

Guspelin Lin Lin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Arduino Yún First configuration sketch

Configures the YunShield/Yún WiFi and infos via the Bridge


Works correctly if Line Ending is set as "NewLine"
If your board has two USB ports, use the Native one

The circuit:
Arduino YunShield
(or any Yun model with firmware > 1.6.1)

created March 2016


by Arduino LLC

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/YunFirstConfig
*/

#include <Process.h>

#define MAX_WIFI_LIST 10

String networks[MAX_WIFI_LIST];
String yunName;
String yunPassword;

void setup() {
SERIAL_PORT_USBVIRTUAL.begin(9600) ; // inicializa la comunicación serial

while (!SERIAL_PORT_USBVIRTUAL); ; // no hacer nada hasta que se abra el monitor


serial

SERIAL_PORT_USBVIRTUAL.println(F( "Hola, me alegro de verte!" ) ) ;


SERIAL_PORT_USBVIRTUAL.println(F( "Soy tu asistente de YunShield" ) ) ;
SERIAL_PORT_USBVIRTUAL.println(F( "Te ayudaré a configurar tu Yun en cuestión de
minutos" ) ) ;

SERIAL_PORT_USBVIRTUAL.println ( F ( "Comencemos comunicándonos con el procesador


Linux" ) ) ;
SERIAL_PORT_USBVIRTUAL.println ( F ( "Cuando el LED (L13) se encienda, ¡ya estaremos
listos!" ) ) ;
SERIAL_PORT_USBVIRTUAL.println ( F ( "Esperando ..." ) ) ;
SERIAL_PORT_USBVIRTUAL.println ( F ( "(mientras tanto, si está utilizando el monitor serie
del IDE, asegúrese de que esté configurado para enviar una \" Nueva línea \ " ) \ n " ) ) ;
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
Bridge.begin(); ; // hacer contacto con el procesador de Linux
digitalWrite(13, HIGH); // Led en el pin 13 se enciende cuando el puente está listo
// Recuperar si el tablero está en modo AP - sin usar
Process wifiList;
bool master = false;
wifiList.runShellCommand(F("iwinfo | grep \"Mode: Master\""));
while (wifiList.available() > 0) {
wifiList.read();
master = true;
}
// Obtener la lista de redes alcanzables
wifiList.runShellCommand(F("iwinfo wlan0 scan | grep ESSID | cut -d\"\\\"\" -f2"));

uint8_t num_networks = 0;
uint8_t i = 0;
char c;
bool dropNet = false;

networks[0].reserve(32);

while (wifiList.available() > 0) {


c = wifiList.read();
if (c != '\n') {
networks[i] += c;
} else {
// comprobar si tenemos redes que ya se encuentran [i] y, finalmente, la dejan caer
for (uint8_t s = 0; s < i; s++) {
if (networks[i].equals(networks[s])) {
dropNet = true;
}
}
if (i <= MAX_WIFI_LIST && dropNet == false) {
networks[i++].reserve(32);
} else {
dropNet = false;
networks[i]="";
}
}
}

num_networks = i;

String encryption;
String password;
int chose = 0;

// Si el número de red es 0, inicie la configuración manual


if ( num_networks == 0 ) {
SERIAL_PORT_USBVIRTUAL.println ( F ( "Vaya, parece que no tienes una red Wi-Fi
disponible" ) ) ;
SERIAL_PORT_USBVIRTUAL.println ( F ( "Vamos a configurarlo manualmente" ) ) ;
SERIAL_PORT_USBVIRTUAL.println ( F ( "SSID de la red a la que desea conectarse:" ) ) ;
redes [ 0 ] = getUserInput ( redes [ 0 ] , false ) ;
SERIAL_PORT_USBVIRTUAL.println ( F ( "Contraseña para la red a la que desea conectarse:" ) ) ;
password = getUserInput ( password , true ) ;
SERIAL_PORT_USBVIRTUAL.print ( F ( "Cifrado (p. ej., WPA, WPA2, WEP):" ) ) ;
encryption = getUserInput ( encryption , false ) ;
} else {
// //si no, imprimirlos anteponiendo un número
SERIAL_PORT_USBVIRTUAL.print ( F ( "Parece que tienes" ) ) ;
SERIAL_PORT_USBVIRTUAL.print ( num_networks ) ;
SERIAL_PORT_USBVIRTUAL.println ( F ( "redes a tu alrededor" ) ) ;
SERIAL_PORT_USBVIRTUAL.println ( F ( "¿A cuál te quieres conectar? \ n " ) ) ;
for ( i = 0 ; i < num_networks && i < MAX_WIFI_LIST ; i ++ ) {
SERIAL_PORT_USBVIRTUAL.print(i);
SERIAL_PORT_USBVIRTUAL.println(") " + networks[i]);
}
String selection;
selection = getUserInput(selection,false);
chose = atoi(selection.c_str());
}

// Extraer la red de seguridad seleccionada


bool openNet = false;
wifiList.runShellCommand("iwinfo wlan0 scan | grep \"" + networks[chose] + "\" -A5 | grep
Encryption | cut -f2 -d\":\"");
while (wifiList.available() > 0) {
c = wifiList.read();
encryption += c;
}

if (encryption.indexOf("none") >= 0) {
openNet = true;
encryption = "none";
}
if (encryption.indexOf("WPA2") >= 0) {
encryption = "psk2";
}
if (encryption.indexOf("WPA") >= 0) {
encryption = "psk";
}
if (encryption.indexOf("WEP") >= 0) {
encryption = "wep";
}

if (openNet == false && password.length() == 0) {


SERIAL_PORT_USBVIRTUAL.print(F( "Parece que necesita una contraseña para conectarse" ) ) ;
SERIAL_PORT_USBVIRTUAL.println(networks[chose]);
SERIAL_PORT_USBVIRTUAL.print(F("Escribelo aquí: "));
password = getUserInput(password, true);
}

// Cambiar nombre de host / contraseña de root


SERIAL_PORT_USBVIRTUAL.println ( F ( "¡Estamos casi listos ! Dale un nombre y una contraseña
a tu Yun" )) ;
SERIAL_PORT_USBVIRTUAL.print( F ( "Nombre:" ) ) ;
yunName = getUserInput ( yunName , false ) ;
SERIAL_PORT_USBVIRTUAL.print( F ( "Contraseña:" ) ) ;
yunPassword = getUserInput ( yunPassword , true ) ;

// Seleccione un código de país


String countryCode ;
SERIAL_PORT_USBVIRTUAL.println ( F ( "Una última pregunta: ¿dónde vives?" ) ) ;
SERIAL_PORT_USBVIRTUAL.print ( F ( "Insertar un código de dos letras del condado (p. ej., IT,
US, DE):" ) ) ;
countryCode = getUserInput ( countryCode , false ) ;

yunName.trim();
yunPassword.trim();
networks[chose].trim();
password.trim();
countryCode.trim();

// Configura Yun con las strings que ha proporcionado el usuario


wifiConfig(yunName, yunPassword, networks[chose], password, "YUN" + yunName + "AP", country
Code,encryption);
SERIAL_PORT_USBVIRTUAL.print(F("Esperando a que Yun se conecte a la red"));
}

bool Connected = false;


bool serialTerminalMode = false;
int runs = 0;

void loop() {
if (!serialTerminalMode) {
String resultStr = "";

if (!Connected) {
SERIAL_PORT_USBVIRTUAL.print(".");
runs++;
}

// Si lleva más de 30 segundos conectarse, deje de intentar


if (runs > 30) {
SERIAL_PORT_USBVIRTUAL.println("");
SERIAL_PORT_USBVIRTUAL.println(F("No pudimos conectarnos a la red" ));
SERIAL_PORT_USBVIRTUAL.println(F( "Reinicia la placa si quieres ejecutar nuevamente el
asistente") ) ;
resultStr = getUserInput ( resultStr , false ) ;
}
// Comprobar si tenemos una dirección IP
Process wifiCheck;
wifiCheck.runShellCommand(F("/usr/bin/pretty-wifi-info.lua | grep \"IP address\" | cut -f2 -d\":\" |
cut -f1 -d\"/\"" )); // -----------------------comando que desamos ejecutar
while (wifiCheck.available() > 0) {
char c = wifiCheck.read();
resultStr += c;
}

delay(1000);

if (resultStr != "") {
// Obtuvimos una IP, congelamos el ciclo, mostramos el valor y "generamos" un terminal en serie
Connected = true;
resultStr.trim();
SERIAL_PORT_USBVIRTUAL.println("");
SERIAL_PORT_USBVIRTUAL.print(F("\nGenial! Ahora puedes contactar a tu Yun desde un
navegador tipeando http: //" ) ) ;
SERIAL_PORT_USBVIRTUAL.println(resultStr);
SERIAL_PORT_USBVIRTUAL.print(F("Presionar la tecla 'Enter' dos veces para iniciar un
terminal en serie "));
resultStr = getUserInput(resultStr, false);
serialTerminalMode = true;
//startSerialTerminal();
SERIAL_PORT_HARDWARE.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11);
// envíar comando puente de apagado
delay(100);
SERIAL_PORT_HARDWARE.println("\nreset\n\n");
SERIAL_PORT_HARDWARE.flush();
SERIAL_PORT_HARDWARE.println("\nreset\n\n");
SERIAL_PORT_HARDWARE.write((uint8_t *)"\n", 1);
}
} else {
loopSerialTerminal();
}
}

String getUserInput(String out, bool obfuscated) {


/*
while (SerialUSB.available() <= 0) {}
while (SerialUSB.available() > 0) {
char c = SerialUSB.read();
out += c;
}
return out;
*/
while (SERIAL_PORT_USBVIRTUAL.available() <= 0) {}
while (1) {
char c = SERIAL_PORT_USBVIRTUAL.read();
if (c == '\n' || c == '\r')
break;
else {
if (c != -1) {
out += c;
if (obfuscated)
SERIAL_PORT_USBVIRTUAL.print("*");
else
SERIAL_PORT_USBVIRTUAL.print(c);
}
}
}
SERIAL_PORT_USBVIRTUAL.println("");
return out;
}

void wifiConfig(String yunName, String yunPsw, String wifissid, String wifipsw, String
wifiAPname, String countryCode, String encryption) {
Process p;

p.runShellCommand("blink-start 100"); // comienza a parpadear el led

p.runShellCommand("hostname " + yunName); //cambiar el nombre del host actual


p.runShellCommand("uci set system.@system[0].hostname='" + yunName + "'");
//cambiar el nombre del host en uci

p.runShellCommand("uci set arduino.@arduino[0].access_point_wifi_name='" + wifiAPname + "'");

//este bloque restablece el wifi psw


p.runShellCommand("uci set wireless.@wifi-iface[0].encryption='" + encryption + "'");
p.runShellCommand("uci set wireless.@wifi-iface[0].mode='sta'\n");
p.runShellCommand("uci set wireless.@wifi-iface[0].ssid='" + wifissid + "'");
p.runShellCommand("uci set wireless.@wifi-iface[0].key='" + wifipsw + "'");
p.runShellCommand("uci set wireless.radio0.channel='auto'");
p.runShellCommand("uci set wireless.radio0.country='" + countryCode + "'");
p.runShellCommand("uci delete network.lan.ipaddr");
p.runShellCommand("uci delete network.lan.netmask");
p.runShellCommand("uci set network.lan.proto='dhcp'");

p.runShellCommand("echo -e \"" + yunPsw + "\n" + yunPsw + "\" | passwd root");


// cambiar los passwors
p. runShellCommand ( "uci commit" ) ; // guardar los mods hechos a través de UCI
p. runShellCommand ( "blink-stop" ) ; // comienza el parpadeo azul

p.runShellCommand("wifi ");
}

long linuxBaud = 250000;

void startSerialTerminal() {
SERIAL_PORT_USBVIRTUAL.begin(115200); // abre una conexión serie a través de USB-Serial

SERIAL_PORT_HARDWARE.begin(linuxBaud); // abrir conexión serie a Linux


}

boolean commandMode = false;


void loopSerialTerminal() {
// copia de USB-CDC a UART
int c = SERIAL_PORT_USBVIRTUAL.read(); // leer desde USB-CDC
if (c != -1) { // se obtiene algo?
if (commandMode == false) { // si no estamos en el modo de comando ...
if (c == '~') { // Tild '~' tecla presionada?
commandMode = true; // entrar en el modo de comando
} else {
SERIAL_PORT_HARDWARE.write(c); // de lo contrario, escriba char en UART
}
} else { // si estamos en modo comando ...
if ( c == '0' ) { // '0' tecla presionada?
SERIAL_PORT_HARDWARE.begin(57600); // set speed to 57600
SERIAL_PORT_USBVIRTUAL.println("Speed set to 57600");
} else if (c == '1') { // '1' key pressed?
SERIAL_PORT_HARDWARE.begin(115200); // set speed to 115200
SERIAL_PORT_USBVIRTUAL.println("Speed set to 115200");
} else if (c == '2') { // '2' key pressed?
SERIAL_PORT_HARDWARE.begin(250000); // set speed to 250000
SERIAL_PORT_USBVIRTUAL.println("Speed set to 250000");
} else if (c == '3') { // '3' key pressed?
SERIAL_PORT_HARDWARE.begin(500000); // set speed to 500000
SERIAL_PORT_USBVIRTUAL.println("Speed set to 500000");
} else if (c == '~') { // '~` key pressed?
SERIAL_PORT_HARDWARE.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11);
// enviar el comando "shutdown bridge"
SERIAL_PORT_USBVIRTUAL.println("Sending bridge's shutdown command");
} else { // cualquier otra tecla presionada?
SERIAL_PORT_HARDWARE.write('~'); // escribe '~' en UART
SERIAL_PORT_HARDWARE.write(c); // escribe char en UART
}
commandMode = false; // en todos los casos, salir del modo comando
}
}

// copiar de UART a USB-CDC


c = SERIAL_PORT_HARDWARE.read(); // leer de UART
if (c != -1) { // ¿obtuve algo?
SERIAL_PORT_USBVIRTUAL.write(c); // escribe en USB-CDC
}
}

You might also like