Posts Tagged ‘Raspberry Pi’

About: beaks.live – the hardware

Thursday, April 13th, 2023

This is the bird box that is shown at beaks.live. It is on the side of a house in Cambourne, about 8 miles west of Cambridge, in the UK.

When I put a camera in this bird box last year, I was not optimistic. Expecting to capture nothing more than the inside of an empty box, there didn’t seem much point in spending any significant sum of money on a camera. I decided to see how well I could get it working for how little money.

Two cameras for £21.66 doesn’t scream quality, but they are able to manually focus down to a few cm. Being cheap and nasty also means they won’t have an infra-red filter on the lens, which means I can illuminate the box at night with a light the beaks can’t see.

I picked one and sawed off the mounting at the bottom, knocked up a 3d printed housing to fit it in the apex of the bird box roof, and fitted some cheap Ebay IR LEDs.

A mess of wires being put into the 3d printed camera mount.
Cheap and nasty does it every time

This is the camera and LED housing mounted in the bird box:

Looking up into the box with the mounting fitted.
Looking upwards into the roof of the box

On the outside is the 3d printed box which holds the interface to the cable that goes into the house and the drivers for the LEDs. I actually had a proper PCB made with a D/A for the microphone but I never wired it up because I’m lazy. That’s why there is no sound. Sorry.

The interface box with unused D/A.

The LED controls and USB for the camera share a length of CAT-5 cable into the house, where they plug into the Raspberry Pi, which has an ethernet connection to the router.

And that’s the hardware. Total cost probably around £75, including custom made PCBs, which were ridiculously cheap. I mean like stupidly cheap – around £5 for 5 PCBs, including delivery from China. Anything clever is done in software, including stuff to improve the performance of the (frankly substandard) parts I used. Next year I’ll replace it with decent kit, including a camera that isn’t shit.

Coming up next… The software

Abusing Public WiFi Access Point Protocols for Fun and Beer Measurement (Raspberry Pi)

Tuesday, June 9th, 2020

This is a little sub-project of what I’ve been working on recently – a hideously over-engineered Raspberry Pi-based system to measure the amount of beer left in the kegs in my keezer.

Normally I would simply set up a web server on the Pi and have it on the home network, so I could see the levels remotely. The problem is that the routers are all inside the house and the Pi is in the garage, invisible to them all thanks to the 2 external walls between them. I needed some way to read out the beer levels on my phone – after all, walking up to something and looking at the level gauge is so last millennium.

So – Bluetooth or some sort of ad-hoc Wifi thing? I like to re-use stuff I’ve got lying around in drawers, so the solution seemed to be an old WiFi dongle that was gathering dust. And Bluetooth is awful. Setting up a Pi as an access point is fairly well covered on the internets, but this is a bit different in that we don’t want to forward traffic onto our network like an access point – not that it could connect anyway, being out of range. I also didn’t want to install a web server on the Pi. It’s only a Pi 1 model B, so sticking Apache and PHP on it might be asking a bit much – especially when you can do it all with one command and a small BASH script.

So the cunning plan was to take advantage of a feature of public access points – the ones that show you a registration page for you to fill in with fake info.

When you connect to a public WiFi hotspot your device tries to load a page on the internet using non-SSL http. It might be any page (captive.apple.com/ seems to be popular), but it will be a web page that the device knows should exist and if it loads, your device knows the internet is working.

A public access point intercepts the page request and, rather than forwarding it, sends a 30x redirect HTTP response back to the device – basically hijacking the request and spoofing the reply. Your device then loads up the page it has been redirected to and displays it as a sign-in page.

It is this mechanism that I used to show the keg levels on any phone, just by connecting to the Wifi. This is how to do it if you want to do something similar. I’m assuming you SSH on to a Pi connected with an ethernet cable to your network, and you have a Wifi dongle hanging out of its USB port. In all likelihood they will be eth0 and wlan0 respectively, so I’ll use them.

wlan0 is going to use a different range of IP addresses from the ones used by eth0, so edit /etc/dhcpcd.conf to manually assign an IP address to the wlan0 interface. Add this at the bottom (comment out any existing definition for wlan0):

interface wlan0
    static ip_address=192.168.4.1/24
    nohook wpa_supplicant

Next we need to install hostapd to run the hotspot and dnsmasq to sort out assigning IP addresses to devices that connect.

sudo apt-get install hostapd
sudo apt-get install dnsmasq
sudo systemctl stop hostapd
sudo systemctl stop dnsmasq

The second two commands disable the services we just installed so we can edit config files before starting them again.

Create the file /etc/dnsmasq.conf and put this in it:

interface=wlan0      # Usually wlan0
dhcp-range=192.168.4.2,192.168.4.20,255.255.255.0,24h
address=/#/192.168.4.1

