<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"><title>The Hub of Heliopolis - IoT</title><link href="https://p403n1x87.github.io/" rel="alternate"/><link href="https://p403n1x87.github.io/feeds/iot.atom.xml" rel="self"/><id>https://p403n1x87.github.io/</id><updated>2018-03-03T22:49:00+01:00</updated><subtitle>notes on technology and my experiments with it.</subtitle><entry><title>IoT with WebSockets and Python's AsyncIO</title><link href="https://p403n1x87.github.io/iot-with-websockets-and-pythons-asyncio.html" rel="alternate"/><published>2018-03-03T22:49:00+01:00</published><updated>2018-03-03T22:49:00+01:00</updated><author><name>Gabriele N. Tornetta</name></author><id>tag:p403n1x87.github.io,2018-03-03:/iot-with-websockets-and-pythons-asyncio.html</id><summary type="html">&lt;p&gt;After &lt;a href="{filename}2017-07-31-intro-to-iot.md"&gt;a gentle introduction to the concept of IoT&lt;/a&gt; and what it entails, we take a dive into WebSockets and Asynchronous I/O in Python to explore other ways of controlling devices over a network. This post uses a simple two LED circuit to introduce WebSockets, and how to use them in Python together with the &lt;code&gt;asyncio&lt;/code&gt; module.&lt;/p&gt;</summary><content type="html">
&lt;h1 id="introduction"&gt;Introduction&lt;a class="headerlink" href="#introduction" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;In this post, we will get back to the topic of IoT to introduce two new
technologies by example: &lt;strong&gt;WebSockets&lt;/strong&gt; and &lt;strong&gt;Asynchronous I/O&lt;/strong&gt; in Python. The
project that will allow us to explore them is a simple system of two LEDs that
we will control with the gravity sensor of an Android device via a Raspberry Pi
over a network.&lt;/p&gt;
&lt;p&gt;The post is divided into two parts. The first one is theoretical in nature and
will cover the essential technical details of the two main subjects, that is
&lt;em&gt;WebSockets&lt;/em&gt; and Python's &lt;em&gt;asyncio&lt;/em&gt;. In the second part we will have a look at
the circuit that we are going to control over the network and discuss the server
and client code.&lt;/p&gt;
&lt;p&gt;But before we dive into the study of the topics of this post, it is perhaps best
to first have a high level view of how all the pieces fit together, thus
motivating the choices of technologies mentioned above. The idea of the project
stems from the following scenario: suppose you want to build a device that can
be controlled over the network, e.g. an hand-held device like a phone. As we
have seen in &lt;a href="https://p403n1x87.github.io/a-gentle-introduction-to-iot.html"&gt;a previous post&lt;/a&gt;, one way of
achieving this is by using a single-board computer like a Raspberry Pi and
control it via a web server.&lt;/p&gt;
&lt;p&gt;Now, what if you wanted more control over the connection method to the device,
and perhaps a bi-directional channel to let data from, e.g. sensors on the
device, to flow upstream to the controlling device? An elegant way of achieving
this goal these days is with &lt;strong&gt;WebSockets&lt;/strong&gt;, which allow (full) duplex
communication between pairs of connected devices. So, for instance, we could
have a WebSocket server running on a Raspberry Pi, and have a native application
on an Android device to run a WebSocket client. Control commands can then flow
from the Android device to the single-board computer, while the server can feed
data from any sensors that the device is equipped with back to the client, with
just a single connection.&lt;/p&gt;
&lt;p&gt;The code samples that we will look at towards the end of the post implement a
Python WebSocket server that will run on, e.g., a Raspberry Pi, and a native
Android application that will act as a WebSocket client to control a pair of
LEDs mounted on a breadboard. The data that we will transfer from the Android
device to our circuit is coming from a gravity sensor, so that when we twist the
hand-held device clockwise or anti-clockwise, a different LED will turn on.
Furthermore, the brightness will depend on how much the device is tilted.&lt;/p&gt;
&lt;p&gt;So, read on to find out more!&lt;/p&gt;
&lt;h1 id="connecting-devices-over-a-network-websockets"&gt;Connecting Devices over a Network: WebSockets&lt;a class="headerlink" href="#connecting-devices-over-a-network-websockets" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;In &lt;a href="https://p403n1x87.github.io/a-gentle-introduction-to-iot.html"&gt;A Gentle Introduction to IoT&lt;/a&gt;, we saw
how to control a single LED over a network by running a web server hosting the
controlling web application. This was a simple web page that displayed a button
that not only showed the current state of the LED, but allowed to control it by
turning it on or off. All we needed to do was to point a web browser to the web
server running on the Raspberry Pi and play around with the only web page on it.&lt;/p&gt;
&lt;p&gt;There might be situations where we are not happy with a web server, but we
actually want more control over the way devices connect with each other. In a
simple client-server relationship, surely TCP/IP sockets spring to mind, but
what if we want to allow for data to flow in both directions?&lt;/p&gt;
&lt;p&gt;Contrary to ordinary sockets, WebSockets offer a full-duplex communication
channel over a single TCP connection. They are compatible with the HTTP
protocol, but make use of their own protocol (the &lt;em&gt;WebSocket&lt;/em&gt; protocol), which
is switched to by including an HTTP Upgrade header in the HTTP handshake. By
default, they are supposed to operate on the standard HTTP ports (80 for HTTP
and 443 for secured HTTP), but a different one can be used for custom use, as we
will see in our example. The advantage over any other solutions is that
WebSockets have been designed to allow for fast bi-directional communication
between client and server via an TCP connection that is kept open until manually
closed (or dropped for other reasons), but without the overheads of HTTP
headers.&lt;/p&gt;
&lt;p&gt;By design, WebSockets are then the perfect tool for exchanging short &lt;em&gt;messages&lt;/em&gt;
between devices. As to what kind of messages we can send back and forth, we will
see that we can either send &lt;em&gt;text&lt;/em&gt; messages, or raw &lt;em&gt;binary&lt;/em&gt; data, by either
operating the WebSocket with &lt;em&gt;text&lt;/em&gt; or &lt;em&gt;binary&lt;/em&gt; frames.&lt;/p&gt;
&lt;p&gt;Having justified the use of WebSockets for our project, we now have to motivate
the use of the other mentioned technology: &lt;code&gt;asyncio&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Like in &lt;a href="https://p403n1x87.github.io/a-gentle-introduction-to-iot.html"&gt;A Gentle Introduction to IoT&lt;/a&gt;,
the choice of Python is motivated by the use of the Raspberry Pi. In Python,
WebSocket support is provided by the
&lt;a href="https://pypi.python.org/pypi/websockets"&gt;&lt;code&gt;websockets&lt;/code&gt;&lt;/a&gt; module, which is built
on top of &lt;a href="https://docs.python.org/3/library/asyncio.html"&gt;&lt;code&gt;asyncio&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Here is where we encounter the first constraint though, since &lt;code&gt;asyncio&lt;/code&gt; was
introduced in Python 3.4. We then have to ensure that we are using a version of
Python greater than or at least equal to 3.4. But our coding can also vary based
on whether we are using Python 3.5 and later. That is because this version of
Python introduces the &lt;code&gt;async&lt;/code&gt; and &lt;code&gt;await&lt;/code&gt; syntax for natively defining
coroutines (&lt;a href="https://www.python.org/dev/peps/pep-0492/"&gt;PEP 492&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;In the last part of this post we will have a look at Python code samples written
with the standard &lt;code&gt;asyncio&lt;/code&gt; syntax, as well as the new one introduced by PEP
492. For now, we shall have a quick overview of the new features that are
brought to Python 3 by the &lt;code&gt;asyncio&lt;/code&gt; module to better familiarise with it and
its usage.&lt;/p&gt;
&lt;h2 id="coroutines"&gt;Coroutines&lt;a class="headerlink" href="#coroutines" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;I believe that the best way to understand &lt;code&gt;asyncio&lt;/code&gt; is to first look at the
basic concepts involved and recall the notion of &lt;code&gt;coroutine&lt;/code&gt;. In Python we have
the concept of &lt;em&gt;Generators&lt;/em&gt; since version 2.2. Generators look and feel like
normal functions, but rather than &lt;em&gt;returning&lt;/em&gt; a value, they &lt;em&gt;yield&lt;/em&gt; one, and are
normally used in loops to provide iterators.&lt;/p&gt;
&lt;p&gt;The typical scenario where you'd want to opt for a generator rather than a
function is when you have to keep track of some state in between the different
values returned. A simple example is a generator that generates the first $n$
Fibonacci numbers:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt;

    &lt;span class="k"&gt;yield&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt;

    &lt;span class="k"&gt;yield&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt;

    &lt;span class="n"&gt;a0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;

    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;a2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a0&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;a1&lt;/span&gt;
        &lt;span class="k"&gt;yield&lt;/span&gt; &lt;span class="n"&gt;a2&lt;/span&gt;
        &lt;span class="n"&gt;a0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a2&lt;/span&gt;
        &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;If $n=0$, the generator doesn't yield any number and we can then return. When
$n=1$, the generator must yield the first Fibonacci number only, which is 0, and
so on. The difference between &lt;code&gt;return&lt;/code&gt; and &lt;code&gt;yield&lt;/code&gt; is that the former terminates
the iteration, while the latter allows it to continue. To better understand what
is going on here, observe that a call to &lt;code&gt;fibonacci&lt;/code&gt;, like &lt;code&gt;f = fibonacci(10)&lt;/code&gt;
doesn't return a Fibonacci number (you might at first expect this to return the
first Fibonacci number), but a &lt;em&gt;generator object&lt;/em&gt; instead, that is, something
that we can use with a &lt;code&gt;for&lt;/code&gt; loop, or any function that expects an iterable
object, like &lt;code&gt;sum&lt;/code&gt;. The first two Fibonacci numbers can then be generated with&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="c1"&gt;# Expected output&lt;/span&gt;
&lt;span class="c1"&gt;# &amp;lt;generator object fibonacci at 0x7f2e0940baf0&amp;gt;&lt;/span&gt;
&lt;span class="c1"&gt;# 0&lt;/span&gt;
&lt;span class="c1"&gt;# 1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;but if we now try to print yet another Fibonacci number, we get a
&lt;code&gt;StopIteration&lt;/code&gt; exception, which signals that the generator has returned and
that there are no more values to be generated:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="c1"&gt;# Expected output&lt;/span&gt;
&lt;span class="c1"&gt;# Traceback (most recent call last):&lt;/span&gt;
&lt;span class="c1"&gt;#   File "&amp;lt;stdin&amp;gt;", line 5, in &amp;lt;module&amp;gt;&lt;/span&gt;
&lt;span class="c1"&gt;#     print(next(f))&lt;/span&gt;
&lt;span class="c1"&gt;#&lt;/span&gt;
&lt;span class="c1"&gt;# StopIteration&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The following code snippet illustrates the use of a generator with a &lt;code&gt;for&lt;/code&gt; loop&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;test_cases&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;test_cases&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Test case: n = &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;I am omitting the expected output to avoid cluttering the page, but it should be
quite clear what the above code is supposed to do. To produce a more compact
result we can do something like&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;sfibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="k"&gt;yield&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;test_cases&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Test case: n = &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;" "&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sfibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;)))&lt;/span&gt;

