Posts Tagged Networking

Using Weave to Network a Docker Multi-Container Java Application

Use the latest version of Weaveworks’ Weave Net to network a multi-container, Dockerized Java Spring web application.

Introduction Weave Image

Introduction

The last post demonstrated how to build and deploy the Java Spring Music application to a VirtualBox, multi-container test environment. The environment contained (1) NGINX container, (2) load-balanced Tomcat containers, (1) MongoDB container, (1) ELK Stack container, and (1) Logspout container, all on one VM.

Spring Music

In that post, we used Docker’s links option. The links options, which modifies the container’s /etc/hosts file, allows two Docker containers to communicate with each other. For example, the NGINX container is linked to both Tomcat containers:

proxy:
  build: nginx/
  ports: "80:80"
  links:
   - app01
   - app02

Although container linking works, links are not very practical beyond a small number of static containers or a single container host. With linking, you must explicitly define each service-to-container relationship you want Docker to configure. Linking is not an option with Docker Swarm to link containers across multiple virtual machine container hosts. With Docker Networking in its early ‘experimental’ stages and the Swarm limitation, it’s hard to foresee the use of linking for any uses beyond limited development and test environments.

Weave Net

Weave Net, aka Weave, is one of a trio of products developed by Weaveworks. The other two members of the trio include Weave Run and Weave Scope. According to Weaveworks’ website, ‘Weave Net connects all your containers into a transparent, dynamic and resilient mesh. This is one of the easiest ways to set up clustered applications that run anywhere.‘ Weave allows us to eliminate the dependency on the links connect our containers. Weave does all the linking of containers for us automatically.

Weave v1.1.0

If you worked with previous editions of Weave, you will appreciate that Weave versions v1.0.x and v1.1.0 are significant steps forward in the evolution of Weave. Weaveworks’ GitHub Weave Release page details the many improvements. I also suggest reading Weave ‘Gossip’ DNS, on Weavework’s blog, before continuing. The post details the improvements of Weave v1.1.0. Some of those key new features include:

  • Completely redesigned weaveDNS, dubbed ‘Gossip DNS’
  • Registrations are broadcast to all weaveDNS instances
  • Registered entries are stored in-memory and handle lookups locally
  • Weave router’s gossip implementation periodically synchronizes DNS mappings between peers
  • Ability to recover from network partitions and other transient failures
  • Each peer is aware of the hostnames and IP address of all containers in the Weave network.
  • weave launch now launches all weave components, including the router, weaveDNS and the proxy, greatly simplifying setup
  • weaveDNS is now embedded in the Weave router

Weave-based Network

In this post, we will reuse the Java Spring Music application from the last post. However, we will replace the project’s static dependencies on Docker links with Weave. This post will demonstrate the most basic features of Weave, using a single cluster. In a future post, we will demonstrate how easily Weave also integrates with multiple clusters.

All files for this post can be found in the swarm-weave branch of the GitHub Repository. Instructions to clone are below.

Configuration

If you recall from the previous post, the Docker Compose YAML file (docker-compose.yml) looked similar to this:

proxy:
  build: nginx/
  ports: "80:80"
  links:
   - app01
   - app02
  hostname: "proxy"

app01:
  build: tomcat/
  expose: "8080"
  ports: "8180:8080"
  links:
   - nosqldb
   - elk
  hostname: "app01"

app02:
  build: tomcat/
  expose: "8080"
  ports: "8280:8080"
  links:
   - nosqldb
   - elk
  hostname: "app01"

nosqldb:
  build: mongo/
  hostname: "nosqldb"
  volumes: "/opt/mongodb:/data/db"

elk:
  build: elk/
  ports:
   - "8081:80"
   - "8082:9200"
  expose: "5000/upd"

logspout:
  build: logspout/
  volumes: "/var/run/docker.sock:/tmp/docker.sock"
  links: elk
  ports: "8083:80"
  environment: ROUTE_URIS=logstash://elk:5000

Implementing Weave simplifies the docker-compose.yml, considerably. Below is the new Weave version of the docker-compose.yml. The links option have been removed from all containers. Additionally, the hostnames have been removed, as they serve no real purpose moving forward. The logspout service’s environment option has been modified to use the elk container’s full name as opposed to the hostname.

The only addition is the volumes_from option to the proxy service. We must ensure that the two Tomcat containers start before the NGINX containers. The links option indirectly provided this functionality, previously.

proxy:
  build: nginx/
  ports:
   - "80:80"
  volumes_from:
   - app01
   - app02

app01:
  build: tomcat/
  expose:
   - "8080"
  ports:
   - "8180:8080"

app02:
  build: tomcat/
  expose:
   - "8080"
  ports:
   - "8280:8080"

nosqldb:
  build: mongo/
  volumes:
   - "/opt/mongodb:/data/db"