This tells dnsmasq to assign the range 192.168.4.2 – 192.168.4.20 with a netmask of 255.255.255.0 and a lease time of 24 hours. The third line tells it to return the server address for all domain lookups that aren’t in /etc/hosts, i.e. all of them. When dnsmasq restarts it will look at this file and load up the config information.

Now to set up hostapd. Create /etc/hostapd/hostapd.conf and put this in it:

interface=wlan0
driver=nl80211
ssid=Your SSID here
hw_mode=g
channel=7
wmm_enabled=0
macaddr_acl=0
ignore_broadcast_ssid=0

It’s pretty obvious what is happening there, other than some of the technical bits; wmm_enabled is something to do with packets (no idea what, though), macaddr_acl tells it to whitelist all connections and ignore_broadcast_ssid tells it to broadcast the SSID – set it to 1 to hide it. There is no WPA password or setup, obviously. Change the SSID to something hilarious.

Now you need to tell hostapd where to find the config file when it starts. Edit /etc/default/hostapd and add (or uncomment and edit) the line:

DAEMON_CONF="/etc/hostapd/hostapd.conf"

We have now set up our access point. Start dnsmasq and hostapd again:

sudo systemctl start hostapd
sudo systemctl start dnsmasq

If there are no errors, your AP should show up in the list of APs on your phone, laptop etc. Try connecting to it – it should connect but you won’t be able to see the internet because there is no forwarding. One thing you can still do however, is connect to SSH on the Pi. You really don’t want any ports other than 80 visible from an unsecured AP. We’ll use iptables to set up a firewall and do the test page hijacking.

sudo iptables -A INPUT -p tcp -i wlan0 --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp -i wlan0 --dport 53 -j ACCEPT
sudo iptables -A INPUT -p tcp -i wlan0 -j DROP
sudo iptables -t nat -A PREROUTING -p tcp -i wlan0 --dport 80 -j DNAT --to-destination 192.168.4.1:80

The first two tell iptables to allow through connections on port 80 (HTTP) and 53 (DNS), the second tells iptables to drop all other TCP connections from wlan0. The third redirects any connection with a destination port 80 (regardless of the IP address) to the Pi at IP address 192.168.4.1, port 80, for our server to handle. If you are a bit confused about how iptables work, this flowchart will either clear things up or make it more confusing. Basically there are 4 tables – filter (default if no -t switch), nat, mangle and raw which each contain “chains” such as INPUT which are the instructions on how to route traffic. It’s a vast subject and I learned just enough to work out the 3 lines above. There are other guides that go into more details.

One thing to do at this point is make it so that the iptables configuration is not lost when the system is rebooted. This command saves it to a file:

sudo iptables-save >/etc/iptables.ipv4.nat

To reload the configuration on boot put this in /etc/rc.local

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

So, moving on to the web server. I’m using socat and a bash script. socat is one of those amazing Linux tools that is impossible to explain to a layperson. “What it does is, it takes data from one place and puts it in another but it’s more complicated than that…” and so on. Best just to tell them it’s the computer equivalent of magic, before their eyes glaze over and they start thinking about feigning an illness in order to escape. We are going to use it to pipe data from an internet port to a script and back again. Incoming text from port 80 is sent to the script on stdin and anything written to stdout gets sent back to the port. It’s easy enough to set up with this command:

sudo socat TCP4-LISTEN:80,reuseaddr,fork EXEC:"/home/your_path_here/server.sh >/dev/null" 2>/dev/null &

Obviously change “your_path_here” to where you are doing all this stuff and put this line in /etc/rc.local if you want it to start automatically on boot. The command tells socat to listen on port 80 and then fork off the script when there is a connection. The script referred to as /home/your_path_here/server.sh is this:

#!/bin/bash

PAGE_NAME="kegs"
FOUND_URL="http://1.1.1.1/$PAGE_NAME"

request=""
while read -r  -t 5 line; do
  if [[ ! -z "${line:-}" && $line == *[^[:cntrl:]]* ]]; then
    if [[ ${line:0:4} == "GET " ]]; then
      request=$(expr "$line" : 'GET /\(.*\) HTTP.*')
    fi
  else
    break
  fi
done

if [[ "$request" == "$PAGE_NAME" ]]; then
  printf "HTTP/1.1 200 OK\n"
  printf "Content-Type: text/html\n\n"
  cat index.html	# Show this as a registration page.
else
  printf "HTTP/1.1 302 Found\n"
  printf "Location: $FOUND_URL\n"
  printf "Content-Type: text/html\n\n"
  printf "Redirect to <a href=\"$FOUND_URL\">$FOUND_URL</a>\n"