&lt;span class="c1"&gt;# Expected output:&lt;/span&gt;
&lt;span class="c1"&gt;#&lt;/span&gt;
&lt;span class="c1"&gt;# Test case: n = 0&lt;/span&gt;
&lt;span class="c1"&gt;#&lt;/span&gt;
&lt;span class="c1"&gt;# Test case: n = 1&lt;/span&gt;
&lt;span class="c1"&gt;# 0&lt;/span&gt;
&lt;span class="c1"&gt;# Test case: n = 2&lt;/span&gt;
&lt;span class="c1"&gt;# 0 1&lt;/span&gt;
&lt;span class="c1"&gt;# Test case: n = 3&lt;/span&gt;
&lt;span class="c1"&gt;# 0 1 1&lt;/span&gt;
&lt;span class="c1"&gt;# Test case: n = 10&lt;/span&gt;
&lt;span class="c1"&gt;# 0 1 1 2 3 5 8 13 21 34&lt;/span&gt;
&lt;span class="c1"&gt;# Test case: n = 20&lt;/span&gt;
&lt;span class="c1"&gt;# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;which also shows how to construct a generator out of another generator.&lt;/p&gt;
&lt;p&gt;From the above example we deduce that the &lt;code&gt;yield&lt;/code&gt; keyword is generating a value
while also "&lt;em&gt;pausing&lt;/em&gt;" the execution of the function, until another value is
requested from it. In this case, the execution resumes from the instruction that
comes soon after the &lt;code&gt;yield&lt;/code&gt;, with all the values of local variables (the
&lt;em&gt;state&lt;/em&gt;) preserved.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Generators&lt;/em&gt; are also known as &lt;em&gt;semicoroutine&lt;/em&gt;, and this leads us to talk about
&lt;em&gt;coroutines&lt;/em&gt;. This is a more general concept, because it encompasses those code
elements that not only pass a value to the caller, but also receive and process
a value passed to them by another code element (e.g. a generator, or another
coroutine). This definition looks a bit circular, and this is due to the fact
that, with coroutines, the relation is not of caller-callee, but symmetric. In
more concrete terms, we are talking about functions that can retain a state in
between invocations, and that can call to other functions, suspending and
resuming execution from certain points of the code.&lt;/p&gt;
&lt;p&gt;Starting with Python 2.5, coroutines have become an integral part of the
language. They can be easily constructed with &lt;code&gt;yield&lt;/code&gt;, which has been turned
into an &lt;em&gt;expression&lt;/em&gt;. The value &lt;code&gt;yields&lt;/code&gt; evaluates to is passed to the coroutine
with a call to &lt;code&gt;send&lt;/code&gt; on the generator, like so&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;coroutine&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;text&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;yield&lt;/span&gt;
        &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"#&lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt; : &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="n"&gt;coro&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;coroutine&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;coro&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;coro&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;coro&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"World"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# Expected output&lt;/span&gt;
&lt;span class="c1"&gt;# #1 : Hello&lt;/span&gt;
&lt;span class="c1"&gt;# #2 : World&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;If you look to code like the above for the first time, you might be wondering
why I have included a call to &lt;code&gt;next&lt;/code&gt;. Remember from our discussion on generators
that, contrary to normal functions, a call to &lt;code&gt;coroutine&lt;/code&gt; returns a generator
object and not the first generated value. After creation, a coroutine needs to
be &lt;em&gt;primed&lt;/em&gt;, that is it needs to be started so that it can execute its code
until the first occurrence of the &lt;code&gt;yield&lt;/code&gt; expression. The coroutine then halts
and waits for values to be sent to it. In Python, there are two equivalent ways
of priming a coroutine: either call &lt;code&gt;next&lt;/code&gt;, as we have done in the code above,
or send it a &lt;code&gt;None&lt;/code&gt; with &lt;code&gt;coro.send(None)&lt;/code&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Since it is quite easy to forget to prime a coroutine, a good idea is to
define a decorator, e.g. &lt;code&gt;@coroutine&lt;/code&gt; that creates, primes and returns a
coroutine.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;If you want to know more about coroutines, I recommend that you have a look at
David Beazley's &lt;a href="http://www.dabeaz.com/coroutines/"&gt;A Curious Course on Coroutines and
Concurrency&lt;/a&gt;. Here, I have just stated the
essential details that we are going to need for our project. These should be
enough to convince you that, with coroutines in Python we can implement
single-threaded concurrency, which offer an ideal ground for asynchronous I/O
operations, without the overhead of many context switches between different
threads.&lt;/p&gt;
&lt;h2 id="the-asyncio-module"&gt;The &lt;code&gt;asyncio&lt;/code&gt; module&lt;a class="headerlink" href="#the-asyncio-module" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;If you have ever done any sort of I/O before, like reading from/writing to a
file, or creating a socket and waiting for a connection etc... you will surely
know that most of the I/O operations are blocking. For example, if you are
trying to read from a file descriptor by making a &lt;code&gt;SYS_READ&lt;/code&gt; system call, your
code will hand control over to the OS until your request can be honoured. The
normal execution flow then resumes.&lt;/p&gt;
&lt;p&gt;The problem with this wait is that, in most cases, you don't know when there
will be enough data available from the file descriptor to read. Your application
then halts while it might be doing something useful instead.&lt;/p&gt;
&lt;p&gt;The typical workaround is to poll the file descriptor periodically, and only
read from it when data is actually available. As you can easily imagine, the
solutions come in different patterns, and every time you have to deal with this
there is some boilerplate code that you would have to write. This amounts to
writing your event loop to cycle through your tasks, which include I/O polling.
Wouldn't it be nice if we were provided with such boilerplate code encapsulated
in a module that we can use whenever we need to perform asynchronous I/O
operations?&lt;/p&gt;
&lt;p&gt;This must be what the people behind &lt;code&gt;asyncio&lt;/code&gt; must have thought, and that's why
the essential element that this Python module offers is an &lt;strong&gt;event loop&lt;/strong&gt;. This
is designed to register and schedule &lt;strong&gt;Tasks&lt;/strong&gt; which, with just a few words, can
be described as &lt;em&gt;objects decorating coroutines&lt;/em&gt; (hence, in practice, they are
coroutines). Some of these tasks might involve I/O operations, and some of these
operations might be blocking. By continuously polling for the I/O status of file
descriptors, sockets etc..., &lt;code&gt;asyncio&lt;/code&gt; allows you to write single-threaded
concurrent code that performs I/O.&lt;/p&gt;
&lt;p&gt;In this post, we are interested in working with WebSockets, as as an example of
what we have just seen we can play around with some WebSocket servers and
clients. In Python, we can make use of the &lt;code&gt;websockets&lt;/code&gt; modules, which builds
its functionalities on top of &lt;code&gt;asyncio&lt;/code&gt;. The &lt;a href="https://pypi.python.org/pypi/websockets"&gt;Getting
Started&lt;/a&gt; page on PyPI shows how simple
it is to create a a WebSocket client, and an echo server to test it. The
following examples are based on them, but with just some slight modifications,
and a twist: the client sends a string read from STDIN and the echo server
reverses it.&lt;/p&gt;
&lt;p&gt;So here is the server code&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="ch"&gt;#!/usr/bin/env python3&lt;/span&gt;