elk:
  build: elk/
  ports:
   - "8081:80"
   - "8082:9200"
  expose:
   - "5000/upd"

logspout:
  build: logspout/
  volumes:
   - "/var/run/docker.sock:/tmp/docker.sock"
  ports:
   - "8083:80"
  environment:
    - ROUTE_URIS=logstash://music_elk_1:5000

Next, we need to modify the NGINX configuration, slightly. In the previous post we referenced the Tomcat service names, as shown below.

upstream backend {
  server app01:8080;
  server app02:8080;
}

Weave will automatically add the two Tomcat container names to the NGINX container’s /etc/hosts file. We will add these Tomcat container names to NGINX’s configuration file.

upstream backend {
  server music_app01_1:8080;
  server music_app02_1:8080;
}

In an actual Production environment, we would use a template, along with a service discovery tool, such as Consul, to automatically populate the container names, as containers are dynamically created or destroyed.

Installing and Running Weave

After cloning this post’s GitHub repository, I recommend first installing and configuring Weave. Next, build the container host VM using Docker Machine. Lastly, build the containers using Docker Compose. The build_project.sh script below will take care of all the necessary steps.

#!/bin/sh

########################################################################
#
# title:          Build Complete Project
# author:         Gary A. Stafford (https://programmaticponderings.com)
# url:            https://github.com/garystafford/sprint-music-docker  
# description:    Clone and build complete Spring Music Docker project
#
# to run:         sh ./build_project.sh
#
########################################################################

# install latest weave
curl -L git.io/weave -o /usr/local/bin/weave && 
chmod a+x /usr/local/bin/weave && 
weave version

# clone project
git clone -b swarm-weave \
  --single-branch --branch swarm-weave \
  https://github.com/garystafford/spring-music-docker.git && 
cd spring-music-docker

# build VM
docker-machine create --driver virtualbox springmusic --debug

# create diectory to store mongo data on host
docker ssh springmusic mkdir /opt/mongodb

# set new environment
docker-machine env springmusic && 
eval "$(docker-machine env springmusic)"

# launch weave and weaveproxy/weaveDNS containers
weave launch &&
tlsargs=$(docker-machine ssh springmusic \
  "cat /proc/\$(pgrep /usr/local/bin/docker)/cmdline | tr '\0' '\n' | grep ^--tls | tr '\n' ' '")
weave launch-proxy $tlsargs &&
eval "$(weave env)" &&

# test/confirm weave status
weave status &&
docker logs weaveproxy

# pull and build images and containers
# this step will take several minutes to pull images first time
docker-compose -f docker-compose.yml -p music up -d

# wait for container apps to fully start
sleep 15

# test weave (should list entries for all containers)
docker exec -it music_proxy_1 cat /etc/hosts 

# run quick test of Spring Music application
for i in {1..10}
do
  curl -I --url $(docker-machine ip springmusic)
done

One last test, to ensure that MongoDB is using the host’s volume, and not storing data in the MongoDB container’s /data/db directory, execute the following command: docker-machine ssh springmusic ls -Alh /opt/mongodb. You should see MongoDB-related content being stored here.

Testing Weave

Running the weave status command, we should observe that Weave returned a status similar to the example below:

gstafford@gstafford-X555LA:$ weave status

       Version: v1.1.0

       Service: router
      Protocol: weave 1..2
          Name: 6a:69:11:1b:b4:e3(springmusic)
    Encryption: disabled
 PeerDiscovery: enabled
       Targets: 0
   Connections: 0
         Peers: 1

       Service: ipam
     Consensus: achieved
         Range: [10.32.0.0-10.48.0.0)
 DefaultSubnet: 10.32.0.0/12

       Service: dns
        Domain: weave.local.
           TTL: 1
       Entries: 2

       Service: proxy
       Address: tcp://192.168.99.100:12375

Running the docker exec -it music_proxy_1 cat /etc/hosts command, we should observe that WeaveDNS has automatically added entries for all containers to the music_proxy_1 container’s /etc/hosts file. WeaveDNS will also remove the addresses of any containers that die. This offers a simple way to implement redundancy.

gstafford@gstafford-X555LA:$ docker exec -it music_proxy_1 cat /etc/hosts

# modified by weave
10.32.0.6       music_proxy_1
127.0.0.1       localhost

172.17.0.131    weave weave.bridge
172.17.0.133    music_elk_1 music_elk_1.bridge
172.17.0.134    music_nosqldb_1 music_nosqldb_1.bridge
172.17.0.138    music_app02_1 music_app02_1.bridge
172.17.0.139    music_logspout_1 music_logspout_1.bridge
172.17.0.140    music_app01_1 music_app01_1.bridge

::1             ip6-localhost ip6-loopback localhost
fe00::0         ip6-localnet
ff00::0         ip6-mcastprefix
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters

