Silicon ChipWiFi Controlled Switch Using A Raspberry Pi & Smartphone - November 2016 SILICON CHIP
  1. Outer Front Cover
  2. Contents
  3. Publisher's Letter: Renewable energy is seriously damaging the Australian economy
  4. Feature: Airbags: Your Car’s Explosive Guardian Angels by Dr David Maddison
  5. Feature: What Is The Internet Of Things (IoT)? by Ross Tester
  6. Project: 50A Battery Charger Controller by John Clarke
  7. Serviceman's Log: Odd happenings in my new house by Dave Thompson
  8. Project: Passive Line To Phono Input Converter by Nicholas Vinen & Bao Smith
  9. Product Showcase
  10. Feature: Micromite Plus Advanced Programming by Geoff Graham
  11. Project: Micromite Plus LCD BackPack by Nicholas Vinen
  12. Project: WiFi Controlled Switch Using A Raspberry Pi & Smartphone by Greg Swain & Nicholas Vinen
  13. PartShop
  14. Review: Siglent SDS2104 4x100MHz Mixed Signal Scope by Jim Rowe
  15. Subscriptions
  16. Vintage Radio: The incredible shrinking mantel set: GE’s T2105 by Ian Batty
  17. Market Centre
  18. Notes & Errata: 4-Input Automotive Fault Detector, Sept 16; Circuit Notebook, Sept 16; Vintage Radio, Sept 16; Appliance Energy Meter, Aug-Oct 16; Compact 8-Digit Auto-Ranging Frequency Meter, Aug 16; 5-Element DAB+ Antenna, Nov 15
  19. Advertising Index
  20. Outer Back Cover

This is only a preview of the November 2016 issue of Silicon Chip.

You can view 42 of the 104 pages in the full issue, including the advertisments.

For full access, purchase the issue for $10.00 or subscribe for access to the latest issues.

Items relevant to "50A Battery Charger Controller":
  • 50A Battery Charger Controller PCB [11111161] (AUD $10.00)
  • PIC12F675-I/P programmed for the 50A Battery Charger Controller [1111116A.HEX] (Programmed Microcontroller, AUD $10.00)
  • Firmware (ASM and HEX) files for the 50A Battery Charger Controller [1111116A.HEX] (Software, Free)
  • 50A Battery Charger Controller PCB pattern (PDF download) [11111161] (Free)
  • 50A Battery Charger Controller lid panel artwork (PDF download) (Free)
Items relevant to "Passive Line To Phono Input Converter":
  • Passive Phono To Line Input Converter PCB [01111161] (AUD $5.00)
  • Matte/Gloss Black UB5 Lid for Passive Phono To Line Input Converter (PCB, AUD $5.00)
  • Passive Phono To Line Input Converter PCB pattern (PDF download) [01111161] (Free)
  • Passive Phono To Line Input Converter panel artwork and drilling template (PDF download) (Free)
Articles in this series:
  • Micromite Plus Advanced Programming (November 2016)
  • Micromite Plus Advanced Programming, Pt.2 (December 2016)
Items relevant to "Micromite Plus LCD BackPack":
  • Micromite Plus LCD BackPack PCB [07110161] (AUD $7.50)
  • PIC32MX470F512H-120/PT programmed for the Micromite Plus (Programmed Microcontroller, AUD $20.00)
  • Micromite Plus LCD BackPack complete kit (Component, AUD $65.00)
  • Matte/Gloss Black UB3 Lid for 2.8-inch Micromite LCD BackPack (PCB, AUD $5.00)
  • Clear UB3 Lid for 2.8-inch Micromite LCD BackPack (PCB, AUD $5.00)
  • Gloss Black UB3 Lid for 2.8-inch Micromite LCD BackPack (PCB, AUD $4.00)
  • Firmware (HEX) file and documents for the Micromite Mk.2 and Micromite Plus (Software, Free)
  • Micromite Plus LCD BackPack PCB pattern (PDF download) [07110161] (Free)
Items relevant to "WiFi Controlled Switch Using A Raspberry Pi & Smartphone":
  • Script for the Raspberry Pi WiFi Controlled Switch (Software, Free)

Purchase a printed copy of this issue for $10.00.