&lt;span class="c1"&gt;# Echo server. Will reverse everything we throw at it.&lt;/span&gt;

&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;asyncio&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;websockets&lt;/span&gt;

&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;echo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;[::&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

&lt;span class="n"&gt;loop&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_event_loop&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;loop&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;run_until_complete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;websockets&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;serve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;echo&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'localhost'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;8765&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="n"&gt;loop&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;run_forever&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;and here is the client code&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="ch"&gt;#!/usr/bin/env python3&lt;/span&gt;

&lt;span class="c1"&gt;# Client. Sends stuff from STDIN to the server.&lt;/span&gt;

&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;asyncio&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;websockets&lt;/span&gt;

&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;hello&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;uri&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;websockets&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;connect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;uri&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello world!"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;input&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;

&lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_event_loop&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;run_until_complete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hello&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'ws://localhost:8765'&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;And that's where we make our first encounter with the new &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt;
keywords, introduced by the already cited PEP 492. The new syntax &lt;code&gt;async def&lt;/code&gt; is
used to declare a &lt;em&gt;native coroutine&lt;/em&gt; in Python 3.5 and later versions. Perhaps
more interesting are &lt;code&gt;async with&lt;/code&gt; and &lt;code&gt;async for&lt;/code&gt;. The former introduces native
asynchronous context managers for classes that define the new magic methods
&lt;code&gt;__aenter__&lt;/code&gt; and &lt;code&gt;__aexit__&lt;/code&gt;, but apart from this, its usage is analogous to the
synchronous counterpart &lt;code&gt;with&lt;/code&gt;. The new syntax &lt;code&gt;async for&lt;/code&gt; is used to consume
asynchronous iterable, i.e. instances of classes that implement the &lt;code&gt;__aiter__&lt;/code&gt;
magic method. When the &lt;code&gt;await&lt;/code&gt; keyword is on its own, it defines an expression
that execute the coroutine it appears in to execute the one passed as its
argument until it completes. In the case of the code above, we just wait for the
&lt;code&gt;websocket&lt;/code&gt; object to complete the task of sending the data.&lt;/p&gt;
&lt;p&gt;After the above discussion, the code for the client application should be quite
clear. The first call to &lt;code&gt;websocket.send&lt;/code&gt; is used to &lt;em&gt;prime&lt;/em&gt; the socket, so that
&lt;code&gt;async for message in websocket&lt;/code&gt; won't hang indefinitely, waiting for something
to show up on the socket's reading end.&lt;/p&gt;
&lt;p&gt;Before we look at how to rewrite the above code snippets for Python 3.4, where
we do not have native coroutines, I would like to briefly comment on the last
two lines of code of the server application. The first time I came across that
code, they gave me a bit of thinking as to why we need to call
&lt;code&gt;run_until_complete&lt;/code&gt; and &lt;code&gt;run_forever&lt;/code&gt;. Wouldn't the former alone suffice? If
you recall our discussion about blocking I/O operations and the necessity of
constantly polling in order not to halt the execution of our application, you
realise that the call to &lt;code&gt;run_until_complete&lt;/code&gt; will register the socket with the
I/O polling task. Hence, apart from this task, we have nothing else running, and
if we do not start the event loop, the newly created socket won't be checked and
the application simply terminates. The last line is there to ensure that we keep
monitoring the socket for new incoming connections. When a client connects, a
new task is scheduled to serve the connection with the passed handler, which
must be a coroutine. This can be verified by peeking at the source code of both
&lt;a href="https://github.com/python/cpython/tree/a19fb3c6aaa7632410d1d9dcb395d7101d124da4/Lib/asyncio"&gt;&lt;code&gt;asyncio&lt;/code&gt;&lt;/a&gt;
and &lt;a href="https://github.com/aaugustin/websockets"&gt;&lt;code&gt;websockets&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;And now to the Python 3.4 version of the above code snippets. There are a few
rule of thumb that we can use to convert from 3.5 and later to 3.4, where we
don't have &lt;code&gt;await&lt;/code&gt; and &lt;code&gt;async&lt;/code&gt;. The first is the use of the decorator
&lt;code&gt;@asyncio.coroutine&lt;/code&gt; instead of &lt;code&gt;async def&lt;/code&gt;. The situation is a bit more
complicated for &lt;code&gt;async with&lt;/code&gt;, which requires a replacement for &lt;code&gt;await&lt;/code&gt;, which is
&lt;code&gt;yield from&lt;/code&gt;. The latter is substantially equivalent to&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;foo&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="k"&gt;yield&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;    &lt;span class="c1"&gt;# Same as: yield from foo()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;With this in mind, &lt;code&gt;async with&lt;/code&gt; can be coded with a more traditional &lt;code&gt;try ...
finally&lt;/code&gt; block as&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# async with coro() as foo:&lt;/span&gt;
&lt;span class="c1"&gt;#     # &amp;lt;code&amp;gt;&lt;/span&gt;
&lt;span class="c1"&gt;#     pass&lt;/span&gt;
&lt;span class="n"&gt;foo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="n"&gt;coro&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="c1"&gt;# &amp;lt;code&amp;gt;&lt;/span&gt;
    &lt;span class="k"&gt;pass&lt;/span&gt;
&lt;span class="k"&gt;finally&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="c1"&gt;# Whatever coro().__aexit__() would have done.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The &lt;code&gt;async for&lt;/code&gt; loop would translate to something like the following&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# async for foo in bar():&lt;/span&gt;
&lt;span class="c1"&gt;#     # &amp;lt;code&amp;gt;&lt;/span&gt;
&lt;span class="c1"&gt;#     pass&lt;/span&gt;
&lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;foo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="n"&gt;bar&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="fm"&gt;__anext__&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="c1"&gt;# &amp;lt;code&amp;gt;&lt;/span&gt;
&lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="ne"&gt;StopAsyncIteration&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This coding is not strict, since you could, or you might have to replace the
code of &lt;code&gt;bar().__anext__()&lt;/code&gt; with the actual coding inside this coroutine. This
is the case for the code that we are about to see, in which we perform the above
translations. The server code for Python 3.4 is the following&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="ch"&gt;#!/usr/bin/env python3&lt;/span&gt;

&lt;span class="c1"&gt;# Echo server. Will reverse everything we throw at it.&lt;/span&gt;
&lt;span class="c1"&gt;# For Python 3.4&lt;/span&gt;

&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;asyncio&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;websockets&lt;/span&gt;

&lt;span class="nd"&gt;@asyncio&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;coroutine&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;echo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;[::&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

&lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_event_loop&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;run_until_complete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;websockets&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;serve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;echo&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'localhost'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;8765&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_event_loop&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;run_forever&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;while the client code now looks like this&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="ch"&gt;#!/usr/bin/env python3&lt;/span&gt;

&lt;span class="c1"&gt;# Client. Sends stuff from STDIN to the server.&lt;/span&gt;
&lt;span class="c1"&gt;# For Python 3.4&lt;/span&gt;

&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;asyncio&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;websockets&lt;/span&gt;

&lt;span class="nd"&gt;@asyncio&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;coroutine&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;hello&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;uri&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;websocket&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="n"&gt;websockets&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;connect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;uri&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello world!"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;yield from&lt;/span&gt;  &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;input&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
    &lt;span class="k"&gt;finally&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;close&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_event_loop&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;run_until_complete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hello&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'ws://localhost:8765'&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Note how to execute a native coroutine, or one decorated with
&lt;code&gt;@asyncio.coroutine&lt;/code&gt; in Python 3.4, needs to be executed by an event loop from
the &lt;code&gt;asyncio&lt;/code&gt; module.&lt;/p&gt;
&lt;h1 id="setting-things-up"&gt;Setting Things Up&lt;a class="headerlink" href="#setting-things-up" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;We shall now present the circuit that makes up the device that we want to
control over the network, and both the server and client code that will allow us
to use the gravity sensor of an Android device to operate it.&lt;/p&gt;
&lt;h2 id="the-circuitry"&gt;The Circuitry&lt;a class="headerlink" href="#the-circuitry" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;This part of the post will be brief, because we are going to recycle part of the
previous post on IoT A Gentle Introduction to IoT. In fact, we are going to
double it up by making a circuit with two LEDs, each one following the same
design in the just mentioned post. The idea is to turn either one or the other
on, depending on the rotation angle of our Android device. For example, if we
tilt our device to the right, the green LED will become brighter, while when we
tilt it to the left, the red LED will become brighter.&lt;/p&gt;
&lt;p&gt;So, based on the knowledge acquired with the previous post on IoT, the circuit
that we want to build will look like this.&lt;/p&gt;
&lt;p&gt;&lt;a href="https://p403n1x87.github.io/images/ws_asyncio/ws_asyncio_bb.png" rel="noopener" target="_blank"&gt;&lt;img alt="Double LED configuration" src="https://p403n1x87.github.io/images/ws_asyncio/ws_asyncio_bb.png"/&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;For this project I am using a Raspberry Pi 3 Model B. As you can see from the
picture above, we need two LEDs, preferably of different colours, e.g. green and
red, and two 220 Ω resistors. The green LED will be controlled via the BCM 18
(8) pin (green jumper wire), while the red one is controlled via the BCM 5 (29)
pin (red jumper wire) of the Raspberry Pi. The black jumper wires indicate a
connection on a ground pin.&lt;/p&gt;
&lt;h2 id="the-server-code"&gt;The Server Code&lt;a class="headerlink" href="#the-server-code" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The server code will run on the Raspberry Pi and will open a WebSocket server,
listening for connection requests. At the moment of writing, Raspbian Jesse has
Python 3.4.2 in its repository, so that we cannot benefit of the native Python
coroutine offered by Python 3.5, unless we install this version manually.&lt;/p&gt;
&lt;p&gt;All the server code can be found inside the
&lt;a href="https://github.com/P403n1x87/iot/tree/master/gravity_led/server"&gt;gravity_led/server&lt;/a&gt;
folder of the &lt;a href="https://github.com/P403n1x87/iot"&gt;iot&lt;/a&gt; repository. Due to its
length I will refrain from embedding it on this post, but I will comment on the
essential aspects.&lt;/p&gt;
&lt;p&gt;The code is based on an abstract WebSocket Server class, &lt;code&gt;WSServer&lt;/code&gt;, contained
in
&lt;a href="https://github.com/P403n1x87/iot/blob/master/gravity_led/server/lib/wss.py"&gt;lib/wss.py&lt;/a&gt;.
An actual WebSocket server has to inherit from this class and implement the
&lt;code&gt;handler&lt;/code&gt; method, which is the one that bootstraps the logic of the server
application. This will be called as soon as the WebSocket server starts serving
connection requests.&lt;/p&gt;
&lt;p&gt;On creation, we can specify the address and port the server is to listen on, as
well as a possible limit on the number of simultaneous connections that the
server is allowed to serve. Why would such a limit be ever necessary? The reason
is that, in this particular example, we only have one device, and this can only
be controlled by one client at a time. It makes no sense to accept more than one
connection. By setting the limit to 1, we then prevent other clients from
connecting and finding out that the device is already being controlled by
another client. For the way it is implemented though, the class is flexible
enough to allow changing this limit at run-time with a call to the
&lt;code&gt;set_server_limit&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;After instantiation, we can run the server with a call to the &lt;code&gt;start&lt;/code&gt; method,
and we can check whether it is running at any time with &lt;code&gt;is_running&lt;/code&gt;. Most of
the code in the former method provides logging information and a graceful
shutdown when the user presses Ctrl+C to halt the server.&lt;/p&gt;
&lt;p&gt;The code contained in
&lt;a href="https://github.com/P403n1x87/iot/blob/master/gravity_led/server/main.py"&gt;main.py&lt;/a&gt;
is used to bootstrap the class &lt;code&gt;GyroListener&lt;/code&gt; contained in
&lt;a href="https://github.com/P403n1x87/iot/blob/master/gravity_led/server/gyro_listener.py"&gt;gyro_listener.py&lt;/a&gt;,
which holds the actual logic of the server. As you can see, all that we have to
do is inherit from &lt;code&gt;WSServer&lt;/code&gt; and implement the &lt;code&gt;handler&lt;/code&gt; coroutine, as shown
here.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="nd"&gt;@asyncio&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;coroutine&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;handler&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;conn_id&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;logger&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;info&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Connection ID &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt; established [path &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;]"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;conn_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

    &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;setmode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;BOARD&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;setup&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;CHR&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;OUT&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;setup&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;CHL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;OUT&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;pr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;PWM&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;CHR&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;FREQ&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;pl&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;PWM&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;CHL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;FREQ&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;pr&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;pl&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;is_running&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;gyro_data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="n"&gt;websocket&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="n"&gt;g&lt;/span&gt;         &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;gyro_data&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;split&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="n"&gt;val&lt;/span&gt;       &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]))&lt;/span&gt;

            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;logger&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;debug&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Received datum &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;pr&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ChangeDutyCycle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;pl&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ChangeDutyCycle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;pr&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ChangeDutyCycle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;pl&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ChangeDutyCycle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="n"&gt;websockets&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exceptions&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ConnectionClosed&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;logger&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;info&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Connection ID &lt;/span&gt;&lt;span class="si"&gt;{}&lt;/span&gt;&lt;span class="s2"&gt; closed."&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;conn_id&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
            &lt;span class="n"&gt;pr&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stop&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="k"&gt;break&lt;/span&gt;

    &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;cleanup&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here we initialise the Pi's GPIO and start listening to data over the socket