Weave resolves the container’s name to eth0 IP address, created by Docker’s docker0 Ethernet bridge. Each container can now communicate with all other containers in the cluster.

Weave eth0 Network

Results

Resulting virtual machines, network, images, and containers:

gstafford@gstafford-X555LA:$ docker-machine ls
NAME            ACTIVE   DRIVER       STATE     URL                         SWARM
springmusic     *        virtualbox   Running   tcp://192.168.99.100:2376   


gstafford@gstafford-X555LA:$ docker images
REPOSITORY             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
music_app02            latest              632c782010ac        3 days ago          370.4 MB
music_app01            latest              632c782010ac        3 days ago          370.4 MB
music_proxy            latest              171624a31920        3 days ago          144.5 MB
music_nosqldb          latest              2b3b46af5ef3        3 days ago          260.8 MB
music_elk              latest              5c18dae84b26        3 days ago          1.05 GB
weaveworks/weaveexec   v1.1.0              69c6bfa7934f        5 days ago          58.18 MB
weaveworks/weave       v1.1.0              5dccf0533147        5 days ago          17.53 MB
music_logspout         latest              fe64597ab0c4        8 days ago          24.36 MB
gliderlabs/logspout    master              40a52d6ca462        9 days ago          14.75 MB
willdurand/elk         latest              04cd7334eb5d        2 weeks ago         1.05 GB
tomcat                 latest              6fe1972e6b08        2 weeks ago         347.7 MB
mongo                  latest              5c9464760d54        2 weeks ago         260.8 MB
nginx                  latest              cd3cf76a61ee        2 weeks ago         132.9 MB


gstafford@gstafford-X555LA:$ weave ps
weave:expose 6a:69:11:1b:b4:e3
2bce66e3b33b fa:07:7e:85:37:1b 10.32.0.5/12
604dbbc4473f 6a:73:8d:54:cc:fe 10.32.0.4/12
ea64b42cf5a1 c2:69:73:84:67:69 10.32.0.3/12
85b1e8a9b8d0 aa:f7:12:cd:b7:13 10.32.0.6/12
81041fc97d1f 2e:1e:82:67:89:5d 10.32.0.2/12
e80c04bdbfaf 1e:95:a5:b2:9d:30 10.32.0.1/12
18c22e7f1c33 7e:43:54:db:8d:b8


gstafford@gstafford-X555LA:$ docker ps -a
CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS                                                                                            NAMES
2bce66e3b33b        music_app01                   "/w/w catalina.sh run"   3 days ago          Up 3 days           0.0.0.0:8180->8080/tcp                                                                           music_app01_1
604dbbc4473f        music_logspout                "/w/w /bin/logspout"     3 days ago          Up 3 days           8000/tcp, 0.0.0.0:8083->80/tcp                                                                   music_logspout_1
ea64b42cf5a1        music_app02                   "/w/w catalina.sh run"   3 days ago          Up 3 days           0.0.0.0:8280->8080/tcp                                                                           music_app02_1
85b1e8a9b8d0        music_proxy                   "/w/w nginx -g 'daemo"   3 days ago          Up 3 days           0.0.0.0:80->80/tcp, 443/tcp                                                                      music_proxy_1
81041fc97d1f        music_nosqldb                 "/w/w /entrypoint.sh "   3 days ago          Up 3 days           27017/tcp                                                                                        music_nosqldb_1
e80c04bdbfaf        music_elk                     "/w/w /usr/bin/superv"   3 days ago          Up 3 days           5000/0, 0.0.0.0:8081->80/tcp, 0.0.0.0:8082->9200/tcp                                             music_elk_1
8eafc6225fc1        weaveworks/weaveexec:v1.1.0   "/home/weave/weavepro"   3 days ago          Up 3 days                                                                                                            weaveproxy
18c22e7f1c33        weaveworks/weave:v1.1.0       "/home/weave/weaver -"   3 days ago          Up 3 days           172.17.42.1:53->53/udp, 0.0.0.0:6783->6783/tcp, 0.0.0.0:6783->6783/udp, 172.17.42.1:53->53/tcp   weave

Spring Music Application Links

Assuming springmusic VM is running at 192.168.99.100, these are the accessible URL for each of the environment’s major components:

* The Tomcat user name is admin and the password is t0mcat53rv3r.

Helpful Links

, , , , , , , , ,

Leave a comment

Remote Motion-Activated Web-Based Surveillance with Raspberry Pi

Introduction

Want to keep an eye on your home or business while you’re away? Maybe observe wildlife close-up without disturbing them? Or, keep an eye on your kids playing in the backyard? Low-end wireless IP cameras start at $50-$75 USD. Higher-end units can run into the hundreds of dollars. Add motion detection and the price raises even further. How about a lower-cost solution? Using a Raspberry Pi with an inexpensive webcam, a wireless WiFi Module, and an optional battery pack, you can have a remote, motion-activated camera solution, at a fraction of the cost. Best of all, you won’t need to write a single line of code or hack any electronics to get started.

