Blink an LED over the internet: the begginer’s low level approach

ledoth

In this article we continue our road to the IoT approached at a low level, or better, at bottom-up approach, that will be applied in the future to my UART interpreter. Here I will talk about how to drive an LED over the Internet. So as always I’m using Python libraries to get things done safely, quickly, but also make them useful under the knowledge point of view. So, if you are trying to do similar things, this can be an article that is not completely useless. And remember, if you can blink an LED, you can do whatever you want… This is the “Hello World!” of the basic IoT. Maybe even less.

But be aware, there are a lot of guides that allow you to do the job quickly. You are reading this because I am developing an hardware platform which works differently from most of ready-to-go solutions, and I usually need to develop my own application and if something become useful, I write about that, like in this article.

Let’s start

As a starting point, you have to understand what you need. Here, since I don’t have any ethernet/wifi adapter to be used by an MCU and considering that I may need some calculus power, I used the well trusted RaspberryPi B. I set it up with a basic Raspbian distro and configured it to use a static IP address local to my LAN. Forwarding the traffic from outside is made by the router connected to the internet.

If you start from scratch and don’t have the DHCP disabled and the RPi doesn’t have a fixed IP, you can connect it to the LAN and observe by looking at the router at what address is connected to. Then to access to the board once you know the IP, you should have the ssh daemon running, this is the default normally. In Windows, I use PuTTY to access to it.

Once entered in our RaspberryPi at its new address, we set a static IPv4 address (note that in the so called “IoT” stuff the IPv6 should be used, but for now it is not a big problem) to avoid checking the IP every times. Open the file /etc/network/interfaces, it should look like this:

auto lo
iface lo inet loopback
#uncomment to change loop address
#address <address>
#netmask <address>

auto eth0
iface eth0 inet static
address 192.168.1.5
netmask 255.255.255.0
#uncomment for use RPi as router
#network <address>
#broadcast <address>
gateway 192.168.1.1

where iface eth0 inet static matters, because in this way we assign a static local IP address w/out using the DHCP of the router. Remember to set the IP accordingly to the gateway, where in this case represents the address of my router. The netmask should be identical.

Restart the network typing on the console:

sudo /etc/init.d/networking restart

and may not work, in that case simply reboot the RPi. Now, every time you boot the Raspberry and connect it to the router, it should always have the address that you have choosen, in this example is the 192.168.1.5

The scripts

As usually, I wrote a script that should run on the RaspberryPi, called server and another client that you can run on whatever PC, smartphone which can interpret python commands. Those are derived from the same functions described in this article, and with a new one, fine_data(), to refine the data received by cutting out the number of byte attached at the head of the string prior to send the data. Be aware that the server implemented is not working like a real server, it is capable to handle only one connection at a time, because my application because I want it. It’s a kind of  be-or-not-to-be-server. Otherwise, the basic concept is that you need to put the server.accept() call in a loop and exploit multithreading. That is why servers are needing high parallelism and memory to allow parallel execution, instead of single thread performances.

Both scripts uses an infinite loop to interpret the data, and the client send to server whatever command is inserted from the user. The server itself should verifiy the command and decide what to do. So what’s new, now, is in the server, where thanks to the library GPIO, prepare and drive one pin of the RaspberryPi. Depending on what is received from client, the pin 3 of the RaspberryPi (in my case is model B, rev 2) can be set to high or low. The server reasponds to client according to the action taken with the send_sck(clientsocket, msg).

Something like this:

while 1:
cmd = 0
mex = receive_sck(clientsocket) # lettura comandi veri
try:
mex = fine_data(mex)
print(&amp;amp;amp;quot;Incoming data from client: &amp;amp;amp;quot; + mex)
if mex=='on':
msg = 'Led ON.'
msg = msg_len(msg)
send_sck(clientsocket, msg)
cmd = 1
GPIO.output(3, 1)
if mex=='off':
msg = 'Led OFF.'
msg = msg_len(msg)
send_sck(clientsocket, msg)
cmd = 1
GPIO.output(3, 0)

if mex=='q':
#print(&amp;amp;amp;quot;Incoming data from client: &amp;amp;amp;quot; + mex)
msg = &amp;amp;amp;quot;Server ended. Stay rock.&amp;amp;amp;quot;
cmd = 1
msg = msg_len(msg)
send_sck(clientsocket, msg)
GPIO.output(3, 0)
break;
except:
print(&amp;amp;amp;quot;Uncorrect format received&amp;amp;amp;quot;)

if cmd == 0: # is still zero
msg = 'Unrecognized command.'
msg = msg_len(msg)
send_sck(clientsocket, msg)

server.close()
print(&amp;amp;amp;quot;Server connection closed.&amp;amp;amp;quot;)

Note that this GPIO library “simply” interacts with hardware control registers of the BCM2835 by accessing the file /dev/mem, and since it is a system file you must run the server script as a root. In the server script you should locate the line below and set the address and port like this

server.bind(('192.168.1.5', 8000))

while in the client

client.connect(('192.168.1.5', 8000))

The server should have the internal LAN address. The internal port, 8000 in this case, is the one used inside the LAN by the server. At the moment in which you decide to access from outside, you should open a port (can be different if you want) on the router allowing it to redirect the packets toward the internal address:port, here 192.168.1.5:8000. For this capability, refer to your specific router manual. About the port, an high number (> 1024) usually do not provides standard services, so often conflicts are not encoutered.

The client.connect() must use the address of your ISP provider if you are outside the LAN, and the proper port opened on your router previously. Here are the same because I’m using the scripts inside my LAN, so no redirect is needed. Note that you can’t test the correctness of forwarding from inside the same LAN where the server resides. If you are in the same LAN, you can instead connect to localhost and run both scripts on the same machine.
There are tons of guides on emulate a free static public IP and I don’t want to load too much this presentation. And since I’ve not tried this method in first person, I will skip the static IP tricks for now.

You can download the scripts and start playing with them. I’ve remained quite short in descriptions because I want to arrive at the next part. 🙂
If you have questions, you can ask them in the comments, of course!

And finally…

The final result is a LED which is on whenever I write “on” and viceversa if “off”. Connect using an SSH connection to the board and start the script “server.py” by typing

sudo python3 server.py

because I wrote it in Python3. If there is an error about an already used port:

[Errno : 98] Message Address already in use

it’s normal, maybe there is an open connection or if you are already ran the script, maybe the client has not closed the connection. In that case you can change the port: after few minutes that previous port will became again available.

I remotely driven the GPIO 3 (SCL) pin. Be careful to follow the guidelines  to avoid to ruin the SoC pins, and remember that those pins can output up to 50mA. See image below:

The setup is very trivial, just the GPIO 3 with a series resistor connected to the LED. This useless picture is posted “just for fun”. 🙂

ledThe server script has a console allowing to understand what is going on, while the client works as always in a console style. Whenever the LED is in the wanted state, the server confirm that by printing on screen. The use of the screen can be avoided if not needed, because the response message is sent to the client, as you can see.

serverThe client, for now, requires the user intervention, so the screen is needed to allow writing commands in console, as below.

client

 Downloads

Client:  https://www.dropbox.com/s/xzxoirvgg2hwm2u/client.py?dl=0

Server: https://www.dropbox.com/s/o6b0klsoqcymch8/server.py?dl=0