fi

That’s pretty dinky for a web server, huh? Don’t forget to change permissions of server.sh with chmod 755 server.sh. Rename PAGE_NAME and FOUND_URL to whatever you want. Note that because we are grabbing all port 80 traffic coming in on wlan0, it doesn’t matter what you put for an IP address – it’ll all go to our server. The first block of code reads the HTTP request coming from the device, which will be saying something along the lines of:

GET / HTTP/1.1
Host: captive.apple.com
Accept: image/gif, image/jpeg, */*
... and so on

The script ignores everything except the GET /… part, from which it extracts the page name, if any. It won’t match (unless the test page is called “/kegs” – unlikely), so it will respond with the redirect code 302, to send the device to “/kegs”. The device sees the redirect, thinks it’s for a registration page and loads 1.1.1.1/kegs. This time the script sees that /kegs has been requested, sends a 200 OK code and the contents of index.html, which the device displays. My beer measurement system generates index.html as a page showing how much is left in each keg.

As a useful tool with which to quickly see the levels of my kegs without any fuss, this is rubbish, quite frankly. But then the whole raspberry-pi-based-keg-measurement thing could be replaced with cheap mechanical bathroom scales, so I might as well go all in on the pointless technology.

Updated 10/6/2020 : Improved the firewall rules.
Updated 18/2/2021 : Improved DNS rules.

Pi-rate Radio Jukebox

Friday, October 31st, 2014

p1070168Note: there is an update to this post.

There is a nice hack for a Raspberry Pi where you can turn it into an FM transmitter.  While this is illegal in most countries, the range is quite limited so it’s fairly unlikely you’ll go to prison. The only hardware needed is your Raspberry Pi and a piece of wire attached to pin 7 (GPIO 4) of the GPIO connector.  The length of the wire depends on the frequency you are transmitting on – roughly speaking, it should be 299/(frequency x 4) metres long.  So 103 MHz is 725 mm.  Or if you are using inches, 299/(frequency x 0.1016) inches.

It’s very easy to transmit internet radio using just one line of Bash but if, like me, you have a few thousand MP3s , there’s no quick and dirty way to pump them out to the transmitter.

Until now.  Behold the PIrate Radio Juke Box (pirjb). If you can think of a better name for it, please leave a comment.  A couple of Bash scripts, a minor alteration to the pifm code and a reckless disregard for radio licensing regulations is all that is needed to listen to your collection on any FM radio.   You can repeat and shuffle with either a playlist of MP3s in a file or point it to the directory the MP3s live in and it’ll scan them and make its own playlist.

Also included is a web server to show you the currently playing track.  Using your browser, you can skip to the next track or shut everything down and turn the transmitter off.  Note that you can’t turn it back on with the web interface yet.  That’s the next thing on the to do list.  You can get to the page by going to http://your_pi_address:8080/  The “8080” is set in the pirjb.sh file, at the top.

Note that I do not condone or encourage the use of transmitting equipment without the proper license.  This article is presented purely as an exercise in theoretical programming.  Your statutory rights are not affected.  Your home may be at risk if you set fire to the curtains.

Setting up

You need to have the following packages installed: sox, netcat, mp3info.  Use

sudo apt-get install sox netcat mp3info

to install them.

Copy the pirjb archive to an empty directory on your Pi and extract the files with

tar zxf pirjb.tgz

You need to edit pirjb.sh.  The top few lines are where things like the transmission frequency, path to the scripts and the port for the web server are defined.  There is also a line for the compander settings for sox in order to have an AGC.  If you didn’t understand that last sentence, don’t change that line.  I’ve also included the source for the pifm binary included in the archive.  There is a very minor change to it from this one – calling it with no parameters turns off the transmitter.  Please do compile it and use it instead of the binary I’ve put in the archive.  You shouldn’t really be running binaries from random geezers on the interwebs anyway.  And I am sometimes quite random.

You need to make pifm run as root using setuid in order for the transmitter to work.  Do this with:

sudo chown root:root pifm
sudo chmod 4755 pifm

To run it use:

pirjb.sh -d <directory name>  or
pirjb.sh -p <playlist>

Switches are -s to shuffle the track order, -r to repeat the playlist indefinitely.  The playlist file should have the full path of each mp3 you want to play per line, i.e.

/home/naich/music/Wombles Christmas Special/01 Wombling Christmas.mp3
/home/naich/music/Napalm Death/Scum/Human Garbage.mp3
… and so on.

Have fun playing with it and do not use it because it is illegal to do so.

Files included in the archive:

  • pifm : The transmitter binary
  • pirjb.sh : The jukebox script.  Edit the first few lines for your system.
  • pirjb_webserver.sh : The webserver script.  No need to edit it.
  • pirjb_template.html : The template for the web server page.  See pirjb_webserver.sh for information about using it.  Or just look at the file itself and have a guess.  It’s not hard to see what’s going on.
  • source/pifm.c : The source for pifm.  Compile with g++ -O3 -o pifm pifm.c then copy over the top of pifm.  Don’t forget to chown and chmod the compiled program.

Yummy Pi – what to do with a Raspberry Pi

Thursday, June 21st, 2012

So you’ve got your Raspberry Pi and it’s sitting there, staring at you PCB-ily while you are wondering why you ordered it in the first place.  If you don’t know what to do with your Raspberry Pi, don’t bother plugging it into your TV, booting it up and clicking despondently at a few things before chucking it in the loft.  Use it for something useful and learn a bit about Linux at the same time.  Don’t tie up the TV with your Pi, use it on your home network as your faithful assistant – always on and connected to the internet, ready to do whatever you want at any time.  Use it headless (no monitor, keyboard or mouse) and install a whole load of useful stuff on it: a Bittorrent client, media streamer, network-attached-storage or any of these ideas.  You have a PC that is more powerful than the best computer you could buy 10 years ago and it uses less power than a low power light bulb.  It would be a crime not to use it for something.

A Raspberry Pi in a snazzy Lego case

These series of posts are aimed at someone who knows a bit about computers (above the level of randomly clicking at things in a blind panic, but below reprogramming the BIOS with a 9 volt battery and a hair clip) but not much (or indeed anything at all) about Linux.  You will learn to use your Pi at a fairly intimate level, gently stroking its settings by typing in commands and editing files.  This is not pointing and clicking, as you do with Windows, Macs or Linux distributions like Ubuntu, but typing stuff in is not difficult and it makes you feel like a hardcore hacker.  Embrace your inner geek and learn to love your Pi.

1.  Plugging it in

If you want to, you can plug your Raspberry Pi into your TV, stuff a mouse and keyboard up its USB ports and use its (quite slow by all accounts) GUI, but I don’t do these sorts of shenanigans.  I have a simpler setup where it’s just plugged into the network and accessed remotely, with no keyboard, mouse or anything.  To run it this way, you need three things: a power supply, an SD memory card and a bog standard CAT5 network cable.  Don’t panic if you are running your home network wirelessly – your router will have sockets on it for plugging in network cables.  You won’t need physical access to your Pi after the initial set up, so you can leave it next to your router – in the cupboard, under the sofa, or wherever your router lives.

To power it up, you need a 5V power supply that can provide at least 700mA with a mini-USB connector on the lead.  Have a look in that collection of phone chargers you’ve got rattling around in your crap drawer.  Jen’s Samsung charger worked a treat.  Failing that you can buy one for less than a fiver from Amazon – something like a Nokia AC-10x charger..

2.  Booting it up

You need a SD card of at least 2GB, but 4GB is better if you want to install anything.  There isn’t really an upper limit, so 16, 32 or 64GB cards should work, with faster (class 10) cards giving you a faster system overall.  It used to be the case that some cards worked better than others but later firmware versions fixed the problems that some Pis had with faster cards.  If you find that your Pi is not booting, it is worth trying a different type of card just in case.

There is no software built into the Pi, so it boots and runs off the SD card as if it were a hard drive.  That means you need to install all the software it needs on the card before you plug it into the Pi.  This page shows you how to do it. using a disk image that you copy onto the card using a card reader and software on your PC.  Here is where you download the image fileto copy to the card.  Download Raspbian “wheezy”, which is basically Debian optimised for the Pi.

If you have just finished installing the image, unplug the card from the reader now.  Plug the card back into your card reader and a window with a 59MB partition in it should pop up on your PC.  This contains the files that boot the Pi. If you are using Linux, you will also see a 1.9GB partition in another window – this contains the the rest of the files for the Raspbian system.  Because Windows can’t recognise the type of filesystem (EXT3),  Windows users can’t see this partition, but don’t worry about that.  You might be wondering what has happened to the rest of your SD card – you can only see about 2GB of it.  The file system can be adjusted to use the rest of the card’s memory once the Pi is up and running.

Now safely remove the card, lob it in your Pi, plug it into your router with the CAT5 cable and plug in the power supply.  If it’s all OK, the red LED should come on for a few seconds followed by the other ones, with the green one flashing occasionally.  The LEDs are stupidly bright.  Congratulations!  Your Raspberry Pi is now ready for use.  If only the red light is on then something is wrong.  If you have followed all the instructions and have the correct partitions and files on it, then it is probably the card itself which is the problem.  Try a different card and see if that fixes it.

Continued here…