_MG_9526

Motion

There are many posts on the Internet, demonstrating how to build a Raspberry Pi-powered motion-activated camera system. One of the more frequently used off-the-shelf applications for these projects is Motion. According to their website, ‘Motion is a program that monitors the video signal from one or more cameras and is able to detect if a significant part of the picture has changed; in other words, it can detect motion‘. Motion uses a technique known as visual motion detection (VMD) to compare a series of sequential camera frames for differences at a pixel level. A change between a series of sequential frames is an indication of movement.

Motion has the ability to stream images from a webcam and server them from it’s built-in web server, with little or no configuration. In addition, Motion is easily configured to work with streaming video applications like the very popular FFmpeg, and save images to databases like mySQL or PostgreSQL. Motion can also execute external scripts such as python or shell. In this post, we are going to use Motion’s most basic features, motion detection and web-streaming.

Installing Motion

Firmware Update
Before installing Motion, I recommend ensuring your Raspberry Pi is up-to-date with the latest software and firmware. Updating firmware is not necessary. However, I was recently helping someone with camera issue on their Raspberry Pi. Finding a few suggestions online for similar problems, we updated the firmware on the Raspberry Pi. It fixed the problem. Installing firmware can sound a bit intimidating. However, Liam McLoughlin (hexxeh) has made the process easy with rpi-update. I have used it successfully on multiple Raspberry Pi’s. Three commands is all it takes to update your Raspberry Pi to the latest firmware.

Software Update
You should also update your Raspberry Pi’s existing software. To update your Raspberry Pi’s software, execute the following apt-get commands:

sudo apt-get update && sudo apt-get upgrade

If you don’t do this on a regular basis, as recommended, these could take up to several minutes. Watch for errors. If there are any errors, try to run the command again. Sometimes the Raspberry Pi cannot connect to all code repositories for updates.

Installing Motion
Once the updates are complete, install Motion by issuing the following command:

sudo apt-get install motion

Enabling Motion

As the installation completes, you should see a warning in the command shell about Motion being disabled by default.

...
Adding user `motion' to group `video' ...
Adding user motion to group video
Done.
[warn] Not starting motion daemon, disabled via /etc/default/motion ... (warning).
Setting up ffmpeg (6:0.8.4-1) ...
pi@garyrasppi ~ $

To enable Motion (the motion daemon), we need to edit the /etc/default/motion file.

sudo nano /etc/default/motion

Change the ‘start_motion_daemon‘ parameter to ‘yes’.

Enable Daemon

Configuring Motion

Motion is easy to customize with loads of parameters you can tweak based on your needs. Motion has no GUI. All configuration is all done through Motion’s configuration file (/etc/motion/motion.conf). Before editing the configuration file, we need to change the permissions on it, so Motion can get access to it. While we are at it, we will also change permissions on the folder where Motion stores captured images.

sudo chmod -R 777 /etc/motion/motion.conf
sudo chmod -R 777 /tmp/motion

After changing the permissions, to configure Motion, open the Motion’s configuration file in a text editor, as root (sudo). I like using Nano. The configuration file can be opened in Nano with the following command:

sudo nano /etc/motion/motion.conf

Motion’s configuration file is lengthy. However, it is broken down into logical sections, making finding the setting you are looking for, easy. First, we need to change the ‘Live Webcam Server’ section of configuration. Below are the default settings:

############################################################
# Live Webcam Server
############################################################

# The mini-http server listens to this port for requests (default: 0 = disabled)
webcam_port 8081

# Quality of the jpeg (in percent) images produced (default: 50)
webcam_quality 50

# Output frames at 1 fps when no motion is detected and increase to the
# rate given by webcam_maxrate when motion is detected (default: off)
webcam_motion off

# Maximum framerate for webcam streams (default: 1)
webcam_maxrate 1

# Restrict webcam connections to localhost only (default: on)
webcam_localhost on

# Limits the number of images per connection (default: 0 = unlimited)
# Number can be defined by multiplying actual webcam rate by desired number of seconds
# Actual webcam rate is the smallest of the numbers framerate and webcam_maxrate
webcam_limit 0

The first thing you will want to change is Motion’s default setting that restricts image streaming to ‘localhost‘, only ( ‘webcam_localhost on‘). This means you can only view images in a web browser on the Raspberry Pi, not remotely over your network. Change that line of code to read ‘webcam_localhost off‘.

The next setting I recommend changing for security purposes is the default port Motion’s web server uses to stream images, 8081. Security through obscurity is better than no security at all. Change port 8081 to a different arbitrary port, for example, 6789 (‘webcam_port 6789‘). Just make sure you don’t pick a port already in use by another service or application. Having made this change, if your Raspberry Pi’s local IP address is 192.168.1.9, images from the webcam should be accessible at 192.168.1.9:6789.