until the server is running or the connection is closed by the client. The two
pins that we have chosen to use to control the LEDs (&lt;code&gt;CHR&lt;/code&gt; and &lt;code&gt;CHL&lt;/code&gt;) are set on
the PWM (Pulse Width Modulation) mode so that we can control the brightness: the
more the Android device is tilted in one direction, the brighter the LED for
that direction.&lt;/p&gt;
&lt;p&gt;Here we also notice the "&lt;em&gt;contract&lt;/em&gt;" between the server and the client: the
latter will send the three coordinates of the gravity sensor as a
space-separated list of three floating point values. The server will split this
string and use the second component (the &lt;em&gt;y&lt;/em&gt;-axis of the gravity sensor) to
control the LEDs. When the value is positive the LED on the &lt;code&gt;CHR&lt;/code&gt; pin will turn
on, with a duty cycle proportional to the value passed by the client; when the
value is negative the LED on the &lt;code&gt;CHL&lt;/code&gt; pin will start to turn on.&lt;/p&gt;
&lt;p&gt;To launch the server, run &lt;code&gt;main.py&lt;/code&gt; and pass the IPv4 address and a port number,
for example&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;python3&lt;span class="w"&gt; &lt;/span&gt;main.py&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="m"&gt;0&lt;/span&gt;.0.0.0&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="m"&gt;5678&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;to listen on &lt;em&gt;any&lt;/em&gt; IP address on the Raspberry Pi and accept connections from everywhere.&lt;/p&gt;
&lt;h2 id="the-client-code"&gt;The Client Code&lt;a class="headerlink" href="#the-client-code" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;For the client, we are going to develop a minimalist Android application, with
the same project structure that we have encountered in the previous post on
&lt;a href="https://p403n1x87.github.io/android-development-from-the-command-line.html"&gt;Android Development from the Command
Line&lt;/a&gt;. Again, the code is quite extensive,
but you can find it in the
&lt;a href="https://github.com/P403n1x87/iot/tree/master/gravity_led/client"&gt;gravity_iot/client&lt;/a&gt;
folder. Apart from the minimal Android project setup, with the
&lt;code&gt;AndroidManifest.xml&lt;/code&gt; and the resource files for the UI, all that we need is a
single activity where we can specify the IP address and the port of the server
to connect to, and a toggle button to start and close a connection to the
server.&lt;/p&gt;
&lt;p&gt;For dealing with WebSockets in Java, we make use of the &lt;a href="https://mvnrepository.com/artifact/org.java-websocket/Java-WebSocket"&gt;Java
WebSockets&lt;/a&gt;
library, which offers the &lt;code&gt;WebSocketClient&lt;/code&gt; abstract class. As you can see from
the code in
&lt;a href="https://github.com/P403n1x87/iot/blob/master/gravity_led/client/src/main/java/MainActivity.java"&gt;MainActivity.java&lt;/a&gt;,
all that we have to do is extend the &lt;code&gt;WebSocketClient&lt;/code&gt; class and implement a few
methods, which we just use for logging purposes. The actual signalling is done
via callbacks triggered by the on-board gravity sensor on the Android device:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="nd"&gt;@Override&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;onSensorChanged&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;final&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;SensorEvent&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;values&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;values&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;values&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sqrt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;webSocketClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Float&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;" "&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Float&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;" "&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Float&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;z&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;WebsocketNotConnectedException&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;Log&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;w&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"ctrl_ws_client"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;"Sensor updated but socket not connected"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This method is part of the &lt;code&gt;MainActivity&lt;/code&gt; class since we decided that this
should implement the &lt;code&gt;SensorEventListener&lt;/code&gt; interface. When a connection is
successfully started, we register the instance of this class with the sensor, so
that when the value is changed a white-space separated list of the three
components of the gravity vector are sent in text form to the server via the
WebSocket.&lt;/p&gt;
&lt;p&gt;We can use Gradle to build and deploy the application for testing on a device
with the command&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;./gradlew&lt;span class="w"&gt; &lt;/span&gt;installDebug
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;assuming that you have an Android device in developer mode connected to your
building machine via USB. This is what it looks like on my Nexus 5&lt;/p&gt;
&lt;p&gt;&lt;a href="https://p403n1x87.github.io/images/ws_asyncio/ctrl_ws_client.png" rel="noopener" target="_blank"&gt;&lt;img alt="ctrl_ws_client" class="center-image" src="https://p403n1x87.github.io/images/ws_asyncio/ctrl_ws_client.png"/&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Before moving to the conclusion, just a quick note on the contents of the
&lt;code&gt;AndroidManifest.xml&lt;/code&gt; file. If you have had a look at it, you might have noticed
the attribute &lt;code&gt;android:configChanges="orientation|screenSize"&lt;/code&gt; on the &lt;code&gt;activity&lt;/code&gt;
element. This allows the application to rotate with the device orientation,
without the application being restarted. If we do not put this attribute, any
previous connection would be closed and we would have to restart it by pressing
on the toggle button. The use of this attribute is not mandatory, but bear in
mind that if you decide not to use it, then you would have to make sure that the
same WebSocket connection is persisted across every screen rotation.&lt;/p&gt;
&lt;h1 id="conclusions"&gt;Conclusions&lt;a class="headerlink" href="#conclusions" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;In the introduction, I have mentioned that WebSockets can be operated in two
modes: &lt;em&gt;text&lt;/em&gt; and &lt;em&gt;binary&lt;/em&gt;. In the code that we have seen in this post we have
sent &lt;em&gt;text&lt;/em&gt; frames between the server and the client. This is because we have
used data of type &lt;code&gt;String&lt;/code&gt; in the Java client code, which is then received as
&lt;code&gt;str&lt;/code&gt; on the Python server end.&lt;/p&gt;
&lt;p&gt;In most practical cases, it is more convenient to send a stream of bytes
instead, thus increasing throughput. On the Java side, this is achieved by
passing an array of bytes (&lt;code&gt;bytes[]&lt;/code&gt;) to the &lt;code&gt;send&lt;/code&gt; method. On the Python end,
data will then be received as &lt;code&gt;bytes&lt;/code&gt; (that is, the return value of the &lt;code&gt;recv&lt;/code&gt;
coroutine is of type &lt;code&gt;bytes&lt;/code&gt;) that one can iterate over, or perform any
necessary operation to make sense of the received information.&lt;/p&gt;
&lt;p&gt;The same holds on reverse: if we send an array of bytes from Python, we will
receive an binary frame on Java. In this case, though, we will have to implement
the &lt;code&gt;ByteBuffer&lt;/code&gt; version of the &lt;code&gt;onMessage&lt;/code&gt; callback of the &lt;code&gt;WebSocketClient&lt;/code&gt;
class, i.e. the one with signature&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;onMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ByteBuffer&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bytes&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;</content><category term="IoT"/><category term="python"/><category term="android"/><category term="raspberry pi"/><category term="electronics"/></entry><entry><title>A Gentle Introduction to IoT</title><link href="https://p403n1x87.github.io/a-gentle-introduction-to-iot.html" rel="alternate"/><published>2017-07-31T19:30:15+01:00</published><updated>2017-07-31T19:30:15+01:00</updated><author><name>Gabriele N. Tornetta</name></author><id>tag:p403n1x87.github.io,2017-07-31:/a-gentle-introduction-to-iot.html</id><summary type="html">&lt;p&gt;The IoT revolution has started. But what is it exactly? Is it hard to take part to it? In this post I present you with all the details of a very simple and almost inexpensive &lt;i&gt;Internet of Things&lt;/i&gt; project. Read through as we go from assembling the required hardware, to coding the software that will drive it, exploring some of the most modern free technologies that are on offer today. At the end we will be able to take control of some LEDs over the internet, from wherever we are. Consider this as a launch pad to more complex and exciting IoT projects.&lt;/p&gt;</summary><content type="html">
&lt;h1 id="preamble"&gt;Preamble&lt;a class="headerlink" href="#preamble" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;No, I'm afraid this post is not on how to build your army of toy soldiers. If
the disappointment hasn't stopped you from reading any further, what I will
discuss here is something simpler and more peaceful, involving general
electronics single board computers, LEDs, Python, web servers and web
applications. All in just one place!&lt;/p&gt;
&lt;p&gt;I will try to introduce the fundamental concepts of IoT by example, and I will
do so by sharing my recent hands-on experience with my first Raspberry Pi, and
how this has led me to get to know of fascinating technologies of the modern
era. If your main objective is still to build an army of toy soldiers, this is
definitely a first step (however you should consider using technology for better
purposes, really!).&lt;/p&gt;
&lt;p&gt;I will try not to give much for granted, but of course I will have to draw a
line at some point, or this post would have never been finished! The subject is
software, but it is also hardware, for the former would make little sense
without the latter.&lt;/p&gt;
&lt;p&gt;The approach will be very practical. We will start with a concrete problem, and
we shall see how to solve it, both from a hardware and a software perspective.&lt;/p&gt;
&lt;h2 id="whats-iot"&gt;What's IoT?&lt;a class="headerlink" href="#whats-iot" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Can you eat it? Well, although your are free of munching on a breadboard if you
really want to, IoT, as you probably know already, stands for &lt;em&gt;Internet of
Things&lt;/em&gt;. This term is used to indicate the inter-networking of physical devices
(the &lt;em&gt;things&lt;/em&gt;) that are equipped with electronics, sensors, motors etc.. and
that communicate information with each other, sometimes taking actions based on
the received inputs. In this sense, every-day life devices, like the fridges or
the washing machines in our homes, or vending machines, or cars even, become
&lt;em&gt;smart&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Even though the first example of &lt;em&gt;smart things&lt;/em&gt; appeared in the 1982 (and you
can surely consider the toy army of Toy Story as an example of IoT in early
animation movies), it is around 2016 that the IoT has evolved greatly, and the
key aspect is the almost ubiquitous availability of wireless networks that allow
an increasing pool of diverse devices to communicate with one another.&lt;/p&gt;
&lt;p&gt;The IoT example of this post is somewhat a classic, but that will hopefully give
you a rough idea of what the IoT is also about, in case this is the first time
that you came across it. It is also quite simple and with a contained cost, but
nonetheless will spawn many interesting connections with some fascinating modern
technologies.&lt;/p&gt;
&lt;h2 id="the-project"&gt;The Project&lt;a class="headerlink" href="#the-project" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;So what is exactly the project described in this post about? The idea is to turn
some LEDs on and off by sending commands to a Raspberry Pi through a web page.
This might seem quite a trivial project, but it has given me the opportunity to
refresh some rusty knowledge of electronics that dated back to my undergraduate
years, as well as learn a great deal of new things from the software side too.&lt;/p&gt;
&lt;h1 id="the-hardware"&gt;The Hardware&lt;a class="headerlink" href="#the-hardware" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;In this first part I will describe all the hardware that is necessary for the
project. The main one is, I would say, a single-board computer like a Raspberry
Pi. In my case, I'm using a Raspberry Pi 3 Model B running the Raspbian OS. To
turn an LED on and off we will use one of the GPIO pins. For commodity, I will
also use a T-cobbler to connect all the GPIO pins on a breadboard, where the
rest of the circuit will be assembled. All that we still need are a couple of
jumper wires, a 220 Ω resistor and an LED of your favourite colour. To
summarise, here is the minimum required:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1x Raspberry Pi&lt;/li&gt;
&lt;li&gt;1x breadboard&lt;/li&gt;
&lt;li&gt;1x T-cobbler and a bus cable (alternatively 2x male-to-female jumper wires)&lt;/li&gt;
&lt;li&gt;2x male-to-male jumper wires&lt;/li&gt;
&lt;li&gt;1x 220 Ω resistor&lt;/li&gt;
&lt;li&gt;1x LED (about 20 mA max current)&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="the-gpio-pins"&gt;The GPIO Pins&lt;a class="headerlink" href="#the-gpio-pins" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Before looking at the circuit, it is probably best to mention a few facts about
the Raspberry Pi. In particular, the key part here is the set of GPIO pins that
it provides.&lt;/p&gt;
&lt;p&gt;The General Purpose Input-Output pins represent, as the name itself suggests, a
way to connect to external devices in order to send commands to and from the
Raspberry Pi. Some of these can be set to work as input or output, and can be
set either high (3.3 V or a logic 1) or low (0 V or a logic 0). Some pins can be
used together for other purposes, like communicating with another device through
a Serial Peripheral Interface (SPI), attaching LCD screen through the Display
Parallel Interface (DPI) etc.... Good references for the Raspberry Pi GPIO pins
are &lt;a href="https://pinout.xyz/"&gt;this website&lt;/a&gt; and the &lt;a href="https://www.raspberrypi.org/documentation/hardware/raspberrypi/bcm2835/BCM2835-ARM-Peripherals.pdf"&gt;Broadcom BCM2835 ARM
Peripherals&lt;/a&gt;
manual.&lt;/p&gt;
&lt;p&gt;From the software side, the pins can be conveniently configured and controlled
by means of the RPi Python module. The thing to be mindful of is that there are
a bunch of different naming conventions for the pins on the Raspberry Pi. The
main ones, to use a terminology proper of the RPi module, is &lt;code&gt;BOARD&lt;/code&gt; and &lt;code&gt;BCM&lt;/code&gt;.
The former is a pin numbering that reflects the physical location of the pins on
the PCB. Pin number one is on the top-left corner and gives a 3.3 V fixed
output. Pin 2 is the one to its right, Pin 3 is the one below it, and so forth.
The latter is the numbering convention used in the Broadcom manual.&lt;/p&gt;
&lt;h2 id="the-circuit"&gt;The Circuit&lt;a class="headerlink" href="#the-circuit" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Here is the schematic of the circuit that we want to build.&lt;/p&gt;
&lt;figure&gt;&lt;a href="https://p403n1x87.github.io/images/iot/iot_schem.png" rel="noopener" target="_blank"&gt;&lt;img alt="The circuit schematics" class="center-image" src="https://p403n1x87.github.io/images/iot/iot_schem.png"/&gt;&lt;/a&gt;&lt;figcaption&gt;The schematic of the circuit, showing all the components used for this project.&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;As I have already mentioned, I prefer using a T-cobbler to connect all the GPIO
pins to the breadboard. In case you are not using one, this is what your
breadboard should look like this picture.&lt;/p&gt;
&lt;figure&gt;&lt;a href="https://p403n1x87.github.io/images/iot/iot_bb.png" rel="noopener" target="_blank"&gt;&lt;img alt="The physical components" class="center-image" src="https://p403n1x87.github.io/images/iot/iot_bb.png"/&gt;&lt;/a&gt;&lt;figcaption&gt;Another schematic representation of the circuit, showing how the components are physically connected with each other on the breadboard and the Raspberry Pi 3 Model B.&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Where did the magic number 220 Ω come from? The explanation is very simple and
essentially based on Ohm's law. Across a resistor $R$ to which a voltage
difference of $V$ is applied, the current flowing through it is given by&lt;/p&gt;
&lt;p&gt;$$I = \frac VR.$$&lt;/p&gt;
&lt;p&gt;An LED is a diode, i.e. a p-n junction, that is capable of emitting light. In
&lt;em&gt;forward bias&lt;/em&gt;, an order-one approximation of a diode is given by a small
resistor (order of 10 Ω) in series with a voltage generator (of about -0.67 V).
The manufacturer of the LED usually provides the maximum current that the diode
can withstand. In the case of common LEDs, this value is around 20 mA.
Considering that, when a GPIO pin is on, it will provide 3.3 V to our circuit,
in order not to burn our LED we need to use a resistor of resistance $R$ given
by the inequality&lt;/p&gt;
&lt;p&gt;$$\frac{3.3\text{ V} - 0.67\text{ V}} R \leq 20\text{ mA},$$&lt;/p&gt;
&lt;p&gt;which yields&lt;/p&gt;
&lt;p&gt;$$R\geq 130\ \Omega.$$&lt;/p&gt;
&lt;p&gt;For a better estimate, we can look at the V-I chart provided by the
manufacturer, which would probably give us a minimum value closer to 200 Ω.
Anything below and you might risk frying your LED. Using a way bigger resistor,
however, would starve it of current and it would not turn on at all. But with
220 Ω we should be perfectly fine (and safe!).&lt;/p&gt;
&lt;h1 id="the-software"&gt;The Software&lt;a class="headerlink" href="#the-software" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;Now that we have assembled the required hardware, it is time to see how to
control it. What we have done so far is to connect the Raspberry Pi with a very
simple one-wire device, i.e. an LED. The IoT is the possibility of controlling a
device from the internet, anywhere in the world, with the actual device that we
want to control possibly miles and miles away from us.&lt;/p&gt;
&lt;p&gt;What we now need is then a simple interface, accessible from the internet, that
allows us to control the LED. Let's see how to create such interface,
step-by-step.&lt;/p&gt;
&lt;p&gt;But before we go any further, let's have a look, like we did with the hardware
part, at all that we will need.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Python (2.7 or later; note that the project has been tested with Python2.7
   and it might have to be adapted slightly to work with Python3)&lt;/li&gt;