Using your Raspberry Pi with a smart-phone as a WiFi-controlled switch Bake your Raspberry Pi with a smartphone and a relay board to open or close your garage door remotely By Greg Swain & Nicholas Vinen Ever driven 1km down the road and wondered if you had closed the garage door? Well, by installing a WiFi camera and an app on your smartphone, you can easily check the door’s status. Add an RPi computer that’s coupled to a garage-door remote and you can also use the phone to open or close the door via a web browser. W E’VE ALL done it – driven off and then couldn’t remember whether or not the garage door had been closed. Fortunately, a mix of technology makes it easy to remedy that situation. The ingredients are simple: take one IP camera to monitor the garage, add a spare garage remote, mix in your smart-phone and bake them all with a $60 Raspberry Pi (RPi) computer and a 3-way relay board. Once it’s all done, you can use the smart-phone (or a PC) to “see” inside your garage and control up to three doors by “pressing” virtual buttons on a web page served up by the RPi When you press a web-page button, the RPi momentarily sends one of its I/O pins high to pulse a relay on. The relay’s NO (normally open) contacts are wired 74  Silicon Chip across one of the remote’s switches. When they close, this simulates a button press and the garage door opens or closes accordingly. If you have more than one door, it’s just a matter of wiring another set of relay contacts acoss the relevant button on the remote. This set-up can not only remotely close a garage door if you’ve accidentally left it open but is also useful if you want to give someone access to the garage when you’re not at home; eg, to have building materials delivered. It also lets you gain access to the garage if you’ve accidentally left your garage remote at work or lost it. In summary then, the RPi has two functions: (1) it serves up the web page with the garage door control buttons; and (2) it briefly pulses the garage-door remote via the relay board. The separate camera app on your phone siliconchip.com.au The web page served up by the RPi has nine control buttons – three to pulse the relays on for 0.5s, three to toggle them on and three to turn them off. simply lets you check the garage door status. As shown in the photos, the web page served up by the RPi has nine control buttons, three for each relay. In each case, the “pulse output x” button pulses the associated relay on for half a second (0.5s), while the “output on x” and “output off x” buttons respectively toggle the relay on and off. So as well as briefly pulsing the relays on, you can also toggle them on or off to switch low-voltage devices. RPi relay board The Waveshare RPi Relay Board used here supports the Raspberry Pi A+, B+, 2B and 3B models. It has three relays and plugs directly into the RPi’s 40-pin I/O header. In operation, the relays are driven via optocouplers, while their contacts are brought out to 3-way screw terminal blocks. Separate on-board status LEDs are used to indicate whether each relay is on or off. By default, the relays are controlled by pins 37, 38 & 40 on the RPi’s I/O header, as selected by three jumpers. These jumpers can be removed so that other I/O pins on the header can be linked across to control the relays if that suits your particular application. Supplied with the relay board are two M2.5 x 16mm metal stand-offs (plus screws & nuts). As shown in the photos, these are used to support one side of the relay board (ie, the side opposite the header) when it is plugged into the RPi. Raspberry Pi set-up Any RPi computer with a 40-pin GPIO header can be used, including the RPi Model B+, RPi 2 Model B and the recently released RPi 3 Model B. If you’re buying a new unit, get the RPi 3 since this comes with onboard WiFi. If you have an earlier model, then you will also siliconchip.com.au need to buy a Wi-Pi WiFi dongle. An 8-32GB microSD card to accommodate the operating system and a suitable power supply are also required. In addition, you’ll also initially need these parts to set the unit up: a USB keyboard and mouse (wireless units can be used), an HDMI cable, a suitable monitor (with HDMI input) and a USB memory card reader. Once you have all the ingredients, install and configure the Raspbian operating system on the microSD card, as detailed in Steps 1-5 on pages 20-22 of the January 2016 issue (ie, in the RPi Temperature Monitor article). Be sure to use a strong password (Step 5), then get the WiFi working as outlined in Steps 6 & 7. Steps 8-10 can be omitted but you should install TightVNC by following the instructions on pages 26 & 27. Once you’ve installed TightVNC (VNC = Virtual Network Computing), you will be able to run your RPi “headless” (ie, without a mouse, keyboard or monitor), with all control now coming via your PC (ie, the RPi’s desktop will appear on your PC’s monitor). Next, you need to install the Apache2 Web Server and the mod_python module on the RPi. Python is a programming language that’s used with Raspbian and the mod_python module embeds the Python interpretor with Apache2 so that the two can work together. First, make sure that your Raspbian OS is completely up to date by running the following commands from a terminal window: sudo apt-get update sudo apt-get upgrade sudo reboot That done, install Apache2 and the Python module by following Steps 1-8 on pages 56 & 57 of the February November 2016  75 the RPi’s Apache2 web server by entering https:// <yourpublicIPaddress> in a web browser on your PC or smartphone. When you do so, the log-in dialog should immediately appear and you should be able to enter your details to access Apache2’s default web page. How do you know what your public IP address is? That’s easy; just go to www.whatismyip.com/ and the address will be displayed. If you don’t know how to assign a fixed IP address to the RPi or how to set up port forwarding, page 59 of the February 2016 issue spells it out in detail. Dynamic DNS (DDNS) The relay board plugs into the RPi’s I/O header. By default, it’s controlled by I/O pins 37, 38 & 40. 2016 issue of SILICON CHIP. And because the RPi’s web server will be accessible via the internet, it’s necessary to set up password access, as follows: sudo apt-get install apache2-utils sudo a2enmod authn_dbm sudo htdbm -c -TSDBM /etc/apache2/dbmpasswd <username> <enter password> sudo chown www-data /etc/apache2/dbmpasswd.pag Once again, be sure to choose a strong password. It should be a mixture of upper case and lower case letters, numbers and alphanumeric symbols. (Note: the above procedure is exactly the same as Step 10 in the February 2016 issue except that the -c and -TSDBM switches in line 3 have been transposed). Next, go to the two Apache2 configuration files (ie, 000-default.conf and default-ssl.conf, in /etc/apache2/ sites-available/) and add the following lines under the lines you added in Steps 2 & 3: AuthType basic AuthName “private area” AuthBasicProvider dbm AuthDBMType SDBM AuthDBMUserFile /etc/apache2/dbmpasswd Require valid-user Then do: sudo service apache2 restart Now, whenever you attempt to browse to the RPi’s web server, you will initially be greeted by a dialog box asking you to enter your user-name and password. Note, however, that you must use SSL (set up as in Step 6 of February 2016) and use https://<yourpublicIPaddress> to access the site when browsing from the internet (see later), otherwise your password could be intercepted. Accessing it via the internet The next step is to configure the RPi so that you can access its web server via the internet. That’s done by: (1) assigning a fixed IP address to the RPi (by default, it has a dynamic IP that’s assigned by the router); and (2) setting up port forwarding on the router so that port 443 (for https) is forwarded to that fixed IP. Once that’s been done, you should be able to access 76  Silicon Chip Having to remember your WAN IP is a hassle. Not only that but it can change if the modem/router is restarted. So if you want to be sure that you always have online access to your RPi’s web server, the answer is to use a DDNS service. DDNS stands for “Dynamic Domain Name Server” and it allows you to connect to your home network by using a hostname and domain name. It still makes the connection via your public IP (WAN) address but it no longer matters if this IP address changes and you don’t have to know (or remember) what the address is. The DDNS service will let you choose a hostname when you sign up. You can then browse to your RPi’s web server by using this hostname and the DDNS domain name. If your router supports your preferred DDNS, then you can use the router itself to update the DDNS with your WAN IP. Note, however, that the popular DynDNS service is no longer free, while No-IP now requires you to confirm your hostname every 30 days unless you sign up for the paid version. Duck DNS is a great free alternative and it only takes a few minutes to sign up. It probably won’t be supported by your router but there’s an easy answer to that problem – use the RPi itself to run a script to periodically update the Duck DNS server with your WAN (public) IP address. It’s all quite easy to do and is set out in detail on page 60 of the February 2016 issue. Having completed the set-up, check that you can browse to your RPi’s default web page using the hostname. For example, if you’re using Duck DNS, enter http://yourhostname.duckdns.org into your browser (replace “yourhostname” with your chosen name). Web page set-up The next step is to get Apache2 working with the Python 3 program that displays our web page with the relay control buttons. The program itself is called index. py and you’ll find it on the SILICON CHIP website zipped up inside RpiWiFiSwitchV1.zip. You have to download this file, unzip it and move it into the RPi’s /var/www/html folder. Begin by browsing to http://www.siliconchip.com.au using the RPi’s web browser. Now click Shop, select Software from the drop-list and left-click the RPiWiFiSwitch.zip file. The file will download into the /pi/Downloads folder after which you navigate to this folder, then right click the zip file to extract index.py. Before moving index.py, it’s a good idea to rename siliconchip.com.au You’ll Need These Parts Core parts The NO relay contacts are wired across the buttons on the garage remote as shown here. Remove the battery before soldering the wires. any existing index.py file in /var/www/html. That’s done by issuing the following commands: cd /var/www/html sudo mv index.py index.py.old The new index.py file can now be moved into /var/ www/html as follows: sudo mv /pi/Downloads/index.py /var/www/html You now need to give Apache2 permission to access the RPI’s GPIO pins, as follows: sudo adduser www-data gpio That’s it! – it should now work. Using a computer on the local network (or the RPi itself), browse to (for example) https://yourhostname.duckdns.org (or use your public IP address). Enter your user-name and password to log-in, then check that the relays on the RPi Relay Board respond when the various control buttons are clicked. If it works, test it out on your smart-phone. Note that you will have to zoom in on the buttons to make sure you touch the correct one. Retaining access to an existing web page What if you want to keep an existing index.py web page? For example, you may have previously set up your RPi’s web server so that you can monitor temperatures (see March 2016 issue) and you may want to maintain access to these measurements. In that case, it’s just a matter of renaming the newly unzipped index.py file for the garage doors before moving it. For example, you could rename the file to garage. py and then move this to /var/www/html. The web page for your temperature measurements can then be access­ ed as normal, while the garage door control buttons are accessed by browsing to https://yourhostname.duckdns. org/garage.py Wiring the remote This job couldn’t be easier; just wire a pair of leads across each button you wish to control and connect them to the NO & COM contacts of the corresponding relay. You will need to remove the remote’s PCB from its case and use a soldering iron with a fine tip to connect the wires. It’s a good idea to remove the battery before soldering, to prevent the remote from being damaged during this process. Once the leads have been attached, cut a couple of siliconchip.com.au 1 Raspberry Pi 3 Model B or Raspberry Pi 2 Model B computer module 1 Wi-Pi WiFi dongle (not necessary if you have a RPi 3 Model B, as these have onboard WiFi) 1 8-32GB microSD card (class 6 or class 10) . . . or purchase a pre-programmed microSD card from element14 or Wiltronics 1 5V power supply with USB to micro-USB cable (note: must be rated at 2.5A for RPi 3 Model B) 1 spare garage remote 1 Waveshare RPi Relay Board (order from AliExpress or Amazon) The parts required during set-up 1 USB keyboard and mouse (wireless units should work, provided they’re paired) 1 monitor with HDMI or DVI input 1 HDMI-HDMI or HDMI-DVI cable to suit monitor 1 microSD card reader Raspberry Pi starter packs Wiltronics has a number of Raspberry Pi starter packs – see www.wiltronics.com.au notches in one end of the case for the leads to exit and refit the PCB. If that’s not practical, install the PCB inside a separate case (perhaps with the RPi itself). If you don’t have a spare remote, you can buy one from a garage door specialist. You can buy these quite cheaply on eBay but if you take that approach, make sure it’s the right type to work with your garage door controller as many remotes look similar but operate differently. Another possibility is to simply connect the relay contacts across the manually-operated door control switch that’s mounted on the garage wall or even directly to the open/close terminals on the back of the motor control unit itself. Take security seriously Security is a serious issue here. You really don’t want someone to hack their way in and open or close your garage doors at will! So how secure is it? The answer is that your garage doors are about as secure as the password you chose for the RPi’s web server. Similarly, your camera (see below) will be about as secure as the strength of its password. Fortunately, there’s a fairly simple way to lock it down even further, to keep the bad guys out of your RPi’s web server. The answer is to install an intrusion software utility called “Fail2Ban”. This utility monitors the number of log-in attempts and if they exceed a preset number (say five), it bans the offending source IP address from making any further attempts for a set period (or even permanently). Fail2Ban is easy to install and configure. The accomNovember 2016  77 This screen grab shows the RPi’s web page as it appears on a PC. If a smartphone is used, the page is automatically zoomed. It’s a good idea to install a panning camera on the back wall of the garage so that you can check that the garage is empty before closing the door. panying panel titled “Keeping The Bad Guys Out” (reproduced from February 2016) has the details. You could also install a separate firewall on the RPi but since it normally sits behind your router’s firewall, this won’t normally be necessary. Once again, the accompanying panel has the details. Setting up an IP camera OK, now that the RPi’s web server and relay board are working correctly, the next step is to set up an IP camera to monitor the garage doors. If you don’t already have a suitable camera, the Jaycar TechView QC3834 and Altronics EasyN S9012 are good candidates. Setting up the camera to connect to your WiFi network is straightforward. It’s usually just a matter Exercise Caution Naturally, you should exercise a great deal of caution if you intend to close a garage door from a remote location. After all, you don’t want to close it on a family member who is out the front working in the garden, or collecting the mail, or who has just come home and is driving into the garage. To avoid problems like this, always check where each family member is before closing the door. It’s also a good idea to restrict usage to one smartphone only, to avoid potential conflicts. Setting up a panning camera so that you can monitor the whole inside garage area is also a good idea (eg, mount the camera high up on the back wall). That way, you can pan to ensure that your neighbour’s dog or a curious cat hasn’t wondered inside while the door was opened. Both the Jaycar TechView QC3834 and Altronics EasyN S9012 IP cameras can be panned and so are well suited to this role. 78  Silicon Chip of first plugging it into your router via a Cat5 cable, figuring out its IP address, then logging into the camera’s web interface (via a browser) and entering your WiFi network’s SSID (ie, the network name) and password. How do you figure out the camera’s IP address in order to access its web interface? Well, assuming your router has DHCP enabled, it will automatically allocate an IP address to the camera when it is plugged in, just as it does for other devices on the network. From there, you can quickly figure out the allocated IP address by trial and error. For example, if the router itself has an IP address of 192.168.0.1, then the camera might be on 192.168.0.2 or 192.168.0.3 (or higher), depending on which addresses have already been allocated to devices such as PCs, smart-phones and smart TVs, etc. To test an IP address, simply enter it along with the camera’s port number into the address bar of your web browser. The default port number (usually 80) will either be on a label on the camera’s body or listed in the supplied instructions. It must be separated from the IP address by a colon. For example, let’s say that the camera’s port number is 80 and you want to test an IP address of 192.168.0.7. It’s just a matter of entering 192.168.0.7:80 into your browser and pressing Enter. If it’s the correct IP, the camera’s web interface will immediately appear and you can log into it using the default user name (usually “admin”) and password (usually “admin” or left blank). Another way of determining the IP address is to log into your router’s web interface and check the DHCP client table or similar. In addition, some cameras such as the TechView QC3834 are supplied with a software utility called “IP Camera Tool”. Installing and running this on your PC will then list the camera’s IP and its port number. Double-clicking this will then bring up its web interface. Before actually entering the WiFi set-up details, be sure to change the camera’s default user name and password. A strong password is an absolute must if you don’t want others spying on you. You can also change the default port number if you wish. Disconnect the LAN cable and restart the camera after entering all the details. You will then be able to access the camera and view the video via the WiFi network. Viewing via the internet In most cases, an IP camera will be supplied with a unique DDNS hostname so that you can view it over the siliconchip.com.au Keeping The Bad Guys Out Opening port 443 on the router (to enable internet access to the web-server) is a potential security problem. That’s why it’s important to choose a strong password for the Apache2 authentication log-in. Fail2Ban Despite this, the web-server’s log-in prompt will soon attract brute force attempts to gain access by people running password dictionaries. There’s an easy way to defeat such attacks, though: limit the number of log-in attempts by using an intrusion detection software utility called “Fail2Ban”. Fail2Ban works by monitoring the logs generated by various services (such as Apache2). If there are too many failed log-in attempts, it then temporarily (or permanently) bans the offending IP from making further attempts. For example, it can be configured to allow three login attempts and if all are unsuccessful, ban the offending IP for 20 minutes, depending on the settings in the configuration file. In practice, Fail2Ban sets up a few simple iptable firewall rules (iptables is the utility used to configure Linux fire- walls). It then automatically alters these rules after the preset number of failed log-in attempts. By default, it monitors SSH (port 22) only but it’s just a matter of altering its configuration file to include other protocols such as HTTP (port 80) and HTTPS (port 443), as used by Apache2. An excellent guide on configuring Fail2Ban can be found at www.digitalocean. com/community/tutorials/how-to-protect-an-apache-server-with-fail2banon-ubuntu-14-04 It’s just a matter of following this to configure Fail2Ban so that, as well as SSH, it also protects the RPi’s Apache2 server (HTTP & HTTPS). Important points Note that you have to copy the default configuration file to “/etc/fail2ban/jail. local ”.You then edit this new file (it overrides the original configuration file) to set the “bantime”, the maximum number of tries (“maxretry”) and the “findtime” (the time period over which the retries are counted). The default bantime is 600 seconds but you can increase this (eg, to 1800 seconds) or enter a negative number to ban the offending IP forever. It’s then important to scroll down to internet. It’s just a matter of setting the camera up for WiFi access as described above, then entering the address shown on a label on the bottom of the camera into your browser, followed by a colon, then the port number. Alternatively, some cameras carry a Q-code on the base label and scanning this using a smartphone (with the necessary app installed) will take you straight to that address (you may have to manually enter the port number if you’ve changed it). If it works, then your router has inbuilt support for automatic port forwarding via UPnP (Universal Plug and Play) and that’s the end of the story. Of course, your IP camera must also support UPnP but just about all do. If it doesn’t work, check that UPnP hasn’t been disabled in the router. That said, not all routers support automatic port forwarding, even if they do have UPnP. In that case, you will have to assign a static IP address to your camera and manually set up the port forwarding in your router. A detailed explanation on how to do this is in “Setting Up An IP Camera For WiFi & Internet Access” in the March 2015 issue of SILICON CHIP. Once its working, install the relevant camera app on your smartphone and enter the connection details. These details include the DDNS hostname, the port number, your user name (ie, for the camera) and the password. You will then be able to fire up the app and view the video inside your garage. siliconchip.com.au the [apache] jail section and change to line enabled = false to enabled = true. Fail2Ban will then cover both http and https. Installing a firewall Unless you’ve opened up myriad ports on your router, a separate firewall on the RPi isn’t really necessary. However, if you’re a “belts’n’braces” type, try Uncomplicated Firewall (UFW) which is an easy-to-use iptables configuration utility. The following website has the basics on UFW’s installation and usage: www. digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufwon-ubuntu-14-04 Of course, all bets are off if you decide to add the RPi to your router’s DMZ (demilitarised zone). Placing it in the DMZ means that it cannot contact other devices on your internal LAN in the event that it’s compromised (it’s added to the DMZ by logging into your router and going to the DMZ set-up page). The downside is that all ports on the router will then be forwarded to the RPi, so it’s wide open. As a result, a firewall is then an absolute must. In practice, you would set up the firewall to initially block all incoming ports. You then create rules to open port 443 (for https) and any other ports required, eg, for SSH (secure shell) long-ins. Controlling Other Devices As well as controlling garage doors, you could also use the RPi to control other devices. For example, it could be used to pulse the remote of a remote-controlled mains power board. However, exercise caution as to the circumstances under which you remotely turn mains-powered devices on in this manner. Turning on an unattended device such as a heater or a lamp could lead to a fire, for example (and in any case, a heater should not be plugged into a power board). Because the relay outputs can be toggled, you can directly switch low-voltage devices (eg, LED lamps) on or off (up to about 24V DC or 15VAC). However, despite the fact that the relays are rated at 250VAC, you should keep mains voltages well away from your RPi set-up. Running mains wiring to the RPi’s relay board would be much too dangerous. If you do wish to switch mains voltages, use the RPi to control the remote of a remote-controlled mains switch or use a commercial WiFi switch, eg, from Bunnings – see https://www.bunnings.com.au/belkin-wemo-switch_ p4420346 In the unlikely event that the camera’s manufacturer doesn’t offer a DDNS service, use Duck DNS as explain­ SC ed earlier. November 2016  79