The other two settings in this section you can play with are the webcam quality and maximum frame-rate. You will have to adjust this based on your network speed and the processing power of your Raspberry Pi. The default settings are a good place to start. I changed my quality from the default of 50 to 80 (‘webcam_quality 80‘), and changed my max frame-rate to 2 (‘webcam_maxrate 2‘).

Speaking of quality, the other two settings you may want to change are the width and height of the image being captured by Motion. The ‘Capture device options’ section is where we change these settings. As the configuration’s comments suggest, these settings are dependent on your camera. Check the camera’s available image sizes; you will need to use one of those size combinations. I have mine set to an average size of 352 x 288. This is a good size for those of us with a slower network, or when streaming video over the Internet to mobile web browser. Conversely, a larger image is better for viewing over your local network.

Image size, like compression quality, and frame-rate are dependent on processing power of your Raspberry Pi and it’s OS (Raspbian, Debian, Arch, etc.). You may need to play with these settings to get the desired results. I couldn’t stream images larger than 352 x 288 over the Internet, with my Raspberry Pi, even though my webcam could capture up to 640 x 480 pixels.

# Image width (pixels). Valid range: Camera dependent, default: 352
width 352

# Image height (pixels). Valid range: Camera dependent, default: 288
height 288

It’s important to remember, each time you make changes to Motion’s configuration file, you must restart Motion, using the following command.

sudo /etc/init.d/motion restart

Viewing Your Webcam Remotely

To view your webcam’s output from another device on your local network, point your web browser to the IP address of your Raspberry Pi, and add the port you assigned in Motion’s configuration file. Motion may take up to 15-20 seconds to start responding in the browser. If it takes longer, you probably have your image size, frame-rate, and compression settings to high for your Raspberry Pi.

Over the Internet
Enabling your webcam’s output over the Internet is relatively easy with the average home router and Internet service provider. Suppose the IP address of my Raspberry Pi, on my local network, is 192.168.1.9. Suppose I assigned port 6789 to Motion’s web server. Lastly, suppose my router’s external Internet IP address is 113.45.67.88. With this information, I can create a port-forwarding rule in my router, allowing all external HTTP traffic over TCP to 113.45.67.88:3456, to be automatically forwarded internally to 192.168.1.9:6789. The external port, 3456, is totally arbitrary, just make sure you don’t pick a port already in use.

Netgear Port Forwarding

IMPORTANT SECURITY NOTE: There are no passwords or other network protection used with this method. Make sure to keep the external IP address and port combination private, and always stop Motion, or better yet your Raspberry Pi, when not in use. Otherwise, someone could potentially be watching you!

Down at the local coffee shop, I decide to check if the mailman has delivered my new Raspberry Pi to the front porch. Having set-up port-forwarding, I enter 113.45.67.88:3456 in my smartphone’s web browser. My Internet provider routes the HTTP request to my Internet router. My router receives the request and forwards it over my local network to 192.168.1.9:6789, where Motion’s built-in web server on my Raspberry Pi is running. Motion’s web server responds by streaming still images back to my phone at the coffee shop when it detects motion. Still no sign of the mailman or my Raspberry Pi…

Static IP Addresses
I recommend using a static IP address for your Raspberry Pi, versus DHCP, if possible. Else, you will have to change your router’s port-forwarding rules each time your Raspberry Pi’s DHCP lease is renewed and its local IP address changes. There are some ways to prevent addressed from changing frequently with DHCP, if your router supports it. Look for configurable lease times or reservations options in your router’s configuration; these may be able to be extended.

Locating Your External Internet IP Address
What is your router’s external Internet IP address? To find mine, I looked in Netgear’s Router Status window. You can also use a ‘tracert’ from the command line, if you know what to look for in the output.

Since I do not pay my Internet-provider for a static external Internet IP address, the address my provider assigns to my router is dynamic. It can and will change, sometimes almost never, or sometimes daily. The frequency of change depends on your provider. To view your webcam’s images, you will need to know your router’s current external Internet IP address.

Motion Example

Here are some example from a Microsoft LifeCam VX-500 and Logitech Webcam C210 webcams. The highest quality I could consistently stream over the Internet, from my Raspberry Pi 512Mb Model B, with both Soft-float Debian “wheezy” and Raspbian “wheezy”, was 352 x 288 at 80% compression and 2 fsp max. Locally on my LAN, I could reach a frame size of 640 x 480 pixels.

In the first example, I’ve placed the Raspberry Pi in a plastic container to protect it, and mounted the webcam in a flower box. Viewing the feed over my local network, we are able to watch the hummingbirds without scaring them.

Hummingbird Feeder Remote Camera