&lt;li&gt;a web server e.g. Apache2&lt;/li&gt;
&lt;li&gt;a text editor of your choice.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Yep, that's all.&lt;/p&gt;
&lt;h2 id="the-rpi-python-module"&gt;The RPi Python Module&lt;a class="headerlink" href="#the-rpi-python-module" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;On Raspbian there is a pretty simple way to control the GPIO pin that comes
already bundled with the OS. I'm talking about the
&lt;a href="https://pypi.python.org/pypi/RPi.GPIO"&gt;RPi&lt;/a&gt; Python module. For the simple task
that we want to achieve here, RPi exposes all the features that we need.
However, keep in mind that more advanced tasks, like real-time applications,
cannot be solved by this module. This is not just because it is a Python module,
but a "limitation" of any OS based on the Linux kernel, which is multitasking in
nature. This means that the kernel can decide on its own how to allocate
resources for all the running processes, potentially giving rise to jitter in
your applications.&lt;/p&gt;
&lt;p&gt;Another important limitation that should push you towards other approaches, like
&lt;a href="http://wiringpi.com/"&gt;wiringPi&lt;/a&gt;, is the lack of hardware PWM. PWM stands for
Pulse-Width Modulation and is a technique used to encode a message in a pulsing
signal. Some of the common uses are that of dimming an LED (recall that an LED
response is exponential, even though we treated it as linear in our first-order
approximation discussed above), or controlling a motor, but this is a topic that
would take us away from the main focus of this post, and it might be the subject
of a future one.&lt;/p&gt;
&lt;p&gt;Returning to our project, let's have a look at how to turn our LED on. Recall
from the schematic above that we are using the GPIO Pin 16 (according to the
Broadcom convention), which is the 36th physical pin on the GPIO.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;RPi.GPIO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;as&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;G&lt;/span&gt;     &lt;span class="c1"&gt;# Import the GPIO component from the RPi module&lt;/span&gt;

