RaspberryPi als 3G / WIFI Gateway

09.12.2021

Raspberry Pi as a 3g (Huawei E303) wireless (Edimax ESet up the Raspberry Pi as a wireless router using the Raspbian OS. The internet connection will be provided by a Huawei E303 USB 3g dongle on the safaricom network in Kenya, though the setup should be similar on most Huawei dongles and 3g networks. The wireless access point will be provided by an Edimax Nano USB Wifi adapter.

The USB ports of the Pi seem to struggle to provide the power for a 3g dongle, so a powered USB hub is necessary.

After a lot of reading and messing around, I’ve come up with a step by step guide for setting up my Pi as a wireless internet router. I use this every time I make a fresh setup of Raspbian, which is a fairly regular event. Stumbling round my latest install like a drunken elephant, it never takes me long to screw something up so badly that it’s easier just to start from scratch.

As such, this guide assumes that the Raspbian operating system is ‘fresh’. It has been tested with the 2012-12-16 release - as soon as I have the time free, I’ll update the guide for the newest release. So, the steps I use to set up the ‘Pifi’ Router are as follows:

Step 1: Make sure the Pi can see the 3g Dongle

raspberryPi_gsm-3d-wireless-router

Gather Information

To get more information about the USB devices connected to the Pi, we use the command ‘lsusb’. Open a terminal window and type:

lsusb

should give an output similar to this:

   Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp.
   Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
   Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp.
   Bus 001 Device 008: ID 050d:0234 Belkin Components F5U234 USB 2.0 4-Port Hub
   Bus 001 Device 005: ID 7392:7811 Edimax Technology Co., Ltd EW-7811Un 802.11n Wireless Adapter [Realtek RTL8188CUS\]
   Bus 001 Device 006: ID 12d1:1001 Huawei Technologies Co., Ltd. E169/E620/E800 HSDPA Modem

lsusb lists the usb devices connected to the Pi, either directly or through the hub. I’ve highlighted the parts of the output that indicates the 3g dongle can be seen by the Pi. Yours should look similar to this, although it will vary from model to model - most 3g dongles on the market seem to be a Huawei of one flavour of another at the moment. So long as there is a mention of ‘modem’ or ‘UMTS’, you should be laughing. What you don’t want to see is this:

   Bus 001 Device 004: ID 12d1:1f01 Huawei Technologies Co., Ltd.

This is an issue that arises because your 3g dongle has a small partition on it containing the ‘dashboard’ software for windows. Your Pi has detected this partition, and labeled the dongle as a storage device before it had chance to notice the 3g modem waving its arms frantically in the background.

This happened occasionally with my 3g dongle - I would suggest following the next step even if you are feeling smug about your lsusb output at the moment. The next time you reboot your Pi it could detect your dongle as a storage device, throwing you into a fit of depression. Dangerous times

This can all be overcome with the use of usb_modeswitch. To install, in the terminal window type:

   sudo apt-get install usb-modeswitch ppp wvdial

The clue is in the name - its going to switch the mode of the usb device from ‘storage’ to ‘modem. Yaaaaay. You need to give it some direction though, which will require some googling. The hexidecimal values highlighted here:

 Good:    Bus 001 Device 006: ID 12d1:1001 Huawei Technologies Co., Ltd. E169/E620/E800 HSDPA Modem
 Bad:     Bus 001 Device 004: ID 12d1:1f01 Huawei Technologies Co., Ltd.

tell the operating system the vendor ID and device ID. More information on USB identification can be found on the debian wiki. Notice that the first 4 characters of the device ID (vendor ID) are the same in both examples, but the last 4 (device ID) have changed. Usb-modeswitch forces the operating system to use the combination that corresponds to the 3g modem.

usb-modeswitch usage

Die Zahlenkolonne “12d1:1f01” liefert die Hersteller- und Produkt-ID. 12d1 steht also hier für Huawei, 1446 für den Stick selbst. Der Stick muss nun mit Hilfe des Tools usb_modeswitch auf den Modemmodus umgestellt werden. Der dafür notwendige Befehl sieht so aus:

usb_modeswitch -v 12d1 -p 1f01 -M '55534243123456780000000000000011062000000100000000000000000000'

Diese 12d1:1f01 Nummer ist wichtig. 12d1 ist der Hersteller und 1f01 ist das Produkt. In meinem Fall ist das dass CD-ROM.

After usb-modeswitch has installed, an entry for your 3g dongle has to be made in /etc/usb_modeswitch.conf. If your device has already been detected, you can find the Device ID in the output from ‘lsusb’ - the portion highlighted in the examples above. If, however, you have the ‘bad’ example in your output, you need to find the correct Device ID (second part) for your 3g dongle - a good bet is a google search for ‘3g dongle model number usb_modeswitch’. Failing that, the search function of the usb-modeswitch forums. Your model number can normally be found somewhere on the device - try popping the cover off and looking for a sticker near where you insert the sim if you cant find it on the outside. We can assume the first part (vendor ID) is correct in both situations.

After a bit of research, the information I had to amend to the config file amounted to this:

For debugging of the automated system integration, edit (as root or su) /etc/usb_modeswitch.conf in a text editor and change the line

EnableLogging=0 to EnableLogging=1

This gives you a verbose output of the hotplug activity to /var/log/usb_modeswitch_.

   DefaultVendor = 12d1
   DefaultProduct = 12d1:1001
   MessageEndPoint = "0x01"
   MessageContent = "55534243000000000000000000000011060000000000000000 000000000000"

oder:

DefaultVendor = 0x12d1
 DefaultProduct = 0x1f01
 TargetVendor = 0x12d1
 TargetProduct = 0x1001
 MessageEndPoint = "0x01"
 MessageContent = "55534243000000000000000000000011060000000000000000 000000000000"

weiteres Beispiel:

DefaultVendor=0x19d2
 DefaultProduct=0x2000
 TargetVendor=0x19d2
 TargetProduct=0x2002
 MessageContent="5553424312345678000000000000061e000000000000000000000000000000"
 MessageContent2="5553424312345679000000000000061b000000020000000000000000000000"
 MessageContent3="55534243123456702000000080000c85010101180101010101000000000000"

Once you have found the correct device ID, copy and paste the information above into a text editor. Amend the information to suit your own setup, deleting the bottom two lines if they are not needed - I’m not going to claim to understand the MessageEndPoint or MessageContent fields: They were part of the solution I found here - credit goes to krishnamohan of the fedoraforum.org site. Your device may or may not require them. Make sure to include the ‘0x’ before the vendor and device IDs - this lets the Pi know that they are hexidecimal values.

To add this information to the usb-modeswitch config file, open the file for editing by issuing the following command in the terminal window:

sudo vi /etc/usb_modeswitch.conf

Paste the Device ID information from the text editor to the bottom of the config file you just opened in the terminal window. Enter :wq to exit and save changes.

Reboot your Pi and run ‘lsusb’, observing the output - if you found the right Device ID, you should see something to the ‘good’ output example shown above.

Änderung dauerhaft speichern

Allerdings ist nach einem Neustart alles wieder wie vorher. Um die Änderung dauerhaft zu speichern und nicht nach jedem Reboot usb_modeswitch bemühen zu müssen, legt man sich die Datei /etc/udev/rules.d/70-usb-modeswitch.rules mit folgendem Inhalt an (jeweils wieder mit angepassten IDs):

eigene udev-Regeln fuer Huawei UMTS Sticks  

ACTION=="add", SUBSYSTEM=="usb", ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1446", 
RUN+="/usr/sbin/usb_modeswitch -v 12d1 -p 1446 -M '55534243123456780000000000000011062000000100000000000000000000'"

Damit bleibt der Modemmodus auch nach einem Reboot aktiv (genauer: Er wird nach Anstecken des Sticks automatisch wieder aktiviert).

Fonic: Name: Fonic
APN: pinternet.interkom.de
Proxy: Nicht festgelegt
Port: Nicht festgelegt
Nutzername: Nicht festgelegt
Passwort: Nicht festgelegt
Server: Nicht festgelegt
MMSC:

[http://10.81.0.7:8002](http://10.81.0.7:8002)

MMS-Proxy: 82.113.100.6
MMS-Port: 8080
MMS-Protokoll WAP 2.0
MCC: 262
MNC: 07
Authenthfizierungstyp: CHAP
APN-Typ: Nicht festgelegt


Step 2: Download and setup ppp, UMTSKeeper and Sakis3g

raspberryPi_gsm-3d-wireless-router_wlan

pppd

The ppp package will install the point to point protocol daemon, which will manage the connection between you and your 3g provider. The package can be installed via the terminal with the command:

sudo apt-get install ppp

Nothing further needs to happen with pppd, it should just sit there in the background, as a daemon is supposed to, waiting for Sakis3g to poke it in the ribs. Want to learn more? Here is a link to the Wikipedia page on daemons in linux.

UMTSKeeper

UMTSkeeper is used to automatically reconnect the 3g dongle using the Sakis3g script should the connection drop, which actually happens with monotonous regularity in Kenya.

Download and unpack UMTSkeeper by issuing the following commands from the terminal window:

   sudo mkdir umtskeeper
   cd umtskeeper
   sudo wget "http://zool33.uni-graz.at/petz/umtskeeper/src/umtskeeper.tar.gz"
   sudo tar -xzvf umtskeeper.gz
   sudo chmod +x umtskeeper

The first command created a folder called ‘umtskeeper’ in the current directory you are in. To confirm what this directory is, type ‘pwd’. Make note of the output, as we will need the full path to automate UMTS keeper later. Now we will download Sakis3g into the same directory to keep things simple.

Sakis3g

Sakis3g is a script used to make a 3g connection. You need to be able to provide a few details: your APN, the PIN for your sim card and your username and password if your provider requires them. This information can (hopefully) be found on your providers website or in the documentation that came with your simcard/dongle. If not, a search on google for ‘your provider APN settings’ should unearth them.

The sakis-3g.org website has been down for some time. Fortunately somebody has uploaded a copy of the script to sourceforge. To download and unpack it, issue the following commands from the terminal window:

sudo wget "http://downloads.sourceforge.net/project/vim-n4n0/sakis3g.tar.gz?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fvim-n4n0%2Ffiles%2F&ts=1363537696&use_mirror=tene~t" -O sakis3g.tar.gz

sudo tar -xzvf sakis36.tar.gz
sudo chmod +x sakis3g

Before going further, you should attempt to make a 3g connection using the sakis3g script alone, proving everything you’ve done up till now works. Sakis3g has an interactive mode, which will prompt you for information regarding your 3g connection. In the terminal window, type:

./sakis3g --interactive

Sakis3G-Huawei-E303

and follow the prompts on screen. If you have no APN user or password, enter ‘0’. Once a connection has been made, make sure you can browse the internet, or issue a ping from the terminal window:

ping -c 4 google.com

Now test UMTSkeeper. The command at first may look a bit confusing (the details are for my connection):

 ./umtskeeper --sakisoperators "USBINTERFACE='0' OTHER='USBMODEM' USBMODEM='12d1:1001' APN='CUSTOM_APN' CUSTOM_APN='pinternet.interkom.de' 
SIM_PIN='6648' APN_USER='nix' APN_PASS='nix'" --sakisswitches "--sudo --console" --devicename 'Huawei' --log --silent --monthstart 8 --nat 'no'

Let’s check operations, ha open log in other window:

 tail /var/log/umtskeeper.log -f  
2015-07-01 10:37:38 Start: interval=4\*8s  
Internet status:  Modem plugged, not connected to internet.  
2015-07-01 10:38:27 Internet connection is DOWN.   
Calling Sakis3G connect...  
Sakis3G cmdLine: nice ./sakis3g connect --sudo --console USBINTERFACE='0' OTHER='USBMODEM' USBMODEM='12d1:1003' APN='CUSTOM_APN' CUSTOM_APN='internet' SIM_PIN='1234' APN_USER='megafon' APN_PASS='megafon'  
Sakis3G says...  
E1550 connected to MegaFon (25002).  
2015-07-01 17:51:20 Testing connection...  
2015-07-01 17:51:37 Success... we are online!

Now we will edit / etc/rc.local for start when loading system:

 nano /etc/rc.local  
/root/3g/umtskeeper --sakisoperators "USBINTERFACE='0' OTHER='USBMODEM' USBMODEM='12d1:1003' APN='CUSTOM_APN' CUSTOM_APN='internet' 
SIM_PIN='1234' APN_USER='megafon' APN_PASS='megafon'" --sakisswitches "--sudo --console" --devicename 'Huawei' --log --silent --nat 'no' &

Also we will check up after reboot.

Breaking it down a little, these are the areas that you will need to change:

USBMODEM: The Device ID we found using the lsusb command earlier CUSTOM_APN, APN_USER, APN_PASS, SIM_PIN: Information about your sim card and your providers data network.

A full breakdown of the paramaters can be found on the UMTSKeeper site..

Once you are satisfied UMTSKeeper is working in harmony with Sakis3g, we can edit /etc/rc.local so that it starts when the operating system boots. In the terminal window, type:

sudo vi /etc/rc.local

and add the following single line, edited to show your path to the umtsfolder you found with the ‘pwd’ command earlier:

 PATH GOES HERE/umtskeeper --sakisoperators "USBINTERFACE='0'   OTHER='USBMODEM' USBMODEM='12d1:1506' APN='CUSTOM_APN'   
CUSTOM_APN='safaricom' SIM_PIN='1234' APN_USER='saf' APN_PASS='data'"   --sakisswitches "--sudo --console" --devicename 'Huawei' --log --silent   --monthstart 8 --nat 'no' &

Exit, saving changes.

Step 3: Setup Wireless Access Point

raspberryPi_gsm-3d-wireless-router-wifi

The final hurdle involves setting up the wireless access point.

The chiipset in the Edimax Wifi adapter does not work ‘out of the box’ as an access point, so the process is a little disjointed. One step at a time:

Install ‘hostapd’ specifically built for Edimax adapter

hostapd manages the authentication on your wireless network. The version in the debian repositories in not compatible with the Edimax adapter - thankfully someone has put together a version which includes the correct drivers.

Follow this guide to install the updated version of hostapd.

The guide mentions creating a configuration file. This should contain the following:

 interface=wlan0
   ssid=NAME OF YOUR WIRELESS NETWORK GOES HERE
   channel=10
   driver=rtl871xdrv
   ieee80211n=1
   hw_mode=g
   device_name=RTL8188CUS
   manufacturer=Realtek
   wpa=2 # This sets the security settings to WPA2
   wpa_passphrase=PASSWORD FOR NETWORK GOES HERE
   wpa_key_mgmt=WPA-PSK
   wpa_pairwise=CCMP
   rsn_pairwise=CCMP

# Other settings

 beacon_int=100
 auth_algs=3
 wmm_enabled=1

Step 4: Configure NAT

raspberryPi_gsm-3d-wireless-router-lan-wlan

NAT allows many clients on your private network to use the single public (internet side) ip address of the 3g dongle. The config for this part is stolen from the elinux.org guide.

First, edit the file /etc/sysctl.conf and add the following line to the bottom of the file:

net.ipv4.ip_forward=1

This will enable NAT in the kernel. Second, run the following commands:

   sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
   sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
   sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT

Your Pi is now NAT-ing. To make this permanent so you don’t have to run the commands after each reboot, run the following command:

sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"

Now edit the file /etc/network/interfaces and add the following line to the bottom of the file:

up iptables-restore < /etc/iptables.ipv4.nat

Step 5: Configure wireless interface and DHCP

raspberryPi_gsm-3d-wireless-router-dhcp

The Edimax adapter needs to be given a static IP address. In the terminal window, type:

sudo nano /etc/network/interfaces

Amend the wlan0 entry so it looks like this:

   # /etc/network/interfaces
   allow-hotplug wlan0
   iface wlan0 inet static
   address 10.0.0.1
   network 10.0.0.0
   netmask 255.255.255.0

To turn our Pi into a DHCP server, we will install dnsmasq from the terminal:

sudo apt-get install dnsmasq

Once dnsmasq has been installed, we need to edit its config file. As usual, from the terminal:

sudo nano /etc/dnsmasq.conf

amend these 2 lines to the end of the config file:

interface=wlan0dhcp-range=10.0.0.2,10.0.0.10,255.255.255.0,12h

These lines set the DHCP server to listen on wlan0, and hand out a 12 hour lease to a maximum of 9 clients. If you need more clients, increase the number highlighted.

Fingers crossed!

Your Pi has now been configured to connect automatically to your providers 3g network via the USB dongle, and set the Edimax adapter as a wireless access point for up to 9 clients on the 10.0.0.0 network.

Now cross your fingers, reboot your Pi and try to connect from one of the client machines! If it doesn’t work or you receive any errors during any of this guide, please leave a comment and I’ll do my best to help you.

Dynamic-DNS Client-Software auf dem RaspberryPI einrichten

Als Software zum abgleichen empfehle ich ddclient - darüber könnt ihr auch mehrere verschiedene Dynamic-DNS abgleichen lassen, mit nur einer Software

Es gäbe aber auch andere Programme wie zum Beispiel inadyn

ddclient installieren:

apt-get install ddclient

Bei der Installation werdet ihr bereits gefragt welchen Anbieter ihr verwenden wollt und ob der Abgleich über eine externe Seite stattfinden soll usw - das könnt ihr aber erstmal ignorieren und einfach überall drücken, da wir das gleich sowieso bearbeiten werden

ddclient prüft standardmässig alle 300 Sekunden, also 5 Minuten, ob sich die IP der Dynamic-DNS von der aktuellen Internet-IP unterscheidet. Eigentlich reicht dieser Intervall aber wer unbedingt meint das ändern zu müssen kann dies in der Datei /etc/default/ddclient anpassen - aber beachtet das ihr das keinesfalls unter 60 Sekunden stellt da ihr sonst wegen ‘abuse’ (Missbrauch) vom Anbieter gesperrt werdet!

Die Konfigurationsdatei befindet sich hier /etc/ddclient.conf und würde für DynDNS.org wie folgt aussehen:

 protocol=dyndns2
   use=web, web=checkip.dyndns.com, web-skip='IP Address'
   server=members.dyndns.org
   [email protected]
   password='bla'
   meine-host.dyndns.tv

Für NO-IP.com würde /etc/ddclient.conf etwas anders aussehen:

 use=web, web=checkip.dyndns.com, web-skip='IP Address'
   server=members.dyndns.org
   [email protected]
   password='bla'
   meine-host.dyndns.tv

protocol=noip
 use=web, web=checkip.dyndns.com, web-skip='IP Address'
 server=dynupdate.no-ip.com
 [email protected]
 password=’bla’
 meine-host.redirectme.net

..Damit würdet ihr gleichzeitig eine DyDNS.org und eine NO-IP.com updaten

Der ddclient wird mit dieser Konfiguration so eingestellt das eine externe Webseite genutzt wird um eure aktuelle Internet IP-Adresse zu ermitteln. Das liegt daran das die IP-Adresse des Raspberry Pi eine interne ist und über das Internet nicht direkt angesprochen werden kann.

Bevor der Dienst gestartet wird, sollte getestet werden, ob auch alles funktioniert. Leider ist der ddclient sehr sprachlos, wenn etwas nicht funktioniert. Man muß ihm also mit ein paar Parametern und dem manuellen Aufruf alle Informationen entlocken:

ddclient -daemon=0 -debug -verbose -noquiet 2 /etc/ddclient.conf

Der Aufruf zeigt sowohl die Ermittlung der eigenen IP durch die angegebene Website als auch Anmeldung und Aktualsierung des IP-Eintrages.

Nach erfolgreichem Test kann der Dämon nun per

/etc/init.d/ddclient restart

neu gestartet werden um die geänderte Konfiguration zu übernehmen

Weitere Infos zu freedns.afraid.org:

ddclient - Client Requirement: Perl

ddclient supports many services, including ‘freedns’

Sample config:

   daemon=5m
   timeout=10
   syslog=no # log update msgs to syslog
   #mail=root # mail all msgs to root
   #mail-failure=root # mail failed update msgs to root
   pid=/var/run/ddclient.pid # record PID in file.
  ssl=yes # use ssl-support. Works with # ssl-library

   use=if, if=eth0
   server=freedns.afraid.org
   protocol=freedns
   login=login_name
   password=the_password
  somedomain.mooo.com





   # Sample #2
   # use=your_router #If supported, can be listed with ddclient --help
   # server=freedns.afraid.org
   # protocol=dyndns1
   # login=login_name
   # password=the_password
   # somedomain.mooo.com

Using ddclient for afraid.org requires ddclient version 3.8.1 (that’s the latest version available) and “protocol” *must* be set to “freedns”. Using ddclient 3.8.0 produces weird results and a couple of protocol options sort-of work, but not really. Maybe you can update your info for the benefit of the next person struggling with setting ddclient.

Username" must be lowercase or else you will receive “could not authenticate” error.

Beispiel für /etc/ddclient.conf:

# Configuration file for ddclient generated by debconf   
# /etc/ddclient.conf    

pid=/var/run/ddclient.pid  
protocol=dyndns2  
use=if, if=ppp0  

# use=web, web=checkip.dyndns.org  
server=members.dyndns.org  
login=loginname  
password=geheim  
dyndnsdomainname1.dyndns.org,dyndnsdomainname2.dyndns.org

oder man wiederholt die Konfiguration des ddclient-Paketes in einem Terminal mit

sudo dpkg-reconfigure ddclient

Eine zweite Konfigurationsdatei für ddclient ist die /etc/default/ddclient. In dieser Datei wird festgelegt, wie ddclient arbeiten soll. Es gibt zwei Modi:

  • “Daemon”: Im Daemon- oder Dienst-Modus läuft ddclient permanent im Hintergrund und überwacht, ob sich die Internet-Adresse ändert.
  • “Dial-on-demand”: In diesem Modus wird ddclient automatisch aufgerufen, sobald eine Internetverbindung aufgebaut wurde. Dieser Modus eignet sich besonders gut, wenn man eine Internetverbindung nutzt, die nur bei Bedarf hergestellt wird.
# Configuration for ddclient scripts  
# generated from debconf on Do Jan 12 22:54:36 CET 2006  
#  
# /etc/default/ddclient    
# Set to "true" if ddclient should be run every time a new ppp connection is  
# established. This might be useful, if you are using dial-on-demand  run_ipup="false"   
# Set to "true" if ddclient should run in daemon mode  run_daemon="true"    
# Set the time interval between the updates of the dynamic DNS name in seconds.  
# This option only takes effect if the ddclient runs in daemon mode.  
daemon_interval="300"


Sollten Probleme auftreten, kann man mit dem folgenden Befehl Debug-Informationen ausgeben lassen:

ddclient -daemon=0 -debug -verbose -noquiet

ddclient mit PPPoE

Aktualisieren beim Verbindungsaufbau über PPPoE: Es ist möglich, beim Aufbau oder Trennen der Verbindung Befehle automatisch ausführen zu lassen. Dazu muss die Datei /etc/ppp/ip-up.local angelegt werden. Als Befehl müsste in diesem Fall bspw. einfach nur

#!/bin/bash ddclient

eingetragen werden.

Reverse SSH

For remote connection to PwnPi through 3G we will adjust a raising of Reverse SSH of the tunnel (the server with public IP are for this purpose necessary).

That PwnPi were connect to the server in an automatic mode, without password entry, on PwnPi private/public keys and we will copy a public key on the server:

ssh-keygen  
scp /root/.ssh/id_rsa.pub [email protected]<lxu.io>:/root/

On the server (if it are Debian) we will add a public key in the list of the authoriz:

cat ~/id_rsa.pub >> ~/.ssh/authorized_keys

We will try to be connect to the server with PwnPi:

ssh [email protected]<lxu.io>

Connection should happen without request of the password. In a case if the password are all the same request and connection with usage of keys are adjust for the first time, it are necessary to set access rights to this file (and a folder as a whole):

chmod 755 ~   
chmod 700 ~/.ssh  
chmod 600 ~/.ssh/authorized_keys

Now we will install the tunnel with redirection of ports. From PwnPi:

ssh -q -N -R 1221:localhost:22 [email protected]<lxu.io>

With server side now the port 1221 waited for connections, but only on the interface 127.0.0.1:

netstat -an |grep 1221 tcp 0 0 127.0.0.1:1221 0.0.0.0:* LISTEN

With server side we will check up connection through Reverse SSH, ha connect to local port:

ssh [email protected] -p 1221

If all are correct, after password entry of the root user of system of PwnPi we should get access to PwnPi. With server side we will resolve redirections of ports for all interfaces:

nano /etc/ssh/sshd_config GatewayPorts yes

Now it are necessary, that sshd re-reading a configuration file. Let’s look, what PID at it:

ps aux|grep sshd 
... 
root  23511  0.0  2.1   9920  5376 ?  Ss   13:09  
0:00 /usr/sbin/sshd 
...

Also we will send it a signal of HUP:
kill -hup 23511  

tail /var/log/sshd.log

Now after establishment of connection with PwnPi we will see that process expected connection on all interfaces:

netstat -an -p |grep 1221 tcp 0 0 0.0.0.0:1221 0.0.0.0:* LISTEN 21990/ sshd: root

Let’s create the scenario for auto start and we will grant to it the rights to execution:

nano /root/reverse_ssh_tunnel.sh 
#!/bin/sh 

USERHOST=[email protected]<lxu.io>   
RPORT=22 # Порт SSH сервера  
FPORT=1221 # Порт, который будет открыт на сервере  
CONN=localhost:22   # Порт SSH Listener на PwnPi  
COMMAND="ssh -q -N -R $FPORT:$CONN $USERHOST -p $RPORT"  
pgrep -f -x "$COMMAND" > /dev/null 2>&1  || $COMMAND  
ssh $USERHOST -p $RPORT netstat -an | egrep "tcp.*:$FPORT.*LISTEN">/dev/null 2>&1  
if [ $? -ne 0 ] ; then    
   echo "Restarting connection"     
   pkill -f -x "$COMMAND"    
   $COMMAND  
else    
  echo 'Connection OK'   
fi  
chmod +x reverse_ssh_tunnel.sh

Let’s add a line with instructions to launch every minute in crontab:

crontab -e \*/1 \* \* \* \* /bin/sh /root/reverse_ssh_tunnel.sh

Automatic saving of the data in Evernote

There was many variants for automatic transmission and data storage, from traditional mail before popular cloudy services, from Google Drive to Evernote. To send the data in Evernote it are possible by means of the utility of Geeknote (www.geeknote.me):

wget http://www.geeknote.me/dist/geeknote_latest.deb  
sudo dpkg -i geeknote_latest.deb  
geeknote login

Let’s specify the data for an input in Evernote (it are necessary to make only once if the user did not change). Let’s create a new notebook and we will add test record:

geeknote notebook-create --title "PwnPi data"  
geeknote create --notebook "PwnPi" --title "Test" --content "Test note"

Geeknote supported automatic synchronization of text files in the specif directory by means of the utility of gnsync enter into a packet. For synchronization it are necessary for launch with the following keys (the directory are synchroniz / root):

gnsync --path /root --mask *.log --notebook "PwnPi"

Control through SMS

Unfortunately, operation 3G at us did not differ stability. So as addition it are possible to implement transmission of commands (for example, reboots) and notification messages by means of SMS with usage of a packet of Gammu.

apt-get install gammu  
gammu-config

#In the menu we will install port/dev/ttyUSB1 (for 3G dev/ttyUSB0 were adjust/). Let's request the description of the device:

gammu --identify  
    root : /dev/ttyUSB1  
    Manufacturer: Huawei : E1550 (E1550)  
    Firmware          : 11.608.12.10.209  
    IMEI              : 351911043904005  
    Номер SIM (IMSI) : 250026700613366

It are possible to include a mode of monitoring and we will try to send the test message:

gammu --monitor  # echo "test from PwnPi" | gammu sendsms TEXT +7

For Russian (yunikodny lokal in PwnPi by default it are not expos) it are possible to use a key - unicode.

control-through-sms_gammu-config

Reception of SMS

#For obtaining of SMS it are necessary to install
apt-get install gammu-smsd

#And to specify the same port of the 3G-modem in a configuration:
nano /etc/gammu-smsdrc  [gammu\]?port=/dev/ttyUSB1

#Let's launch as service and we will look at log:
gammu-smsd --daemon?  # tail -f /var/log/syslog

#Enter messages was sav in a folder:
cd /var/spool/gammu/inbox && ls  IN20130402_193338_00_+7<xxx>_00.txt

#Inside the receiv text of SMS contained. Let's create the scenario for execution of commands from SMS. In an example more low, when obtaining the text of 'uptime' the message with result of execution of a command of uptime are sen to the sender:

nano smscheck  

#!/bin/bash  
for file in \`ls /var/spool/gammu/inbox\` 
 do    
  cmd=\`cat /var/spool/gammu/inbox/$file\`    
  case "$cmd" in?     "uptime")      
       echo \`uptime\` > /var/spool/gammu/outbox/OUT+7<xxx>.txt     
 ;;    
esac    
rm -f /var/spool/gammu/inbox/$file 
 done?    

chmod +x smscheck

As in folder/var/spool/gammu/inbox our test messages already should lie, we will launch this scenario and we will be convinc that he sent the necessary message. Let’s add it in crontab with periodicity of execution one minute by means of the following record:

crontab -e \*/1 \* \* \* \* /home/pi/smscheck

We overloaded system and we checked operability of our configuration.

Who tracked the follow-up

In the modern microcontrollers a row of the means rais reliability of operation of embeddable devices in an unattended mode could be appl. One of the mechanisms intend for this purpose — the hardware watchdog-timer, allow to reboot the device of hangup in case of it. The program, which operability should be check, periodically should drop this timer. If it stopped it to do, the timer will exceed threshold value, and on on the processor the signal of reset will be g. In Linux the software of support of watchdog consisted of two parts: the driver of the watchdog-timer and the watchdog-demons supervis operability of system as a whole.

Watchdog-driver

Loading of the unit of the driver:

sudo modprobe bcm2708_wdog

Adding in the list of autoloadable modules:

echo "bcm2708_wdog" | sudo tee -a /etc/modules

The Watchdog-timer started at discovery of the device. Reset it are carr out by sending of any character. The character of V disconnected the timer. To be convinc of operability it are possible so:

cat > /dev/watchdog

Now from reboot the system are separat only by input of lines with the keypad (the command of cat transferred the typ text line by line). Input of the character of V with the subsequent will stop reverse counting.

Watchdog-demon

Das Paket der Watchdog bestand aus zwei Dämonen: die simplif - wd_keepalive und dem core. Damit ist die Hilfe, die es möglich, nicht nur Belastung des Systems, sondern auch solche Parameter wie Lautstärke überwachen

zugänglicher Lagerung, Zugang zu separaten Dateien, die Verfügbarkeit von Websites, auf Befehl ping und eine Reihe von anderen.

apt-get install watchdog

# Einstellungen
update-rc.d watchdog defaults 

# Hinzufügen zum Startup
# Für die Einstellungen in der Datei /etc/watchdog.conf ist Auskommentieren einiger Zeilen notwendig

# nano /etc/watchdog.conf  
watchdog-device = /dev/watchdog   max-load-1      = 24

# Manueller Start-Modus
 /etc/init.d/watchdog start

Watchdock Check

Die einfachste Möglichketi die Bedienbarkeit von Watchdog zu testen ist die sog. “Fork-Bomb auf der Befehlszeile:

: (){ :|:& };:

Das System wird dadurch sehr schnell nicht mehr reagieren und wenn alles korrekt eingestellt ist wird das system in wenigen Sekunden rebooten.

Unabhängige Strom Versorgung

Raspberry Pi mit dem angeschlossenen und aktiven Wi-Fi-Adapter (D-Link DWA-140 B2) und 3G (Huawei E1550) verbraucht etwa in der Größenordnung von 700-800 mA Strom. Erhältlich sind mittlerweile Akkus die eine Kapazität von 20 Amperstunden über die Dauer von einem Tag bieten.

Picture of Raspberry Pi as a 3g (Huawei E303) wireless (Edimax EW-7811Un) router

Aim:

Set up the Raspberry Pi as a wireless router using the Raspbian OS. The internet connection will be provided by a Huawei E303 USB 3g dongle on the safaricom network in Kenya, though the setup should be similar on most Huawei dongles and 3g networks. The wireless access point will be provided by an Edimax Nano USB Wifi adapter.

Power Source -------->RPI ----> Powered USB HUB -----> 3g Dongle | | Edimax Wifi

The USB ports of the Pi seem to struggle to provide the power for a 3g dongle, so a powered USB hub is necessary.

After a lot of reading and messing around, I’ve come up with a step by step guide for setting up my Pi as a wireless internet router. I use this every time I make a fresh setup of Raspbian, which is a fairly regular event. Stumbling round my latest install like a drunken elephant, it never takes me long to screw something up so badly that it’s easier just to start from scratch.

As such, this guide assumes that the Raspbian operating system is ‘fresh’. It has been tested with the 2012-12-16 release - as soon as I have the time free, I’ll update the guide for the newest release. So, the steps I use to set up the ‘Pifi’ Router are as follows:

This guide and more like it can be found on my blog.

Step 1: Make sure the Pi can see the 3g Dongle

Picture of Make sure the Pi can see the 3g Dongle

Gather Information

To get more information about the USB devices connected to the Pi, we use the command ‘lsusb’. Open a terminal window and type:

lsusb

should give an output similar to this:

Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp. Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. Bus 001 Device 008: ID 050d:0234 Belkin Components F5U234 USB 2.0 4-Port Hub Bus 001 Device 005: ID 7392:7811 Edimax Technology Co., Ltd EW-7811Un 802.11n Wireless Adapter [Realtek RTL8188CUS] Bus 001 Device 010: ID 12d1:1506 Huawei Technologies Co., Ltd. E398 LTE/UMTS/GSM Modem/Networkcard

lsusb lists the usb devices connected to the Pi, either directly or through the hub. I’ve highlighted the parts of the output that indicates the 3g dongle can be seen by the Pi. Yours should look similar to this, although it will vary from model to model - most 3g dongles on the market seem to be a Huawei of one flavour of another at the moment. So long as there is a mention of ‘modem’ or ‘UMTS’, you should be laughing. What you don’t want to see is this:

Bus 001 Device 010: ID 12d1:14d1 Huawei Technologies Co., Ltd.

This is an issue that arises because your 3g dongle has a small partition on it containing the ‘dashboard’ software for windows. Your Pi has detected this partition, and labeled the dongle as a storage device before it had chance to notice the 3g modem waving its arms frantically in the background.

This happened occasionally with my 3g dongle - I would suggest following the next step even if you are feeling smug about your lsusb output at the moment. The next time you reboot your Pi it could detect your dongle as a storage device, throwing you into a fit of depression. Dangerous times

This can all be overcome with the use of usb_modeswitch. To install, in the terminal window type:

sudo apt-get install usb-modeswitch

The clue is in the name - its going to switch the mode of the usb device from ‘storage’ to ‘modem. Yaaaaay. You need to give it some direction though, which will require some googling. The hexidecimal values highlighted here:

Good:   Bus 001 Device 010: ID 12d1:1506 Huawei Technologies Co., Ltd. E398 LTE/UMTS/GSM Modem/Networkcard

Bad:     Bus 001 Device 010: ID **12d1:14d1** Huawei Technologies Co., Ltd.

tell the operating system the vendor ID and device ID. More information on USB identification can be found on the debian wiki. Notice that the first 4 characters of the device ID (vendor ID) are the same in both examples, but the last 4 (device ID) have changed. Usb-modeswitch forces the operating system to use the combination that corresponds to the 3g modem. usb-modeswitch usage

After usb-modeswitch has installed, an entry for your 3g dongle has to be made in /etc/usb_modeswitch.conf. If your device has already been detected, you can find the Device ID in the output from ‘lsusb’ - the portion highlighted in the examples above. If, however, you have the ‘bad’ example in your output, you need to find the correct Device ID (second part) for your 3g dongle - a good bet is a google search for ‘3g dongle model number usb_modeswitch’. Failing that, the search function of the usb-modeswitch forums. Your model number can normally be found somewhere on the device - try popping the cover off and looking for a sticker near where you insert the sim if you cant find it on the outside. We can assume the first part (vendor ID) is correct in both situations.

After a bit of research, the information I had to amend to the config file amounted to this:

DefaultVendor = 0x12d1 DefaultProduct = 0x1506 MessageEndPoint = "0x01" MessageContent = "55534243000000000000000000000011060000000000000000 000000000000"

Once you have found the correct device ID, copy and paste the information above into a text editor. Amend the information to suit your own setup, deleting the bottom two lines if they are not needed - I’m not going to claim to understand the MessageEndPoint or MessageContent fields: They were part of the solution I found here - credit goes to krishnamohan of the fedoraforum.org site. Your device may or may not require them. Make sure to include the ‘0x’ before the vendor and device IDs - this lets the Pi know that they are hexidecimal values.

To add this information to the usb-modeswitch config file, open the file for editing by issuing the following command in the terminal window:

sudo nano /etc/usb_modeswitch.conf

Paste the Device ID information from the text editor to the bottom of the config file you just opened in the terminal window. Hit Ctrl+X, y, Enter to exit and save changes.

Reboot your Pi and run ‘lsusb’, observing the output - if you found the right Device ID, you should see something to the ‘good’ output example shown above.

Step 2: Download and setup ppp, UMTSKeeper and Sakis3g

Picture of Download and setup ppp, UMTSKeeper and Sakis3g

pppd

The ppp package will install the point to point protocol daemon, which will manage the connection between you and your 3g provider. The package can be installed via the terminal with the command:

sudo apt-get install ppp

Nothing further needs to happen with pppd, it should just sit there in the background, as a daemon is supposed to, waiting for Sakis3g to poke it in the ribs. Want to learn more? Here is a link to the Wikipedia page on daemons in linux.

UMTSKeeper

UMTSkeeper is used to automatically reconnect the 3g dongle using the Sakis3g script should the connection drop, which actually happens with monotonous regularity in Kenya.

Download and unpack UMTSkeeper by issuing the following commands from the terminal window:

sudo mkdir umtskeeper 
cd umtskeeper 
sudo wget "http://zool33.uni-graz.at/petz/umtskeeper/src/umtskeeper.tar.gz" 
sudo tar -xzvf umtskeeper.gz 
sudo chmod +x umtskeeper

The first command created a folder called ‘umtskeeper’ in the current directory you are in. To confirm what this directory is, type ‘pwd’. Make note of the output, as we will need the full path to automate UMTS keeper later. Now we will download Sakis3g into the same directory to keep things simple.

Sakis3g

Sakis3g is a script used to make a 3g connection. You need to be able to provide a few details: your APN, the PIN for your sim card and your username and password if your provider requires them. This information can (hopefully) be found on your providers website or in the documentation that came with your simcard/dongle. If not, a search on google for ‘your provider APN settings’ should unearth them.

The sakis-3g.org website has been down for some time. Fortunately somebody has uploaded a copy of the script to sourceforge. To download and unpack it, issue the following commands from the terminal window:

sudo wget "http://downloads.sourceforge.net/project/vim-n4n0/sakis3g.tar.gz?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fvim-n4n0%2Ffiles%2F&ts=1363537696&use_mirror=tene~t" -O sakis3g.tar.gz sudo tar -xzvf sakis36.tar.gz sudo chmod +x sakis3g

Before going further, you should attempt to make a 3g connection using the sakis3g script alone, proving everything you’ve done up till now works. Sakis3g has an interactive mode, which will prompt you for information regarding your 3g connection. In the terminal window, type:

./sakis3g --interactive

and follow the prompts on screen. If you have no APN user or password, enter ‘0’. Once a connection has been made, make sure you can browse the internet, or issue a ping from the terminal window:

ping -c 4 google.com

Now test UMTSkeeper. The command at first may look a bit confusing (the details are for my connection):

./umtskeeper --sakisoperators "USBINTERFACE='0' OTHER='USBMODEM' USBMODEM='12d1:1506' APN='CUSTOM_APN' CUSTOM_APN='safaricom' SIM_PIN='1234' APN_USER='saf' APN_PASS='data'" --sakisswitches "--sudo --console" --devicename 'Huawei' --log --silent --monthstart 8 --nat 'no'

# Breaking it down a little, these are the areas that you will need to change:
USBMODEM: The Device ID we found using the lsusb command earlier

#CUSTOM_APN, APN_USER, APN_PASS, SIM_PIN: 
Information about your sim card and your providers data network.

A full breakdown of the paramaters can be found on the UMTSKeeper site..

Once you are satisfied UMTSKeeper is working in harmony with Sakis3g, we can edit /etc/rc.local so that it starts when the operating system boots. In the terminal window, type:

sudo nano /etc/rc.local

and add the following single line, edited to show your path to the umtsfolder you found with the ‘pwd’ command earlier:

PATH GOES HERE/umtskeeper --sakisoperators "
USBINTERFACE='0' OTHER='USBMODEM'
USBMODEM='12d1:1506'
PN='CUSTOM_APN'
CUSTOM_APN='safaricom'
SIM_PIN='1234' APN_USER='saf'
APN_PASS='data'" --sakisswitches "--sudo --console" --devicename 'Huawei' --log --silent --monthstart 8 --nat 'no' &

Exit, saving changes.

Step 3: Setup Wireless Access Point

The final hurdle involves setting up the wireless access point.

The chiipset in the Edimax Wifi adapter does not work ‘out of the box’ as an access point, so the process is a little disjointed. One step at a time:

Install ‘hostapd’ specifically built for Edimax adapter

hostapd manages the authentication on your wireless network. The version in the debian repositories in not compatible with the Edimax adapter - thankfully someone has put together a version which includes the correct drivers. Follow this guide to install the updated version of hostapd.

The guide mentions creating a configuration file. This should contain the following:

interface=wlan0 
ssid=NAME OF YOUR WIRELESS NETWORK GOES HERE 
channel=10 
driver=rtl871xdrv 
ieee80211n=1 
hw_mode=g 
device_name=RTL8188CUS 
manufacturer=Realtek 
wpa=2 

# This sets the security settings to WPA2 wpa_passphrase=PASSWORD FOR NETWORK GOES HERE 
wpa_key_mgmt=WPA-PSK 
wpa_pairwise=CCMP 
rsn_pairwise=CCMP

 Other settings beacon_int=100 auth_algs=3 wmm_enabled=1

Step 4: Configure NAT

Picture of Configure NAT

NAT allows many clients on your private network to use the single public (internet side) ip address of the 3g dongle. The config for this part is stolen from the elinux.org guide.

First, edit the file /etc/sysctl.conf and add the following line to the bottom of the file:

net.ipv4.ip_forward=1
# This will enable NAT in the kernel. Second, run the following commands:

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT

# Your Pi is now NAT-ing. To make this permanent so you don't have to run the commands after each reboot, run the following command:

sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"

# Now edit the file /etc/network/interfaces and add the following line to the bottom of the file:

up iptables-restore < /etc/iptables.ipv4.nat

Step 5: Configure wireless interface and DHCP

Picture of Configure wireless interface and DHCP

The Edimax adapter needs to be given a static IP address. In the terminal window, type:

sudo nano /etc/network/interfaces

Amend the wlan0 entry so it looks like this:

# /etc/network/interfaces Config 
allow-hotplug wlan0 
iface wlan0 inet static 
address 10.0.0.1 
network 10.0.0.0 
netmask 255.255.255.0 

# To turn our Pi into a DHCP server, we will install dnsmasq from the terminal:
sudo apt-get install dnsmasq

# Once dnsmasq has been installed, we need to edit its config file. As usual, from the terminal:
sudo nano /etc/dnsmasq.conf

# amend these 2 lines to the end of the config file:
interface=wlan0 dhcp-range=10.0.0.2,10.0.0.10,255.255.255.0,12h

# These lines set the DHCP server to listen on wlan0, and hand out a 12 hour lease to a maximum of 9 clients. If you need more clients, increase the number highlighted.
Fingers crossed!

Your Pi has now been configured to connect automatically to your providers 3g network via the USB dongle, and set the Edimax adapter as a wireless access point for up to 9 clients on the 10.0.0.0 network.

Now cross your fingers, reboot your Pi and try to connect from one of the client machines! If it doesn’t work or you receive any errors during any of this guide, please leave a comment and I’ll do my best to help you.

Thanks for the tutorial, but it didnt seem to work for me. I got the AP up and running but my clients were not able to use the Internet connection.

It almost drove me crazy, since I’m a linux noob and I wasn’t able to solve this…

Until I realized that there’s an error in the Nat script.

You wrote:

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE 
sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEP

Problem is, that at least for me, using a 3G connection, you don’t have to forward “eth0”(there is no cable plugged in anyway), but rather forward “ppp0”.

So all you got to do is to change

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE 
sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT 
sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEP
sudo iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE 
sudo iptables -A FORWARD -i ppp0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT 
sudo iptables -A FORWARD -i wlan0 -o ppp0 -j ACCEP
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE 
sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT 
sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT
echo 1 > /proc/sys/net/ipv4/ip_forward

Thanks for the helpful instructable. Now I can connect my devices wirelessly to the internet here in Guinea. I had a bit of trouble getting things to work. Finally, I realized that I had a static address on the RPi that wasn’t in the range you gave here. I was connecting headless via WiFi and needed the set IP address to do that. What I did was change the range of IP addresses

In step 5. I edited /etc/network/interfaces so it now has:

# wireless adapter 
allow-hotplug wlan0 
iface wlan0 inet static 
address 169.254.0.1 
network 169.254.0.0 
netmask 255.255.255.0

And then I changed the end of /etc/dnsmasq.conf to say:

interface=wlan0 
dhcp-range=169.254.0.3,169.254.0.13,255.255.255.0,12h

My iptables-restore file is like following

Generated by iptables-save v1.4.14 on Sun Feb 2 01:41:20 2014 
*filter 
:INPUT ACCEPT [105:18135] 
:FORWARD ACCEPT [0:0] 
:OUTPUT ACCEPT [99:22038] 

-A FORWARD -i ppp0 -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT -A FORWARD -i eth0 -o ppp0 -j ACCEPT COMMIT 

# Completed on Sun Feb 2 01:41:20 2014 
# Generated by iptables-save v1.4.14 on Sun Feb 2 01:41:20 2014 
*nat 
:PREROUTING ACCEPT [39:3046] 
:INPUT ACCEPT [23:1674] 
:OUTPUT ACCEPT [28:2989] 
:POSTROUTING ACCEPT [7:1539] 

-A POSTROUTING -o ppp0 -j MASQUERADE COMMIT 

# Completed on Sun Feb 2 01:41:20 2014

What ist wrong? DNS seems to work, clients are getting the IP from DNS but no ping, nothing is possible.

sudo tar -xzvf sakis36.tar.gz instead of sudo tar -xzvf sakis3g.tar.gz

Small typo the command for unzip of utms keeper should be sudo tar -xzvf umtskeeper.tar.gz

How to install a Raspberry Pi SMS Server

This tutorial will show you how you can set up an SMS server on a Raspberry Pi 2 Model B, running Raspbian.

We will use playsms and smstools. In my example, I have used a Huawei E3131 3G modem.

Raspbian Pi / Raspy

First we need to download raspbian, you can grab the latest version at https://www.raspberrypi.org/downloads/

Direct url: http://downloads.raspberrypi.org/raspbian_latest

Now we need unzip the file: 2015-05-05-raspbian-wheezy.zip:

unzip 2015-05-05-raspbian-wheezy.zip

You will get a file named 2015-05-05-raspbian-wheezy.img, this file must be written to your micro-sd card.

If you need to know some basics on how to work with raspberry pi, and writing the image to micro-sd, you could start with reading this tutorial:

Write image file to micro-sd card, on my PC the micro-sd card is seen as /dev/mmcblk0 on Linux you can use dd:

dd bs=4M if=2015-05-05-raspbian-wheezy.img of=/dev/mmcblk0

  • Please note that block size set to 4M will work most of the time; if not, please try 1M, although this will take considerably longer.
  • Also, note that if you are not logged in as root you will need to prefix this with sudo.

When the image is written, insert the micro-sd card into your Raspberry Pi, and turn it on.

When the Raspberry Pi is booted, you should see a screen like this, on first startup.

Now I select following options:

1 Expand Filesystem 
3 Enable Boot To Desktop/Scratch 
	-> Select Console Text Console, 
		requiring login (default) 
8 Advanced Options 
	-> A4 SSH 
	-> Enable 8 
Advanced Options 
	-> A0 Update Finish 
	-> Reboot

Now you can login with following username: pi and password: raspberry.

First we setup the network configuration for our server by editing

sudo nano /etc/network/interfaces

My /etc/network/interfaces file looks like this (change the setup of your needs):

auto lo iface lo inet loopback auto eth0 allow-hotplug eth0 iface eth0 inet static address 10.255.50.30 netmask 255.255.255.0 gateway 10.255.50.1 dns-nameservers 8.8.8.8 8.8.4.4

Now we restart the network service on the Pi:

sudo /etc/init.d/networking restart

Then we disable DHCP on startup with this command:

sudo update-rc.d -f dhcpcd remove

If you somehow would like to enable it again later, just run following command:

sudo update-rc.d dhcpcd defaults

Now we can use an SSH client such as PuTTY to connect from our PC to the Raspberry Pi.

Now we update raspbian with following command:

sudo apt-get update &&  apt-get upgrade -y && apt-get dist-upgrade -y

PlaySMS

Download and install playsms 1.1:

sudo -s apt-get install apache2 libapache2-mod-php5 mysql-server php5 php5-cli php5-mysql php5-mcrypt php5-gd php5-imap php5-curl php5enmod mcrypt service apache2 restart

When asked for the new password for the MySQL “root” user, use a strong password, in this example I have used [email protected]$$w0rd

Now we can go to http://your-ip, in my case http://10.255.50.30 ,and we will see a page showing: “It Works!”.

cd /tmp/

wget http://downloads.sourceforge.net/project/playsms/playsms/Version%201.1/playsms-1.1.tar.gz

tar -zxf playsms-1.1.tar.gz -C /usr/local/src

ls -l /usr/local/src/ cd /usr/local/src/playsms-1.1/

cp install.conf.dist install.conf

nano install.conf

Copy install.conf.dist to install.conf and edit install.conf

Read install.conf and make changes to suit your system configuration.

I’ve edited the file, so it looks like this:

 INSTALL DATA  
 # ============      
 # Please change INSTALL DATA below to suit your system configurations    
 # Please do not change variable name, you may change only the value    
 # MySQL database username  DBUSER="root"    
 # MySQL database password  DBPASS="[email protected]$w0rd"    
 # MySQL database name  DBNAME="playsms"    
 # MySQL database host  DBHOST="localhost"    
 # MySQL database port  DBPORT="3306"    
 # Web server's user, for example apache2 user by default is www-data  
 # note: please make sure your web server user  WEBSERVERUSER="www-data"    
 # Web server's group, for example apache2 group by default is www-data  
 # note: please make sure your web server group  WEBSERVERGROUP="www-data"    
 # Path to playSMS extracted source files  PATHSRC="$(pwd)"    
 # Path to playSMS web files  # note: please make sure your web root path, in this example its /var/www/html  PATHWEB="/var/www/html/playsms"   
 # Path to playSMS additional files  PATHLIB="/var/lib/playsms"    
 # Path to playSMS daemon and other binary files  PATHBIN="/usr/local/bin"    
 # Path to playSMS log files  PATHLOG="/var/log/playsms"      
 # END OF INSTALL DATA  
 # ===================

Now Run:

./install-playsms.sh

Press Y if everything looks OK.

Now we want to make sure playsms starts on boot by adding a line into rc.local file.

nano /etc/init.d/rc.local

Add following to the file: /usr/local/bin/playsmsd start on the bottom of the file (before exit if there’s an exit command). This way playsmsd will start automatically on boot.

.. /usr/local/bin/playsmsd start

Edit the apache vhost file:

nano /etc/apache2/sites-available/default

My vhost file looks like this:

ServerAdmin [email protected]            
DocumentRoot /var/www/html/playsms                            
	Options FollowSymLinks                  
		AllowOverride None                                      
	Options Indexes FollowSymLinks 
	MultiViews                  
		AllowOverride None                  
	Order allow,deny                  
	allow from all                      
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/  

<directory "="" usr="" lib="" cgi-bin"="">                  
	AllowOverride None                  
	Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch                  
	Order allow,deny                  
	Allow from all                      
	ErrorLog ${APACHE_LOG_DIR}/error.log            
	# Possible values include: debug, info, notice, warn, error, crit,          
	# alert, emerg.          
	LogLevel warn            
	CustomLog ${APACHE_LOG_DIR}/access.log combined

Now reload the Aapache2 configuration to apply the changes.

service apache2 reload

Then you should be able to access the playsms website at following url:

Go to http://your-ip etc.

http://10.255.50.30

You can login with:

username: admin password: admin

Gateway - SMS Server Tools 3

First we install build tools to build the latest version. Run:

apt-get install build-essential libusb-1.0 libusb-1.0-0-dev

Now I have plugged in the Huawei E3131 modem, and I can see it listed with lsusb:

lsusb

lsusb  Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.  Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub  Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp.  Bus 001 Device 004: ID 12d1:14fe Huawei Technologies Co., Ltd.

We would like it to be with ID: 12d1:1506, but it’s detected with 12d1:14fe right now. To change this, we install usb_modeswitch to the system, you can grab the latest version from here:

http://www.draisberghof.de/usb_modeswitch/#download

cd /tmp wget http://www.draisberghof.de/usb_modeswitch/usb-modeswitch-2.2.5.tar.bz2 tar jxvf usb-modeswitch-2.2.5.tar.bz2 cd usb-modeswitch-2.2.5 make install cd /tmp wget http://www.draisberghof.de/usb_modeswitch/usb-modeswitch-data-20150627.tar.bz2 tar xjvf usb-modeswitch-data-20150627.tar.bz2 cd usb-modeswitch-data-20150627 make install

Now unplug the modem, and plug it in again, then run:

lsusb

lsusb  Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.  Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub  Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp.  Bus 001 Device 006: ID 12d1:1506 Huawei Technologies Co., Ltd. E398 LTE/UMTS/GSM Modem/Networkcard

Now we got the desired mode: 12d1:1506.

Next we proceed with SMS Server Tools 3.

First we download it, then unpack it and install it.

cd /usr/local/src wget http://smstools3.kekekasvi.com/packages/smstools3-3.1.15.tar.gz tar -zxvf smstools3-3.1.15.tar.gz cd smstools3 make

If you see an error like in my case, when you run make:

make  cd src && make - make[1\]: Entering directory '/usr/local/src/smstools3/src'  Makefile:51: \*\*\* recipe commences before first target.  Stop.  make[1\]: Leaving directory '/usr/local/src/smstools3/src'  Makefile:10: recipe for target 'compile' failed  make: \*\*\* [compile\] Error 2

Then do following:

nano src/Makefile

The problem is a missing tab, now look for:

ifeq (,$(findstring DISABLE_INET_SOCKET,$(CFLAGS))) override LFLAGS += -lsocket -lnsl endif

And move the line override

LFLAGS += -lsocket -lnsl with a TAB

ifeq (,$(findstring DISABLE_INET_SOCKET,$(CFLAGS))) override LFLAGS += -lsocket -lnsl endif

And try to run make again:

make make install

Now we create some required folders:

mkdir -p /var/log/sms/stats mkdir -p /var/spool/sms/{checked,failed,incoming,outgoing,sent}

mkdir /var/spool/sms/modem1

chown www-data:www-data -R /var/spool/sms

chmod 777 -R /var/spool/sms

And then move the original configuration file and download a sample from PlaySMS:

mv /etc/smsd.conf /etc/smsd.conf.dist cd /tmp wget -c https://raw.githubusercontent.com/antonraharja/playSMS/master/contrib/smstools/smsd.conf cp smsd.conf /etc/

To make sure I always will use the correct device, I will use a dynamic device file.

Read more about dynamic device files at following URL: http://antonraharja.com/2015/05/14/persistent-paths-for-dynamic-device-file/

nano /etc/udev/rules.d/80-ttyusb-map.rules

ACTION=="add", KERNEL=="ttyUSB[0-9\]\*", PROGRAM="/etc/udev/rules.d/ttyusb-map.sh %p", SYMLINK+="gsm%c"

touch /etc/udev/rules.d/ttyusb-map.sh chmod 755 /etc/udev/rules.d/ttyusb-map.sh nano /etc/udev/rules.d/ttyusb-map.sh

#!/usr/bin/perl -w    
@items = split("/", $ARGV[0\]);  
for ($i = 0; $i < @items; $i++) {      
if ($items[$i\] =~ m/^usb[0-9\]+$/) {          
print $items[$i + 1\] . "\\n";          
last;      }  }

Now unplug, and replug your modem, and it should be located at /dev/gsm*:

ls -l /dev/gsm\* 
	lrwxrwxrwx 1 root root 7 Jul 24 01:39 /dev/gsm1-1 -> ttyUSB0 
	lrwxrwxrwx 1 root root 7 Jul 24 01:39 /dev/gsmmodem -> ttyUSB0 

# I made some changes to the file, so here is my config, my modem is located at /dev/gsm1-1 replace that with your location.
###  Global configuration    

#devices = modem1, modem2  
devices = modem1    loglevel = 5   

# logfiles  
stats = /var/log/sms/stats  
logfile = /var/log/sms/smsd.log    

# Default queue directory = /var/spool/sms  
outgoing = /var/spool/sms/outgoing  c
hecked = /var/spool/sms/checked  
failed = /var/spool/sms/failed  
incoming = /var/spool/sms/incoming  
sent = /var/spool/sms/sent    
# do not set report folder, let status report files saved in incoming  

#report = /var/spool/sms/report    
delaytime = 2  
errorsleeptime = 10  
blocktime = 180  
autosplit = 3  

#receive_before_send = yes  
incoming_utf8 = yes    
# Queue configurations    

	[queues]
modem1 = /var/spool/sms/modem1  
#modem2 = /var/spool/sms/modem2    
# Modem configurations    
# Modem name: modem1  
# Modem type: Wavecom USB  

	[modem1]
#init = AT+CNMI=2,2,0,1,0;+CMEE=1  
#init = AT+CPMS="ME","ME","ME"  
device = /dev/gsm1-1  
baudrate = 19200  
incoming = yes  
pin = 3391  
report = yes  
queues = modem1  
decode_unicode_text = yes  
cs_convert = yes    
# Modem name: modem2  
# Modem type: Wavecom USB  

#[modem2]
#init = AT+CNMI=2,2,0,1,0;+CMEE=1  
#device = /dev/ttyUSB1  #baudrate = 115200  
#incoming = yes  
#report = yes 
#queues = modem2



# Restart the SMS Server Tools 3:
/etc/init.d/sms3 restart

# Verify if SMS Server Tools 3 is running:
ps ax | grep -v grep | grep smsd

# Monitor SMS Server Tools 3 log file:
tail -f /var/log/smsd.log

Login and configure smstools in playsms webpanel

Login to your playsms installation my address is http://10.255.50.30/

Username is admin Password is admin

Now go to Settings => Manage gateway and SMSC.

You should see a screen like this:

Now click to edit the smstools gateway.

And ensure it’s setup like this:

Click Save, and when it’s saved click back.

Now you have to setup the SMSC, so please select the + sign at SMSTools.

You should fill in the SMSC Details like this, in receiver number write your modem phone number.

When you are done click save.

Now go to Settings => Main configuration

And fill following fields:

Default sender ID Default prefix or country code

And set Default SMSC to smstools, like shown on the image below.

Click save, we are ready to send first SMS.

Send an SMS

​ Now go to My account => Compose message

Write your cell phone number in Send To, and a message etc. Hello World! in message field, and click send.

If the message get’s queued, you can follow transaction here:

​ Go to Reports => All sent messages

Incoming messages that are unhandled is kept in sandbox, you will this in Reports => Sandbox

​ And log if something doesn’t is located in Reports => View log

If you have any trouble with your setup, a good place seek some help is playsms forum.

https://forum.playsms.org/

Raspberry Pi Camera How-To

Raspberry Pi Camera

In diesem Tutorial zeige ich euch wie man die Raspberry Pi Camera installiert, Foto- oder Videoaufnahmen macht und einen Stream an einen anderen Raspberry Pi / Rechner schickt.

#Abmessungen
25mm × 20mm × 9mm

#Sensor
5 Megapixel mit Fixfokusobjektiv

#Fotoauflösung
bis 2592 x 1944 Pixel

#Videoauflösung
1920 × 1080 / 30 Frames 1280 x 720 / 60 Frames 640 x 480 / 60 oder 90 Frames

Raspberry Pi Camera installieren

Zunächst einmal schließen wir die Kamera an der vorgesehenen CSI-Schnittstelle an (Abbildung oben) und starten das Konfigurationstool des Raspberry Pi.

sudo raspi-config

Weiter unten sollte die Zeile “Enable Camera” zu sehen sein. Falls ja, einfach mit Enter bestätigen, Speichern und den Raspberry Pi mit “sudo reboot” neustarten. Falls die Zeile fehlt muss das System mit den folgenden zwei Befehlen auf den neuesten Stand gebracht werden:

sudo apt-get update 
sudo apt-get upgrade

Raspberry Pi Camera Konfiguration

Fotos aufnehmen

#Aufnahme im Jpeg-Format**
raspistill -o image.jpg

#Aufnahme im PNG-Format Mit dem Parameter -e kann man die Formate jpg, bmp, gif und png erzeugen.
raspistill -o image.png –e png

#Aufnahme ohne Preview
raspistill -o image.jpg -n

#Aufnahme auf Knopdruck (Enter) Ersetzt man image.jpg durch image%02d.jpg wird bei jedem Knopdruck eine neue Datei im Format image01.jpg erstellt.
raspistill -t 0 -k -o image.jpg

#Zeitverzögerte Aufnahme (3 Sekunden)
raspistill -o image.jpg -t 3000

#Aufnahme in einer niedrigeren Auflösung (640x480)
raspistill -o image.jpg -w 640 -h 480

#Aufnahme in einer niedrigeren Qualität Die Reduzierung der Qualität spart Speicherplatz. Es sind Werte von 0 bis 100 möglich.
raspistill -o image.jpg -q 20

#Zeitrafferaufnahme Mit dem folgendem Befehl wird eine Stunde (-t 3600000) lang alle 5 Sekunden (-tl 5000) ein Bild aufgenommen. Dabei steht die Bezeichnung %04d im Dateinamen für eine vierstellige Nummerierung (z.B. image_0001.jpg).
raspistill -o image_%04d.jpg -tl 5000 -t 3600000

#Die erstellten Aufnahmen können mit dem Tool ffmpeg in eine mp4 Videodatei umgewandelt werden.
ffmpeg -qscale 5 -r 4 -b 9600 -i img_%04d.jpg zeitraffer.mp4


Videos aufnehmen

5 Sekündiges Video in 1080p (1920 x 1080) Mit dem Parameter -t gibt man die Aufnahmezeit in Millisekunden an. Für eine unendliche Aufnahme (z.B. für einen Stream) einfach den Wert auf 0 setzen.

raspivid -o video.h264 -t 50000

#5 Sekündiges Video in 720p (1280 x 720)
raspivid -o video.h264 -t 50000 -w 1280 -h 720

#Video mit individueller Bitrate (3.5MBits/s)
raspivid -o video.h264 -t 50000 -b 3500000

#Video mit individueller Framerate (10 Frames/Sekunde)
raspivid -o video.h264 -t 50000 -f 10

#Videostream an stdout schicken
raspivid -t 50000 -o -

Videos konvertieren H264 nach mp4

apt-get install gpac 
MP4Box -fps 30 -add video.h264 video.mp4

LED an-/ausschalten

1. Methode

Füge folgende Zeile zur Datei “/boot/config.txt” hinzu und mache einen Reboot. Leider kann es passieren das die Einstellungen nach einem Neustart verloren gehen. Das hängt mit Kompatibilitätsroblemen einiger SD-Karten zusammen. Sollte dies der Fall sein, bearbeitet die Datei an einem anderem Linuxrechner und benutzt die zweite Methode.

disable_camera_led=1

2. Methode

Einmal mit der obigen Methode deaktiviert, lässt sich die LED über den GPIO 5 steuern.

sudo echo "5" > /sys/class/gpio/export 
echo "out" > /sys/class/gpio/gpio5/direction 
echo "1" > /sys/class/gpio/gpio5/value

Stream auf anderen Raspberry Pi oder Rechner

Vorbereitung des Servers Mithilfe dem Tool Netcat kann man den von raspivid erzeugten Stream direkt an einen anderen Rechner oder Raspberry Pi schicken. Dazu muss man lediglich die IP-Adresse des Empfängers (Client) wissen. Diese zeigt man unter Unix mit ifconfig und bei Windowsrechnern mit ipconfig an. Im folgendem Beipiel wird der Stream an einen anderen Raspberry Pi mit der IP-Adresse 192.168.178.20 auf den Port 5001 geschickt:

apt-get install netcat raspivid -t 0 -o - | nc 192.168.178.20 5001

Vorbereitung des des Clients - Linux Auf dem Raspberry Pi / Linux Client wird zusätzlich zu Netcat der Videoplayer MPlayer nachinstalliert um den Stream direkt auf der grafischen Oberfläche anzuzeigen.

apt-get install mplayer netcat

nc -l -p 5001 | mplayer -fps 31 -cache 1024 -

Zeitraffer-Aufnahmen mit Raspberry PI Camera

Es ist recht einfach mit der Raspberry Pi Camera automatisiert Bilder aufzunehmen und aus diesen eine Zeitraffer-Aufnahme zusammenzustellen. Um den Weg dorthin etwas zu erleichtern findet ihr anbei eine schrittweise Anleitung mit Code-Beispielen um selbst Zeitraffer-Aufnahmen zu erstellen.

Raspberry Pi mit Kamera Modul

Auf dem Raspberry Pi laufen unterschiedliche Linux-Distributionen. Für dieses kleine How-To ist am Raspberry Pi die aktuelle Raspbian (Debian Wheezy) Version installiert. (Release Date: 2014-01-07)

Für die weiteren Schritte wird die Console (Bash) und Python als Programmiersprache verwendet.

Verzeichnis für Bilder erstellen

mkdir -p /home/pi/cam/pic

Python Script für automatisierte Aufnahmen öffnen

nano /home/pi/cam/raspcam.py

Das folgende Script macht alle 60 Sekunden eine Aufnahme. Durch die Variable „sleeptime“ wird der Zeitabstand zwischen den Aufnahmen definiert. In diesem Fall ist diese auf 60 Sekunden gesetzt. Es gibt noch viele weitere Parameter in dem Script, die je nach belieben geändert werden können. Eine Dokumentation ist hier zu finden: http://picamera.readthedocs.org/

#!/usr/bin/env python2.7  
import picamera  from time import sleep  
camera = picamera.PiCamera()  

#sleep time in seconds  
sleeptime = 60  try:    
    camera.sharpness = 0    
    camera.contrast = 0    
    camera.brightness = 50    
    camera.saturation = 0    
    camera.ISO = 100    
    camera.video_stabilization = False    
    camera.exposure_compensation = 0    
    camera.exposure_mode = 'auto'    
    camera.meter_mode = 'average'    
    camera.awb_mode = 'auto'    
    camera.image_effect = 'none'    
    camera.color_effects = None    
    camera.rotation = 0    
    camera.hflip = False    
    camera.vflip = False    
    camera.crop = (0.0, 0.0, 1.0, 1.0)    
    camera.resolution = (1280, 720)    
    for i, filename in 
    	enumerate
        (camera.capture_continuous
         ('{timestamp:%Y-%m-%d-%H-%M-%S}.jpg')):      sleep(sleeptime)  
            finally:    camera.close()
                

Das Skript soll einige Zeit laufen bis es Sinn macht aus den Bildern eine Zeitraffer-Aufnahme zu erstellen. Bei einer Bildwiederholfrequenz von 10 Bildern/s sollten, damit ein brauchbare Ergebnis zu sehen ist, mehr als 50 Bilder zur Verfügung stehen. -> In diesem Fall würde das Video 5 Sekunden dauern.

Um ein Timelapse Video zu erstellen verwenden wir das Tool „mencoder“.

sudo apt-get install mencoder

ffmpeg / avconv / mencoder all replaced. libav-tools and mpv are the updated packages in Jessie: https://packages.debian.org/jessie/libav-tools https://packages.debian.org/jessie/mpv http://mpv.io https://libav.org

Wechseln in das Verzeichnis welches für die Raspberry Pi Camera angelegt wurde.

cd /home/pi/cam

Erstellen einer Liste aller Bilder für das Tool mencoder

ls -tr pic/\* > frames.txt

Konvertierung des Videos mittels dem Tools mencoder. Hiermit werden die Bilder in der Auflösung 1280×720 in ein „avi“ verwandelt bei einer Bildwiederholfrequenz von 10 Bildern pro Sekunde.

mencoder -nosound -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell:autoaspect:vqscale=3 -vf scale=1280:720 -mf type=jpeg:fps=10 mf://@frames.txt -o timelapse.avi

Damit das Script direkt beim Start ausgeführt wird muss kann folgender Befehl in die Datei /etc/rc.local hinzugefügt werden.

/home/pi/cam/raspcam.py &

Diese Zeile muss vor der Zeile „exit 0“ stehen.

Wenn der Raspberry Pi nun startet werden automatisch Bilder aufgenommen.

Wenn sich jemand selbst einen kaufen möchte dann nutzt bitte gleich unsere Affilate-Links zu Raspberry-Pi und Camera-Modul

cam

raspberry_pi