In the next two images, I’ve turned on Motion’s ‘locate box’ option, which tracks the exact area within the image that is moving. As the person come into view of the camera mounted near the front door, Motion detects and outlines the area of the images where it detects movement.

Front Entrance

Capture2

In the next video, you see the view from a Google Nexus 7 tablet. My wife and I use the Raspberry Pi surveillance system to watch our backyard when our kids are outside (the camera is no substitute for adult supervision when the kids are in the pool).

This last image is from my iPhone, while shopping at the local grocery store. My wife was impressed with my port-forwarding knowledge. OK, not really, but she did enjoy showing off the Christmas tree to friends, remotely, even if it wasn’t in motion.

iPhone Scaled

Useful Links

Here are a few links to other useful articles on the use of Motion with the Raspberry Pi:

Raspberry Pi-Powered Dashboard Video Camera Using Motion and FFmpeg

Setup a webcam security system with Ubuntu Linux and Motion

Guest blog #7: Bird table webcam by Francis Agius

Raspberry Pi webcam

motion(1) – Linux man page (good source for understand Motion config)

Linux UVC Supported Devices (a good starting point for buying a webcam)

, , , , , , , , , , , , , , ,

56 Comments

Installing a Miniature WiFi Module on the Raspberry Pi (w/ Roaming Enabled)

Background

In a earlier post, Installing a Miniature WiFi Module on the Raspberry Pi (w/o Roaming Enabled), I detailed the installation and configuration of a Miniature WiFi Module, from Adafruit Industries, on a RaspPi running Soft-float Debian “wheezy”. As I mentioned in that post, there was more than one method of configuring the WiFi Module (WNIC) on a WLAN, based on the research I did. I chose the simple method of hard-coding a single WLAN configuration into the ‘/etc/interfaces’ file.

Recently, while installing the same type WiFi Module (WNIC) on a RaspPi running Raspbian “wheezy”, I chose the alternate method. This involves adding the WLAN configuration to the wpa_supplicant configuration file (‘/etc/wpa_supplicant/wpa_supplicant.conf’). You can add multiple WLAN configurations to the wpa_supplicant configuration file. This allowing the RaspPi to roam from networks to network, automatically connecting to those that are configured.

If you’re not comfortable configuring networks from the command shell, you can also use the wpa_gui application (aka wpa_suppicant user interface) from the RaspPi’s desktop. It allows you to edit the same configuration from a gui, just as we will do manually in the command shell.

wpa_gui

Installing the WiFi Module Driver

Copy the ‘Linux and Android’ Realtek driver folder from the CD, supplied by the manufacturer, to the ‘tmp’ folder on the RaspPi using WinSCP. Then, run the following commands:

cd /
cd /tmp/Linux\ and\ Android
chmod +x install.sh
sudo ./install.sh

Remember to select #1 when asked to choose a card type:

...
Please select card type(1/2):
1) RTL8192cu
2) RTL8192du
#? 1

You can insert the WiFi Module at this point in the process.

Installing Wireless LAN Security Protocol Software

As detailed in the earlier post, we need to install software that allows us to configure and connect to our WPA/WPA2-secured wireless network. The particular software is referred to as ‘wpa_supplicant’. To install ‘wpa_supplicant’ and the ‘wpagui’, enter the following commands. Note this will check for any upgrades to the RaspPi’s existing software, first. This is a commonly-recommended step. The upgrade command might take a few minutes if you haven’t run this on your RaspPi in a while.

sudo apt-get update && sudo apt-get upgrade
sudo apt-get install wpasupplicant wpagui

Configuring the New WiFi Adapter

Examine the contents of the ‘/etc/networks/interfaces’ file, by entering the following command:

sudo cat /etc/network/interfaces

Unlike in the first post, we will make no changes to this file. The ‘/etc/networks/interfaces’ file should have the default settings for both the current NIC (eth0) as well as for the WNIC (wlan0), as shown below. Note the reference to the ‘/etc/wpa_supplicant/wpa_supplicant.conf’ file. Why are the file’s contents different than in the first post? Because we installed ‘wpagui’.

Raspbian Version of Interfaces File

WPA Supplicant Configuration
Enter the following command, substituting your own SSID (‘your_ssid’) and passphrase (‘your_passphrase’).

wpa_passphrase your_ssid your_passphrase

Based your SSID and passphrase, this command will generate a pre-shared key (PSK), similar to the following. Save or copy the PSK to the clipboard; we will need it in the next step.

Creating PSK

Next, open the ‘/etc/wpa_supplicant/wpa_supplicant.conf’ file using Nano, by entering the following command:

sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

Add the following code at the end of the file. Remember to substitute your_ssid and your_psk_or_passphrase. Note the following settings are specific to my WPA2-secured network. If you are using WPA, refer to this post for the correct WPA settings.