&lt;span class="n"&gt;LED&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;36&lt;/span&gt;                 &lt;span class="c1"&gt;# Define a constant with the pin number where the LED&lt;/span&gt;
                         &lt;span class="c1"&gt;# is connected&lt;/span&gt;

&lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;setmode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;BOARD&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;       &lt;span class="c1"&gt;# Set the pin numbering mode to the physical number&lt;/span&gt;

&lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;setup&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;LED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;OUTPUT&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;# Set the LED pin to output mode&lt;/span&gt;

&lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;LED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;         &lt;span class="c1"&gt;# Set the pin to high (3.3 V)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;We can type the above lines of Python code directly into the Python interpreter.
To turn the LED off we can either set the value on the pin 36 back to 0&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;LED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;or clean up the GPIO configuration with&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;cleanup&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;If we'll ever want to use more than just one LED on our breadboard, we can
encapsulate most of the above code inside a Python class so that it can be
reused instead of having to type it every time with setup a new LED. A
minimalist Python class that would represent a physical LED would be something
like&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# File: led.py&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;RPi.GPIO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;as&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;G&lt;/span&gt;

&lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;setmode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;BOARD&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;LED&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;object&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
  &lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ch&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_ch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ch&lt;/span&gt;
    &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;setup&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ch&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;OUT&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;on&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_ch&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;off&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_ch&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="nd"&gt;@property&lt;/span&gt;
  &lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;state&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_ch&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

  &lt;span class="nd"&gt;@state&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;setter&lt;/span&gt;
  &lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;state&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_ch&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

  &lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;toggle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_ch&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_ch&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Our code for turning an LED on and off would then reduce to the following few
