Skip to main content

Cómo conectarse a internet usando una red Wi-Fi o una Data Card desde una Raspberry Pi B+

¿Te gustaría realizar un script para que busque automáticamente las redes Wi-Fi conocidas alrededor de la Raspberry Pi B+ y dado el caso que no se encuentre ninguna, que está se conecte a internet usando una Data Card?.
Si continuas leyendo este post,  encontrarás posibles soluciones que te ayudarán a lograr esto de una forma muy sencilla.

Precondiciones

Adaptador Wireless USB usado: EW-7811Un (EDIMAX)

  1. Data Card usada: Huawei E173u-6
  2. Hardware usado: Raspberry Pi B+ (debería funcionar para cualquier familia de Raspberry Pi u otro hardware).
  3. Sistema Operativo usado: Raspbian.

Pasos:

Únicamente debe ejecutar estos simples comandos en la terminal de la Raspberry Pi:
# Archivo para configurar la salida a internet (Editar (i), guardar (Esc + :w) y salir (Esc + :x))
sudo vim.tiny /etc/network/interfaces
Este archivo debería de contener algo muy similar a esto:
auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
En este mismo archivo se podría hacer la configuración de la red Wi-Fi, pero para este ejemplo se va a usar wpa_supplicant. Ingrese en la terminal:
wpa_cli
# Busca las redes Wi-Fi
> scan
OK
# Muestra las redes. Esto es IMPORTANTE, ya que aquí se muestra 
# el nombre de la red a usar, la autenticación y el tipo de 
# encriptación a usar para la posterior configuración.
> scan_results
# Agregar una red
> add_network
0
> set_network 0 ssid "NombreDeLaRedWiFi"
OK
> set_network 0 psk "ContraseñaDeLaRedWiFi"
OK
# Protocolos: WPA y/o RSN.
> set_network 0 proto RSN
OK
# Este es la clave de administración o el tipo de seguridad de la 
# red, puede ser WPA-PSK (WPA/WPA2), WPA-EAP, NONE(Abierta/WPE), 
# IEEE8021X ,  WPA-PSK-SHA256 o WPA-EAP-SHA256
> set_network 0 key_mgmt WPA-PSK
OK
# Este es el tipo de encriptación de la red, puede ser 
# CCMP(WPA2), TKIP(WPA) o NONE 
> set_network 0 pairwise TKIP
OK
# Lista IEEE 802.11 de algoritmos de autenticación permitidos: 
# OPEN (requerido para WPA/WPA2), SHARED, y LEAP.
> set_network 0 auth_alg OPEN
OK
# Con este comando la RPI se debería de conectar a internet
> enable_network 0
OK
# Guardar la configuración
> save_config
OK
# Salir
> quit
Todo debería dar OK. Importante tener claro que esta aplicación lo que hace es modificar este archivo:
sudo cat /etc/wpa_supplicant/wpa_supplicant.conf
El mismo debería de verse muy similar a esto:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
        ssid="NombreDeLaRedWiFi"
        psk="ContraseñaDeLaRedWiFi"
        proto=RSN
        key_mgmt=WPA-PSK
        pairwise=TKIP
        auth_alg=OPEN
}
Por otro lado, si la RPI aún no se ha conectado a internet, puede:
# Desconectar la interface wlan0
sudo ifdown wlan0
# Y luego volverla a levantar
sudo ifup wlan0
Ahora usted tiene acceso a internet desde su Raspberry Pi (usar ifconfig para ver la Ip asignada). Pero qué pasa si está fuera del rango dado por su red Wi-Fi conocida, pues podría usar una Data Card con una SIM preferida por su proveedor de telefonía móvil, en este caso, para Costa Rica se usará una del ICE (Kolbi). Tan solo debe de ingresar estos comandos en la terminal de la RPI:
# Instalar ppp  
sudo apt-get install usb-modeswitch ppp
# Descargar sakis3g
sudo wget https://www.dropbox.com/s/chdacgf6svzvddm/sakis3g.tar.gz?dl=0
sudo mv sakis3g.tar.gz\?dl\=0 sakis3g.tar.gz
sudo tar -xzvf sakis3g.tar.gz
sudo chmod +x sakis3g
sudo mkdir -p /opt/ncubo/
sudo mv sakis3g /opt/ncubo/
sudo chown root:root /opt/ncubo/sakis3g
sudo ln -s /opt/ncubo/sakis3g /usr/bin
Para dar permisos ingrese en la consola:
# Añadir al final de siguiente archivo: su-usuario ALL = NOPASSWD: /opt/ncubo/sakis3g 
sudo visudo
Video PlayeSi está usando una SIM del ICE, se pone el PIN de la SIM (en el caso que lo requiera), en el APN_USER y APN_PASS se usó “kolbi3g”. Una vez terminado de ver y establecer la configuración dada en el video, debería de tener acceso a internet con la Data Card (tome en cuenta que si tiene un plan prepago, podría verse disminuido su saldo).
Para ver los pasos de la instalación de la Data Card (sudo sakis3g –interactive), puede ver el siguiente video:

Si está usando una SIM del ICE, se pone el PIN de la SIM (en el caso que lo requiera), en el APN_USER y APN_PASS se usó “kolbi3g”. Una vez terminado de ver y establecer la configuración dada en el video, debería de tener acceso a internet con la Data Card (tome en cuenta que si tiene un plan prepago, podría verse disminuido su saldo).

Dado que esta configuración es temporal, o sea, cuando la RPI se reinicie, es necesario volver a establecer la configuración. Para evitar esto y lograr que se conecte automáticamente cuando inicia la RPI se deben ejecutar estos simples pasos:
# Copiar el ID de la Data Card (como se muestra en la imagen de abajo)
lsusb
Crear el archivo de configuración de sakis3g:
sudo vim.tiny /etc/sakis3g.conf
Y agregar este texto, junto con el ID visto anteriormente, junto con el APN y el PIN:
USBDRIVER="option"
USBINTERFACE="0"
APN="kolbi3g"
APN_USER="kolbi3g"
APN_PASS="kolbi3g"
SIM_PIN="5998"
MODEM="12d1:1436"
Crear un script para la configuración automática de la Data Card:
sudo vim.tiny /etc/init.d/autoconnectnet
Luego se agrega el siguiente código:
#***************************************************
#! /bin/sh
# /etc/init.d/autoconnectnet

### BEGIN INIT INFO
# Provides:          noip
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Simple script to start a program at boot
# Description:       A simple script from www.stuffaboutcode.com which will start / stop a program a boot / shutdown.
### END INIT INFO

case "$1" in
  start)
    sleep 10
    echo "connecting via sakis3g"
    # run application you want to start
    /opt/ncubo/sakis3g --sudo  "connect"
    ;;
  stop)
    echo "dissconnecting via sakis3g"
    # kill application you want to stop
    /opt/ncubo/sakis3g --sudo  "disconnect"
    ;;
  *)
    echo "Usage: /etc/init.d/autoconnectnet {start|stop}"
    exit 1
    ;;
esac

exit 0
#*********************************************************
Y por último, ejecutar en terminal:
# Dar permisos de ejecución
sudo chmod 755 /etc/init.d/autoconnectnet
# Inicializar la Data Card
sudo /etc/init.d/autoconnectnet start
# Hacer que este script se ejecute automáticamente cuando la RPI inicia
sudo update-rc.d autoconnectnet defaults
¡A disfrutar del acceso a internet desde su Raspberry Pi B+!
Agradezco a Ncubo por brindarme el equipo necesario para realizar el post.

Popular posts from this blog

ISTQB - Foundation Level Agile Tester Recap

ISTQB - Foundation Level Agile Tester Recap This is a summary that will help you to approve the Agile Tester certification test. 1 - Agile Software Development 1.1 - The fundamentals of Agile Software Development  The Agile Manifesto has 4 values : - Individuals and interactions over processes and tools (people-centered) - Working software over big documentations (time to market advantage) - Customer collaboration over contract negotiation (customer requirements) - Responding to change over following plan (change is more important)   The Agile Manifesto has 12 principles : - Satisfy the customer with continuous delivery - Changing requirements - Deliver software frequently (few weeks or months) - Business people and developer must work together - Build projects around motivated individuals - Face to face conversation - Working software is the primary measure of progress - The team should maintain a constant pace indefinitely - Technical excellence and good design - Simplic

RasPI Assistant: Google Assistant + Dialogflow + Raspberry Pi

Would you like to control the TV using your voice without spend a lot of money? ... Amazing right?. So, in this post, I will teach you how to do that and more. Some of my dreams always have been control things without touch them, for example: the television, due to tired to raise the hand to change the channel. So ... let's create a device that can do this action automatically. What things will we need? First, I should understand the problem and be aware about it. For example: if we want to control a TV that is not smart, how will we do that? ... a possibility is to send infrared signals (IR) to transmit the events that the person's desire. Also, if I want that the device can hear me, I may need a microphone. Additionally, it should have a speaker to talk with the people. Further, I will need a database to save all the information, APIs that can help me with the smart logic and cheap electronic components like a Raspberry Pi , resistors, leds, wires an

How to create a simple Chatbot?

Developing an amazing Chatbot ... What is a Chatbot? First to understand how it works, you need to know how it was originated and some algorithms  like  the Natural Language Processing (NLP). It is another AI area, but it is around the language (usually written), it is the component that bridges the gap between human conversation and understanding programmed by a computer. NLP allows the computer to interpret the vast and complicated human language, understand it, process it, and effectively "speak", just like humans. Through the process, the machine has to understand all the jargon that is being using and developing or adapting with the ability to respond, as a human computer. NLP has to do with the creation of systems that process or "understand" the language to perform certain tasks, such as answering questions, analyzing the sentiment in a sentence, making translations between different languages, and another. In the past, the NLP involved a lot