network={
        ssid="your_ssid"
        proto=RSN
        key_mgmt=WPA-PSK
        pairwise=CCMP
        group=CCMP
        psk="your_psk_or_passphrase"
}

Your final file should look similar to this:

Raspbian Version of wpa_supplicant.conf File

Save the file and exit Nano. Lastly, execute the following series of commands to assign an IP address to the new WNIC.

sudo wpa_supplicant -d -c /etc/wpa_supplicant/wpa_supplicant.conf -i wlan0 -D wext
sudo ifconfig wlan0 up
sudo dhclient wlan0
sudo wpa_supplicant -B -c /etc/wpa_supplicant/wpa_supplicant.conf -i wlan0 -D wext 
ip addr show wlan0

You should see an IP Address for ‘wlan0’ displayed. That it, shutdown the RaspPi, remove the Ethernet cable, and restart the RaspPi. Use a program like ‘Advanced IP Scanner’ for Windows, or ‘Fing’ for iOS, to discover the wireless IP address of the RaspPi. The RaspPi will show up with the WiFi chipset manufacturer’s name, ‘REALTEK SEMICONDUCTOR’ or ‘REALTEK SEMICONDUCTOR CORP.’. Use this address to re-connect to the RaspPi.

Need to add another network’s configuration? Simply enter the information in the ‘/etc/wpa_supplicant/wpa_supplicant.conf’ and restart. Here are a few good articles I found on configuring a WiFi Module on the RaspPi with roaming:

http://hostap.epitest.fi/wpa_supplicant/

http://www.cyberciti.biz/faq/linux-ndiswrapper-wpa_supplicant-howto/

http://linux.die.net/man/5/wpa_supplicant.conf

http://ubuntuforums.org/showthread.php?t=1259003

http://ubuntuforums.org/showthread.php?t=318539

http://unix.stackexchange.com/questions/7817/how-to-find-out-which-wi-fi-driver-is-installed

, , , , , , , , , , , , , , , , ,

Leave a comment

Installing a Miniature WiFi Module on the Raspberry Pi (w/o Roaming Enabled)

One of the best purchases I’ve made recently was a Miniature WiFi Module for my Raspberry Pi, from Adafruit Industries. No more having my RaspPi tethered to an Ethernet port on my wireless router. I can have my RaspPi with me, wherever I’m working. At the same time, I have Internet access on both my laptop and the RaspPi. All this for less than $12!

OURLiNK WiFi Module Installed

Background

The Miniature WiFi Module is technically a wireless network interface controller (WNIC). It connects the RaspPi to a wireless local area network (WLAN). Wherever you see the word ‘Interface’ in this post, it is referring to either the new Miniature WiFi Module, or the built-in network interface controller (NIC), which connects the RaspPi to a local area network (LAN) via Ethernet.

In researching how to properly install and configure the WiFi Module, I read a number of articles and posts on the Internet. The simplest approach I found was presented in this article by Macro M.C. on MacroMC.com. Much of the following is based on his article. Marco directly edits the ‘interfaces’ file, instead of also editing the ‘wpa_supplicant.conf’ file, as is demonstrated in other posts. I will only be connecting my RaspPi to a single WLAN in this post. If you will be switching between multiple WLANs with your RaspPi, you might want to investigate the alternate method of editing the ‘wpa_supplicant.conf’ file, or using the wpa supplicant user interface, instead.

I will be installing and configuring my RaspPi using a Windows laptop. However, if you are using a Mac or Linux-based computer, you shouldn’t need change these directions. Also, I am using the WPA2-Personal security protocol on my home’s wireless network. These directions should work for both commonly used WPA and WPA2 wireless network security protocols; I will explain further in step 2. Lastly, since I largely develop Java SE Embedded applications for the Raspberry Pi, I have installed Soft-float Debian “wheezy” on my RaspPi. However, these directions should also work for the more commonly installed Raspbian “wheezy”, as well.

Getting Started

The configuration and installation of the Miniature WiFi Module takes less 15 minutes. I’ve broken the process down into three steps:

  1. Installing the WiFi Module driver
  2. Installing wireless LAN security protocol software
  3. Configuring the new WiFi Module

Before we start, make sure you have the following items available:

  • Your wireless network’s name (aka SSID)
  • Your network security key (aka passphrase)
  • SSH enabled on your RaspPi
  • LAN access to your RaspPi
  • Internet access from your RaspPi
  • PuTTY to your RaspPi
  • WinSCP to copy files to your RaspPi
  • Advanced IP ScannerFing, or similar network scanning software (optional)

Installing the WiFi Module Driver

Don’t insert the WiFi Module into the RaspPi, yet. Instead, connect the RaspPi to your LAN using an Ethernet cable. Make sure the RaspPi has Internet access. Insert the small CD that comes with the WiFi Module into your laptop’s CD/DVD player. Connect to the RaspPi from your laptop using WinSCP. Copy the ‘Linux and Android’ folder from the CD to the ‘tmp’ folder on the RaspPi, as shown below.