lines&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;led&lt;/span&gt;&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;LED&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;time&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;sleep&lt;/span&gt;

&lt;span class="n"&gt;led_red&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;LED&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;36&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;led_red&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;on&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="n"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;led_red&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;off&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The extra method &lt;code&gt;toggle&lt;/code&gt; can be used, as the name suggests, to toggle the LED
state from on to off and vice-versa. In the above example we could then replace
both &lt;code&gt;led_red.on&lt;/code&gt; and &lt;code&gt;led_red.off()&lt;/code&gt; by &lt;code&gt;led_red.toggle()&lt;/code&gt;. The property
&lt;code&gt;state&lt;/code&gt; is used to get the state of the LED as a Boolean value (&lt;code&gt;True&lt;/code&gt; for on
and &lt;code&gt;False&lt;/code&gt; for off), and it can also be used to set it. For instance, something
like&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;led_red&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;would turn the LED on, since &lt;code&gt;[1]&lt;/code&gt; evaluates to &lt;code&gt;True&lt;/code&gt; when converted to a
Boolean. Analogously, the following line of code&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;led_red&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;would turn the LED off, since &lt;code&gt;bool({}) = False&lt;/code&gt; in Python.&lt;/p&gt;
&lt;p&gt;Sweet! We now know how to control our LED with code and all that's left to do is
build a nice web interface that will execute this code on demand.&lt;/p&gt;
&lt;h2 id="the-wsgi-specification"&gt;The WSGI Specification&lt;a class="headerlink" href="#the-wsgi-specification" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Given that we already have some code in Python to control our LED, it would be
good if the web interface could use that code directly. Is this possible? The
(short) answer is &lt;em&gt;yes&lt;/em&gt;!&lt;/p&gt;
&lt;p&gt;A more articulated answer to the above question leads us into the realm of the
Web Server Gateway Interface specification, or WSGI for short. It is a universal
specification that was born out of the necessity of putting some order among all
the Python frameworks for developing web applications. Before the specification,
each of said frameworks would be compatible with just a few web servers.
Choosing one of them would then restrict your choice of a web server to go with
it, and vice-versa. To overcome this limitation, the WSGI specification was
proposed in the &lt;a href="https://www.python.org/dev/peps/pep-0333/"&gt;PEP 333&lt;/a&gt;, which
dates back ton 2003. The technical details can be found in the linked page. Here
we just limit ourself to the essential details of the specification that will
allow us to write a simple web application to control the LED over the internet.&lt;/p&gt;
&lt;p&gt;In very simple terms, a Python web application consists of a &lt;em&gt;bootstrap
callable&lt;/em&gt; object that is called by the web server. The python code contained in
the callable is executed, and the web server expects a response consisting of a
code (200 for OK, 403 for Forbidden, 404 for Not Found etc...) and a stream of
bytes (usually the HTML code to be rendered by the browser). A callable can be
any Python object that exposes a &lt;code&gt;__call__&lt;/code&gt; function like, e.g., classes and
functions.&lt;/p&gt;
&lt;p&gt;My favourite web server is Apache2 and it will be the one that I will discuss in
this post. Its functionalities can be extended with modules, and the
&lt;a href="https://modwsgi.readthedocs.io/en/develop/"&gt;mod_wsgi&lt;/a&gt; project provides a
WSGI-compliant module for Apache. The documentation is very detailed and covers
all the aspects, from the installation to the configuration and debugging
techniques.&lt;/p&gt;
&lt;p&gt;Regarding the installation process, this can be carried out in two modes. Either
on the Apache-side, or on the Python-side. If you are into the IoT, chances are
you will have your web server running on a Raspberry Pi. For this reason, I will
discuss how to install the mod_wsgi module for the Apache web server. On
Raspbian, this can be done with&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;sudo&lt;span class="w"&gt; &lt;/span&gt;apt&lt;span class="w"&gt; &lt;/span&gt;install&lt;span class="w"&gt; &lt;/span&gt;libapache2-mod-wsgi
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;After the installation, the module should already be enabled. If this isn't the
case, you can enable it with&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;sudo&lt;span class="w"&gt; &lt;/span&gt;a2enmod&lt;span class="w"&gt; &lt;/span&gt;wsgi
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2 id="writing-the-web-application"&gt;Writing the Web Application&lt;a class="headerlink" href="#writing-the-web-application" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The next steps are to actually write our web application and configure Apache to
run it when a request comes in. In the configuration process we will specify our
bootstrap Python script. By default, Apache expects to find a callable object
inside it with the name &lt;code&gt;application&lt;/code&gt;. The simplest thing that we could do is
then to create a Python script and define a function with such a name. The code
of our application would then be contained in this function, or called by it, in
case we decide for a more modular approach.&lt;/p&gt;
&lt;p&gt;In case things would go wrong while we develop our web application, we might
want to be able to have a look at the Python stack trace to see where the
problems are. Normally we would have to look in the Apache error log (usually in
&lt;code&gt;/var/log/apache2/error.log&lt;/code&gt;). However, we can make use of a middleware from the
&lt;a href="https://paste.readthedocs.io/en/latest/"&gt;paste&lt;/a&gt; Python package, which is
specifically designed for WSGI applications. Our bootstrap script will then look
like this.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# File: bootstrap.wsgi&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;os&lt;/span&gt;
&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dirname&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="vm"&gt;__file__&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;index&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;Index&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;env&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start_response&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'200 OK'&lt;/span&gt;

    &lt;span class="n"&gt;output&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Index&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;env&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;response_headers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'Content-type'&lt;/span&gt;   &lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'text/html'&lt;/span&gt;     &lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="p"&gt;,(&lt;/span&gt;&lt;span class="s1"&gt;'Content-Length'&lt;/span&gt; &lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;)))&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;start_response&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;response_headers&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;paste.exceptions.errormiddleware&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;ErrorMiddleware&lt;/span&gt;
&lt;span class="n"&gt;application&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ErrorMiddleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;main&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;debug&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The first two lines are necessary if we want to be able to import modules and
packages that are in the same folder as the bootstrap script.&lt;/p&gt;
&lt;p&gt;We then import the class &lt;code&gt;Index&lt;/code&gt; from the &lt;code&gt;index&lt;/code&gt; module. This is just a design
choice. The bootstrap script contains the essential code to get us to the main
page (by means of the &lt;code&gt;Index&lt;/code&gt; class), and returns us the full stack trace in
case of errors (by means of the &lt;code&gt;ErrorMiddleware&lt;/code&gt; class from the paste package).
To make sense of the rest of the code, have a look at the already referenced
documentation of the &lt;code&gt;mod_wsgi&lt;/code&gt; module for Apache2.&lt;/p&gt;
&lt;p&gt;The core code of our application is contained in the &lt;code&gt;Index&lt;/code&gt; class from the
&lt;code&gt;index&lt;/code&gt; module.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# File index.py&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;util&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;templ&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;qs&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;led&lt;/span&gt;&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;LED&lt;/span&gt;