Copy Driver to RaspPi with WinSCP

Before we install the driver, let’s examine the current network interface configuration on the RaspPi. Log into your RaspPi using PuTTY. Using the ifconfig command, you should only see the built-in NIC (eth0), as shown in the example below.

Initial View of Network Interfaces

Realtek is the WiFi Module’s chipset manufacturer. To install the Realtek WiFi Module driver on the RaspPi, enter the following series of commands.

cd /
cd /tmp/Linux\ and\ Android
chmod +x install.sh
sudo ./install.sh

During the install you’ll be prompted to select between two card types, enter 1;

...
Please select card type(1/2):
1) RTL8192cu
2) RTL8192du
#? 1

Installing Wireless LAN Security Protocol Software

After installing the driver, we need to install software that allows us to configure and connect to our WPA-secured wireless network. The particular software is referred to as ‘wpa_supplicant’. According to Jouni Malinenwpa_supplicant is a WPA Supplicant for Linux, BSD, Mac OS X, and Windows with support for WPA and WPA2 (IEEE 802.11i / RSN). It is suitable for both desktop/laptop computers and embedded systems. Supplicant is the IEEE 802.1X/WPA component that is used in the client stations. It implements key negotiation with a WPA Authenticator and it controls the roaming and IEEE 802.11 authentication/association of the wlan driver.

To install wpa_supplicant, enter the following commands. Note this will check for any upgrades to the RaspPi’s existing software, first. This is a commonly-recommended step. The upgrade command might take a few minutes if you haven’t run this on your RaspPi in a while.

sudo apt-get update && sudo apt-get upgrade
sudo apt-get install wpasupplicant

Next, enter the following command, substituting your own SSID (‘your_ssid’) and passphrase (‘your_passphrase’).

wpa_passphrase your_ssid your_passphrase

Based your SSID and passphrase, this command will generate a pre-shared key (PSK), similar to the following. Save or copy the PSK to the clipboard; we will need it in the next step.

Creating PSK

Configuring the New WiFi Adapter

The last step is to configure the new WiFi Module (WNIC) for your WLAN. Open the ‘/etc/networks/interfaces’ file using Nano, by entering the following command.

sudo nano /etc/network/interfaces

This file will only have the default settings for the current NIC (eth0), as shown below.

Original Interfaces File Content

To add the new WNIC (wlan0), enter the following lines of code to the end of the ‘interfaces’ file. Substitute you SSID (‘your_ssid’) in quotes and the PSK you generated in the previous step. Do not use the SSID and PSK below, it will not work for your network, it is only an example.

auto wlan0
allow-hotplug wlan0
iface wlan0 inet dhcp
   wpa-ssid "your_ssid"
   wpa-psk b2abb0fcd2f4527e11817de0823a57bb19ba4622f4595062c94ec4dd1370b5fe

Save the file and exit Nano. Shutdown the RaspPi and remove the Ethernet cable. Insert the Miniature WiFi Module and restart the RaspPi. You should not run the RaspPi with both the LAN and WLAN Interfaces connected.

Finding the Raspberry Pi’s Wireless Address
Since you used Dynamic Host Configuration Protocol (DHCP) in the interface’s configuration, the Module has been assigned a new IP address. To find the RaspPi’s new wireless IP address, log directly into the RaspPi and use the ifconfig command. Alternately, we can use a program like ‘Advanced IP Scanner’ for Windows or ‘Fing’ for iOS, to discover the address of the RaspPi. The RaspPi will show up with the WiFi chipset manufacturer’s name, ‘REALTEK SEMICONDUCTOR’ or ‘REALTEK SEMICONDUCTOR CORP.’.

In the example below from Fing on an iPhone, there are two wireless RaspPi’s on my network, an inactive wireless RaspPi at 192.168.1.7, and my active wireless RaspPi at 192.168.1.9.

iPhone Fing View of Network

Here is another view of my network using Advanced IP Scanner on Windows. My active wireless RaspPi at 192.168.1.9.

Advanced IP Scanner View of Network

If you are unable to find your RaspPi on the WLAN, re-connect to the RaspPi directly and check for errors. I had to do this on more than a few occasions while researching this post, mostly due to typos in my interface file. Try rebooting the RaspPi and watch the shutdown and boot-up screens for errors.; network errors will often show up here.

Use the RaspPi’s new wireless IP address you found to connect back into your RaspPi with PuTTY. To better understand how the new WiFi Module (WNIC) is configured, run the ifconfig command, again. This time you should see both the NIC (eth0) and WNIC (wlan0).

Final View of Network Interfaces

Congratulations, your RaspPi is wireless. Please feel free to ‘move about the cabin’. -gs

, , , , , , , , , , , , , , , , ,

12 Comments