&lt;span class="n"&gt;led&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;LED&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;15&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;Index&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;object&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;

    &lt;span class="nd"&gt;@staticmethod&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;env&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;params&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;qs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;env&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="s2"&gt;"action"&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;params&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="s1"&gt;'toggle'&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'action'&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
            &lt;span class="n"&gt;led&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;toggle&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;templ&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'index'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;state&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"on"&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;led&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="s2"&gt;"off"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In fact, this module looks more like a view rather than a controller, as the
actual code for controlling the LED is buried in the &lt;code&gt;led&lt;/code&gt; module that we have
analysed previously. The &lt;code&gt;util.py&lt;/code&gt; module contains some helper functions to
conveniently deal with HTML templates and query strings. We refrain from showing
the code in this post, but you can find it in the &lt;a href="https://github.com/P403n1x87/led_app"&gt;dedicated GitHub
repository&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The HTML template contained in the &lt;code&gt;index.html&lt;/code&gt; file is very simple and looks
like this.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt; &lt;span class="na"&gt;lang&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"en-us"&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;meta&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"viewport"&lt;/span&gt; &lt;span class="na"&gt;content&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"width=device-width, initial-scale=1.0"&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;meta&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"theme-color"&lt;/span&gt; &lt;span class="na"&gt;content&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"#666666"&lt;/span&gt; &lt;span class="p"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;link&lt;/span&gt; &lt;span class="na"&gt;rel&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"stylesheet"&lt;/span&gt; &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"text/css"&lt;/span&gt; &lt;span class="na"&gt;href&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"led_app/led.css"&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;a&lt;/span&gt; &lt;span class="na"&gt;href&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"?action=toggle"&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;div&lt;/span&gt; &lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"button {state}"&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;div&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;a&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The body is essentially just a link that executes a request with the parameter
&lt;code&gt;action&lt;/code&gt; set to &lt;code&gt;toggle&lt;/code&gt;, containing a placeholder &lt;code&gt;div&lt;/code&gt; element. The
look-and-feel of a 3D button is then provided by the classes contained in the
linked stylesheet, which you can find in the GitHub repository. Note how we use
the &lt;code&gt;{state}&lt;/code&gt; placeholder in the class attribute of the &lt;code&gt;div&lt;/code&gt; element. This
allows us setting the button appearance according to the LED current state. In
the stylesheet we have two classes, &lt;code&gt;.on&lt;/code&gt; and &lt;code&gt;.off&lt;/code&gt;, the former giving a bright
red colour to the button, while the latter giving a darker shade. The value is
passed by the line&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;templ&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'index'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;state&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"on"&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;led&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="s2"&gt;"off"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;in the static method &lt;code&gt;main&lt;/code&gt; of the &lt;code&gt;Index&lt;/code&gt; class of &lt;code&gt;index.py&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="configuring-apache"&gt;Configuring Apache&lt;a class="headerlink" href="#configuring-apache" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;We are almost ready to start playing with our LED over the internet. The last
step is to put our application up and running on the Apache web server. To this
end there is a tiny bit of configuration that we need to do. We can start by
making a copy of the default web site Apache2 comes with. On Raspbian, this is
located in &lt;code&gt;/etc/apache2/sites-available&lt;/code&gt; and is contained in the
&lt;code&gt;000-default.conf&lt;/code&gt; configuration file. Make a copy of this file in, say,
&lt;code&gt;led.conf&lt;/code&gt; and modify it to look like the following one.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c"&gt;# File: led.conf&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;VirtualHost&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;*:80&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="nb"&gt;ServerAdmin&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;webmaster@localhost

&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="c"&gt;# Required by static data storage access (e.g. css files)&lt;/span&gt;
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="nb"&gt;DocumentRoot&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sx"&gt;/home/pi/Projects/www&lt;/span&gt;

&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="nb"&gt;ErrorLog&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;${APACHE_LOG_DIR}/error.log
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="nb"&gt;CustomLog&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;${APACHE_LOG_DIR}/access.log&lt;span class="w"&gt; &lt;/span&gt;combined

&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="c"&gt;# WSGI Configuration&lt;/span&gt;
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="nb"&gt;WSGIScriptAlias&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sx"&gt;/led&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sx"&gt;/home/pi/Projects/www/led_app/bootstrap.wsgi&lt;/span&gt;

&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="nt"&gt;&amp;lt;Directory&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;/home/pi/Projects/www/led_app&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="nb"&gt;Require&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;all&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;granted
&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="nt"&gt;&amp;lt;/Directory&amp;gt;&lt;/span&gt;

&lt;span class="nt"&gt;&amp;lt;/VirtualHost&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Even though we are implementing a WSGI application, the &lt;code&gt;DocumentRoot
/home/pi/Projects/www&lt;/code&gt; is needed because we are importing a css file in
&lt;code&gt;index.html&lt;/code&gt;. The above configuration file assumes that the web application
resides in the &lt;code&gt;/home/pi/Projects/www/led_app&lt;/code&gt; folder. This way, static files
can be accessed with a relative path referring to the parent folder
&lt;code&gt;/home/pi/Projects/www&lt;/code&gt;. This explains why we are importing the &lt;code&gt;led.css&lt;/code&gt; file
as&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;link&lt;/span&gt; &lt;span class="na"&gt;rel&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"stylesheet"&lt;/span&gt; &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"text/css"&lt;/span&gt; &lt;span class="na"&gt;href&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"led_app/led.css"&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The section below the &lt;code&gt;# WSGI Configuration&lt;/code&gt; comment is the WSGI part of the
configuration. The first line of this section tells Apache which script to use
to bootstrap the web application. This is the script that is assumed to contain
the callable object named &lt;code&gt;application&lt;/code&gt;. The rest of the WSGI configuration
section is required to set the rights to read the bootstrap and the python
scripts contained in the web application folder.&lt;/p&gt;
&lt;p&gt;That's it! All we have to do now is deactivate any other website on port 80 with
&lt;code&gt;a2dissite&lt;/code&gt; (this is only required if the web sites are not named), and enable
&lt;code&gt;led.conf&lt;/code&gt; with &lt;code&gt;a2ensite led.conf&lt;/code&gt;. Restart the Apache2 web server with&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;sudo&lt;span class="w"&gt; &lt;/span&gt;service&lt;span class="w"&gt; &lt;/span&gt;apache2&lt;span class="w"&gt; &lt;/span&gt;restart
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;and point the browser on any device that is on the same local network as the Pi
to its local IP address, append '/led' to it to start the web application (e.g.
&lt;code&gt;http://192.168.0.203/led&lt;/code&gt;) and you should now be in the web application, with a
red button that will now allow you to control the LED state over the LAN.&lt;/p&gt;
&lt;figure&gt;&lt;a href="https://p403n1x87.github.io/images/iot/website.png" rel="noopener" target="_blank"&gt;&lt;img alt="The final look of the web application" class="center-image" src="https://p403n1x87.github.io/images/iot/website.png"/&gt;&lt;/a&gt;&lt;figcaption&gt;The final look of the web application. The red button in the middle is used to toggle the LED state.&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;If you are behind a router, of course you will need to forward the port 80 to
the Pi's local address before you could be able to access your web application
from the internet, outside of your local network. In this case you will have to
use the router's public IP instead of the local IP.&lt;/p&gt;
&lt;h1 id="conclusions"&gt;Conclusions&lt;a class="headerlink" href="#conclusions" title="Permanent link"&gt;¶&lt;/a&gt;&lt;/h1&gt;
&lt;p&gt;We have come to the end of this post on a simple IoT project. Its main purpose,
like most of the other posts in this blog, is two-fold. On one hand, it is a way
for me to take notes of new things that I have discovered and that I can later
come back to if I need to. All the information gathered from the cited sources
is gathered in a single place, which makes it more convenient than having to go
through them separately. On the other hand, it is a way to share my experience
with others, in the hope that it could be useful somehow. Even though the
project in it self, as I have remarked many times now, is quite simple, the post
includes references to many topics, e.g. electronics, programming, web servers
and applications, and it shows you how all these different aspects can be
organically combined together to create something.&lt;/p&gt;</content><category term="IoT"/><category term="raspberry pi"/><category term="wsgi"/><category term="electronics"/></entry></feed>