Skip to content
ImagineWorld

Driving the Robot with a Phone and Python

node_idnode-book_learn-robotics-programming_chapter-07-driving-the-robot-with-a-phone-and-python
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleDriving the Robot with a Phone and Python
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Driving the Robot with a Phone and Python

Section titled “Chapter 7 — Driving the Robot with a Phone and Python”

We’ve designed and built our robot, configured a Raspberry Pi, and programmed a simple behavior on it to get it moving. We’ve been launching commands to drive our robot from Secure Shell (SSH), but the robot will be more exciting and more comfortable to demonstrate if you can start the commands from your phone. We will build upon the MQTT service that you built in the preceding chapter to manually drive the robot.

In this chapter, we’ll understand how to start services on the robot automatically. Then we’ll design and build a phone-friendly web app to choose robot modes. We will build a touch surface interface to drive the robot, publishing commands via the MQTT layer. You will learn about HTML apps and get control of the robot.

We will cover the following topics in this chapter:

  • Choosing a controller for the robot
  • Making services start when the Raspberry Pi starts
  • Building a phone app
  • Connecting the phone app to MQTT
  • Adding more control options to the web app

For this chapter, you will need the following items:

  • Your Raspberry Pi robot with the code from previous chapters.
  • A touchscreen smartphone or tablet on the same wireless network as your computer and your robot.
  • A code editor such as VS Code on a Linux, Windows, or Mac computer.
  • One of the Firefox, Chrome, or Edge browsers.
  • The PyInfra tool
  • Python 3 on your local computer.
  • Drawing software such as Inkscape or diagrams.net.

You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.

This chapter’s code files are included in the downloadable code bundle.

We want to be able to control our robot with something that is handheld and wireless. Having seen our robot move in *Chapter 6,*Drive and Turn – Moving Motors with MQTT and Python, we probably want to drive it ourselves!

While logging in and typing commands to start and Ctrl + C to stop behaviors works during the testing phase, it can be slow and cumbersome. It’s easy to mistype commands.

You could use a game controller via Bluetooth or wireless. However, before spending money, you can use the handheld device in your pocket, a.k.a: your phone. It has Wi-Fi, can make hotspots, and has a touchscreen, capable of reading finger movements. Think of it as a wireless touchscreen joystick! We can make the phone drive the robot or start/stop behaviors. Let’s see how to build a User Interface or UI for this.

Let’s design this phone app to connect with our robot.

Let’s start by designing this UI. We’ll target a phone in portrait mode. The next figure shows screen mockups of this UI on a smartphone:

Figure 7.1 – Screen mock-up of phone app

Figure 7.1 – Screen mock-up of phone app

Figure 7.1 – Screen mock-up of phone app

The left screen design in Figure 7*.*1 shows a main menu, with a Robot control title, and a list of menu options including Manual drive and Drive path. We will extend this list throughout the book. Pressing a list item will take you to another view – for example, the manual driving view shown on the right.

The manual driving page has a title bar across the top, and a back button to take us back to the menu. There should be an on-screen, touch-friendly, self-centering joystick that can control the robot. We’ll look for components that provide that functionality.

We have a user interface design. Let’s plan the code blocks we will need to build this.

Let’s take that UI design and look at how we might make a software system to support it. There are components we’ll need to build or configure to make this happen. The following figure shows the software components that will be interacting in this system:

Figure 7.2 – Robot software architecture

Figure 7.2 – Robot software architecture

Figure 7.2 – Robot software architecture

F igure 7.2 shows how the browser M enu pages interact with robot systems over MQTT. The key at the bottom left shows how to read the diagram. The darker shaded components are those we’ll need to build or configure in this chapter. Arrows show the flow of data or control.

The top dashed rectangle is the Phone / computer browser, where it will show the Menu pages being served to it by a Web server running on the Raspberry Pi.

The middle cloud represents the Wi - F i network, which we will use to communicate between the Raspberry Pi and the phone. The MQTT and HTTP connections outside of the Raspberry Pi go via this network.

The lower rectangle contains the services that will run on the Raspberry Pi, with the existing Inventor HAT service and Drive path behavior. We will be adding the Web server and Launcher service, then configuring systemd/systemctl to run things for us.

Similar to the drive path behavior we made in the previous chapter, the joystick on the Manual drive page publishes MQTT messages to control motors. Motor messages are consumed by the Inventor HAT service.

Items with a triangle are run automatically by systemd when the Raspberry Pi starts. systemd lets us configure how to start/stop services on Raspberry Pi OS. It can run code automatically or on demand.systemctl is a command to control systemd services.

The Launcher service will subscribe to a launcher topic and control other services using systemctl. The Drive path page will send MQTT messages on the launcher topic to start the Drive path behavior.

Let’s start by learning how systemd can run the Inventor H AT service automatically.

Making services start when the Raspberry Pi starts

Section titled “Making services start when the Raspberry Pi starts”

When we ran the drive path example in the last chapter, we needed two SSH terminals, one to start the Inventor HAT service and another to start the drive behavior. This is pretty inconvenient.

We want to turn on the robot, let it tell us that it’s ready, and then point your phone app at it to control it. So how do we launch services automatically? This is a building block we can use for other services.

The tool systemd is used by Raspberry Pi OS to automatically launch programs. systemd lets you control programs’ lifecycle and inspect their state. It can control when they run, how they run, as which user, which directory they start in (you’ve been using the /home/<username> directory), and capture their logs as journals. We’ve used systemd before, in Chapter 6*,Drive and Turn – Moving Motors with MQTT and Python,* to start Mosquitto.

We are going to do two things to make this useful, as follows:

  • Use systemd to automatically start the Inventor HAT service
  • Use an LED to indicate that the Inventor HAT service is live

Let’s now configure systemd by writing a unit file.

Writing a systemd unit to start the Inventor HAT service

Section titled “Writing a systemd unit to start the Inventor HAT service”

Each program is configured in a unit file. We can write a template to build Python services with in deploy/service_template.j2:

[Unit]
Description={{ service_name }}
After=mosquitto.service
[Service]
Type=simple
Restart={{ restart }}
WorkingDirectory=/home/{{ pi_user }}/
ExecStart=/usr/local/bin/robotpython -u {{ command }}
KillSignal=SIGINT
[Install]
WantedBy=multi-user.target

The unit file is made of sections named in square brackets (e.g., [Service]). Each section consists of settings and their values in the format SettingName=SettingValue. Because it is a template, it has replaceable placeholder variables like {{ service.name }}, which we can fill in with details like the real service name. We can use this multiple times with different names. Any variable in double brackets will be replaced by PyInfra.

The file starts with the [Unit] section, which has a description of the unit using the {{ service_name }} template variable. We state that we want the service to automatically start After Mosquitto (another service unit) has started. If you recall, Mosquitto is our MQTT broker, so this means the service can connect to the MQTT message bus.

Next is the [Service] section. The Restart setting controls what happens when the service exits or fails, using a {{ restart }} template variable. We can set a service like Inventor HAT to always restart, and a behavior like drive path to never restart.

The WorkingDirectory setting controls which folder the program will find files in. We use the home for {{ pi_user }}, as this is where we’ve stored the code.

ExecStart controls which command line we start. We use our robotpython script to run the Python file in {{ command }}. The ‑u makes sure it doesn’t pause logs.

The KillSignal setting ensures our atexit code is allowed to run.

The [Install] section only has the WantedBy property. Using multi‑user.target here tells the Raspberry Pi to launch this at startup.

Let’s make a pyinfra deployment to fill in the template variables, and create a unit for the Inventor HAT service. Create the file deploy/deploy_services.py:

from pyinfra.operations import files, systemd
from pyinfra import host
def deploy_service(service_name, command, auto_start, changed):
if auto_start:
restart="always"
else:
restart="no"
unit_file = files.template(
name=f"Create {service_name} service",
src="deploy/service_template.j2",
dest=f"/etc/systemd/system/{service_name}.service",
pi_user=host.data.get('ssh_user'),
service_name=service_name,
command=command,
restart=restart,
_sudo=True
)
if changed or code.changed or unit_file.changed:
systemd.service(
name=f"Restart {service_name} service",
service=service_name,
running=auto_start,
enabled=auto_start,
restarted=auto_start,
daemon_reload=unit_file.changed,
_sudo=True,
)

In the imports, we need the files and systemd operations, along with importing host to get the Raspberry Pi username.

After the imports is a function to deploy a service. It has these parameters:

  • Service name: The name we will give our service, and unit file.
  • Command: What we will use robotpython to run in our service.
  • Auto start: If this service should restart when the Raspberry Pi starts
  • Changed: If other changes should prompt a restart of this service

The function does a few things. First, we determine what the restart strategy for the service unit will be – always means that even if it breaks, the Pi will try to restart it. The value no means only a systemctl command will restart the service.

We then set up the unit file. It’s using our deploy/service_template.js file, and filling in the details. The host.data.get('ssh_user') command will get the current Raspberry Pi username. This creates the unit file /etc/systemd/system/

{service_name}.service. We also store the result of this operation in the unit_file variable.

The last part checks if any of our contributing files changed, and if so it will register or re-register the service, ensuring it gets restarted if needed. Setting enabled will mean it starts when the unit file’s WantedBy condition is triggered, and running will mean it starts right now. Daemon reload forces systemd to account for unit file updates.

We now have a function to create a service. Let’s use it to make the Inventor HAT service. Add the following to deploy/deploy_services.py:

common = files.sync(
name="Update common code",
src="robot/common", dest="robot/common")
code = files.put(
name="Update inventor hat code",
src="robot/inventor_hat_service.py",
dest="robot/inventor_hat_service.py")
deploy_service("inventor_hat_service",
"robot/inventor_hat_service.py",
True, common.changed or code.changed)

When we deploy our service, we first ensure any common code used by our service is up to date, followed by the service code. The deploy_service function is called with the following parameters:

  • Service name: inventor_hat_service – it should be in snake_case.
  • Command: The command is robot/inventor_hat_service.py, the filename for this service.
  • Auto start: True as we want the Inventor HAT service to start when the Raspberry Pi starts.
  • Changed: If either the code or common code changes, this will be True.

You can run this deployment from your computer terminal with pyinfra inventory.py deploy/deploy_services.py, and the Inventor HAT service will start when the Raspberry Pi starts. How can we tell, though?

If you want to see the status of a service, you can use this command from SSH:

$ systemctl status inventor_hat_service

The Pi will then respond with something like this:

● inventor_hat_service.service - Inventor HAT Mini service
Loaded: loaded (/etc/systemd/system/inventor_hat_service.service; disabled; preset: enabled)
:
:
Jan 01 21:24:14 learnrob3 systemd[1]: Started inventor_hat_service.service - Inventor HAT Mini service.

Which shows it is running.

If we want more information, and to see its full log, we use journalctl ‑u inventor_hat_service.service. Use arrow keys to scroll up and down through the log, or press S hift + G to go to the end. You can press q to exit this view.

We can track real-time updates to the log output as we run things by adding a ‑f to instruct the command to follow the journal. Use Ctrl + C to stop tracking the log. This will be more fun when we have something emitting motor messages.

It’s a good idea to make a git commit at the end of each section.

The output of systemctl status tells us our service is running via SSH, but we want the robot to tell us it’s ready outside of SSH. Adding LED lights will let us see that the Inventor HAT service is ready. Let’s add these lights.

The Inventor HAT Mini has a set of built-in lights. Let’s set one light to green to show the service is running. We can also use atexit to turn off the lights when it exits.

Find the atexit.register line in robot/inventor_hat_service.py and change it for the following:

def exit_handler():
stop_motors()
board.leds.clear()
atexit.register(exit_handler)

This ensures that LEDs are cleared when the service is stopped.

Next, find the client.loop_start() line, and add the highlighted line:

client.connect("localhost", 1883)
board.leds.set_rgb(0, 0, 255, 0)
client.loop_start()

These LEDs let us mix colors by setting red, green, and blue values. The preceding code sets the first LED (index 0) to green (with red and blue components at 0). Now when the code is started, it will light green. Run pyinfra inventory.py deploy/deploy_services.py, and you should see a green light appear on the robot. Use SSH to shut down the Pi, unplug it, and then power it on again.

The green light should be lit, meaning it’s ready for other services to send motor messages to it. We’ve now got this automatically running!

Let’s check that our automatic service has worked.

Things can go wrong here—if so, try these steps to fix it or find out more:

  • Starting/enabling the service with systemd may fail. If you see Unit inventor_hat_service.service is not loaded properly: Invalid argument, there are problems in the deploy/inventor_hat_service.j2 file. Please verify its content and rerun deploy_services to deploy it.
  • Use the service status and log commands to see if there are Python errors and verify the new LED code you have added. You can use Git to show the difference from the previous version on your computer with git diff robot/inventor_hat_service.py.

Now that our motor service is running automatically, we can build an app to talk to it.

Based on our design, we will be building a web-page-based app, which will be designed for phone and computer. This lets us control the robot without the use of SSH, in a way we can extend and build on as we extend the robot’s capability. We will use three tools designed to work together for this:

  • HTML (Hyper T ext M arkup L anguage) – This presents things on a web page or app, text, inputs, buttons, and links.
  • CSS (Cascading Style Sheets) – This is used to add style and layout to HTML, to determine colors, fonts, positions, and sizes of items.
  • JS (Java S cript) – This is used to write code that runs on a page, what happens when buttons are clicked, or to construct complicated gadgets. We’ll use it to interact with the MQTT services on our robot.

We will also need a web service on the robot, to make these files available to your phone. We will use pyinfra to install these items and make them work together.

Now let’s build a menu page for robot control.

The language HTML is used for the structure of a web page. It also allows the embedding of languages to control other aspects of the page. HTML is fairly universally supported on modern computer and phone devices. Let’s see how to start making a menu page with it.

Make the folder robot_control and add the following to robot_control/index.html:

<!DOCTYPE html>
</html>
<head>
<title>Robot control</title>
</head>
<body>
<h1>Robot control</h1>
<ul>
<li>Drive the robot</li>
</ul>
</body>
</html>

In this file, we start with the DOCTYPE line, to confirm we are using HTML. We then open our document with our first tag in the code, <html>. This tag wraps up the whole page. HTML makes tree-like data structures, with items enclosed in an opening tag, and a closing tag – in this case, </html>. When you see a tag starting with a / character, it is the closing tag.

Our page starts with a head element, which contains information about the page like the title to be shown in a browser tab.

Below this is the body element, which contains things we will see on the page. In this case, we have h1, a level one heading with the Robot control text inside it. Then we have ul, an unordered list, which we will use to make a control menu. In it is a single list item element, li, with the text Drive the robot inside.

Let’s view this file in a browser. From your computer, run a terminal in the project folder, and try the following command:

python -m http.server --directory robot_control

The terminal will respond with:

Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

In VS Code, you can click on the http:// part to see your page in a browser. It should look something like this:

Figure 7.3 – Robot control app

Figure 7.3 – Robot control app

Figure 7.3 – Robot control app

The preceding screenshots show our app in a browser, and how it’s structured:

  1. The first screenshot shows the app in the browser, with the heading element above a simple list.
  2. If you right-click the list, you will see a menu. Near the bottom of this menu is an Inspect button. Click this.
  3. This will reveal an inspector panel, either to the right or bottom of the page. This has the HTML elements in a tree. You can highlight an element, and it will be shown highlighted on the page, with its styles in another panel.

What do we mean by the tree? Where an element has child elements, there’s an arrow or plus button to show the contents of that element. Child elements are then listed under it. One way to look at it is that containers are branches, and child elements with no further children are leaf elements. This is known as the DOM (Document Object Model) tree. Some items are added by your browser and extensions.

While we can see this page, it has no style, and no buttons do anything yet. Let’s make it more menu-like.

The next aspect of our app is to add style. Style is made using another language, CSS, Cascading Style Sheets. They allow us to specify aspects of HTML elements like their size, color, or text fonts. We can either embed them into HTML or put them in a separate file. Putting styles in a separate file means we can use the same styles on multiple pages and keep a consistent style between them.

We will style this list and turn the items into links for further pages. Create the file robot_control/styles.css with the following:

body {
font-family: Arial, Helvetica, sans-serif;
}
h1 {
text-align: center;
font-size: 2em;
}

Styles apply to elements, and unless otherwise overridden, cascade to element children. For example, the first section is styling the body element, which would apply to all the visible child elements on the page. It sets font‑family to font styles that are closer to our design.

The second section styles the h1 element. First, centering it horizontally. We then set font‑size to 2em, multiplying the em unit by 2. The em unit is versatile; it represents the size of the parent element’s font, so we can scale relative to that.

We now need our page to load this CSS file. Open robot_control/index.html and add the highlighted code into the head section:

<head>
<title>Robot control</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>

The link element has no closing tag. It tells the browser to load the styles.css file. After this is a meta element to ensure a smartphone view is the same scale as our desktop. Reload the page and you should now see that the page fonts and title are updated. Being able to debug the HTML directly on our computer in the browser is incredibly useful for fixing the styles.

Let’s turn those menu items into links, with placeholder pages. In robot_control/index.html, modify the ul menu section:

<ul>
<li><a href="manual_drive.html">Manual drive</a></li>
<li><a href="behavior_path.html">Drive path</a></li>
</ul>

The highlighted code now adds an anchor element, abbreviated to just a. An anchor is a place for a clickable link. This has a property href, which names an HTML file to link to when clicked – for example, manual_drive.html. This will be in the same robot_control directory. Between the opening and closing a tag is the clickable text for the menu item.

In your browser, load the file or press C md / Ctrl + R to refresh. See the following screenshot:

Figure 7.4 – The robot control menu with links

Figure 7.4 – The robot control menu with links

Figure 7.4 – The robot control menu with links

The preceding figure shows a screenshot of the robot control menu, with links that can now be clicked or tapped to get to the other pages. The default styles mean they go from blue to purple when clicked. More style work could be done to make this menu look more like our design, but we’ll focus on making stuff work first.

Clicking the links will lead to a not found error, as we need to add the pages they link to. When you are done, go back to the terminal running the web server and press C trl + C to stop it.

We have our main menu, but we are running it on our computer, not on the robot. Let’s put it on the robot.

We are going to set up PyInfra to copy these files over to our robot, and start up a server when our robot starts. We can extend deploy/deploy_services.py by adding this to the end:

code = files.sync(
name="Update web server code",
src="robot_control", dest="robot_control")
deploy_service("web_server",
"-m http.server --directory robot_control",
True, code.changed)

We start by syncing the robot_control folder over, which has our web server code. We then use the deploy_service function again with different parameters.

The command line looks a bit different, as instead of launching a Python file, we’re launching a web server sharing that directory.

We can now deploy this using pyinfra inventory.py deploy_services.py.

You will need to point your phone at your robot’s address. On a computer or iOS device, you can put <hostname>.local:8000 in the address bar, substituting <hostname> for your robot’s hostname.

On Android, you will need the IP address. You can get this via SSH using ip addr show wlan0. You’ll see output similar to the following:

$ ip addr show wlan0
3: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether d8:3a:dd:5a:53:70 brd ff:ff:ff:ff:ff:ff
inet 192.168.0.137/24 brd 192.168.0.255 scope global dynamic noprefixroute wlan0
valid_lft 86213sec preferred_lft 86213sec
inet6 fe80::53f2:c37b:56f3:a55d/64 scope link noprefixroute
valid_lft forever preferred_lft forever

The 4 numbers after the word inet will be your Raspberry Pi’s IP address – for example, 192.168.0.137. You can then use <your address>:8000 on an Android phone. This number may change on different networks, so you will need to look it up again.

If the text looks too small on a phone, ensure you’ve added the meta name="viewport" section in the head.

We can now see the menu on our phone, running from the robot! It doesn’t do much yet, so let’s make it drive something!

Driving the robot manually will mean building more HTML and CSS, but also introducing new elements like JavaScript. We’ll start with a simple page and build out the elements needed in it.

Create the file robot_control/manual_drive.html with the following content:

<!DOCTYPE html>
<html>
<head>
<title>Robot control - Manual drive</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Robot control - Manual drive</h1>
<a href="index.html">Back to menu</a>
</body>
</html>

This has the familiar html, head, body tags, the link to the stylesheet, and an anchor link back to the main menu.

We will make this page more interesting later, but for now, it has a title and a link back.

You can send this to the robot, and you will be able to click the Manual drive link in the menu to show this quite empty screen. Let’s liven it up by adding a joystick.

We will use a component someone else built to make our joystick, the bobboteck/Joystick library from https://github.com/bobboteck/JoyStick. We will configure PyInfra to set this up for us. Insert the highlighted code into deploy/deploy_services.py:

html = files.sync("robot_control", "robot_control")
files.directory(
name="Create robot_control/libs",
path="robot_control/libs"
)
files.download(
name="Download joystick widget",
src="https://github.com/bobboteck/JoyStick/raw/master/joy.js",
dest="robot_control/libs/joy.js"
)
code = files.sync(

In the preceding code, we’ve created the directory robot_control/libs to store libraries like this. We then download this joystick library into that folder.

We can now add that joystick to robot_control/manual_drive.html:

<!DOCTYPE html>
<html>
<head>
<title>Robot control - Manual drive</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="libs/joy.js"></script>
</head>
<body>
<h1>Robot control - Manual drive</h1>
<a href="index.html">Back to menu</a>
<div id="joydiv" style="width:50vh;height: 50vh;"></div>
<script type="module">
var joystick = new JoyStick(
'joydiv',
{} ,
function(stickData) {
console.log(stickData.x, stickData.y);
}
);
</script>
</body>
</html>

The highlighted sections show the changes. The script src line loads the joy.js library into our page. JavaScript lets us build interactive programs that run on our web page and can either be loaded from files like joy.js or embedded in the script tag shown below.

To put this joystick on the page, our code needs an element to hold it. In HTML, a div is a section containing other elements – in this case, a placeholder for a joystick. We give this a few parameters:

  • id – We can use an id to refer to this element later with the unique identifier joydiv.
  • style – We add some local style for this element. 50vh means a percentage of the viewport height. This height is based on the size of your screen or window. Setting the width and height to this means that the joystick will be scaled to fit around half the screen by its height.

After the div tag, we add a script element. It is important that the type here is module. In this form, instead of loading from a file, it has JavaScript code to run inside the element.

This JavaScript code uses the joy.js library to create a JoyStick object, with a set of parameters:

  • We give it the id of our joydiv element. The library will draw a joystick using that element.
  • We then give an empty set of options {}. These can be used to customize the joystick later.
  • We then provide a function, which will be called whenever the joystick control is touched or moved on the screen. This function takes a parameter stickData with information about the state of the joystick.

The stickData.x and stickData.y members hold the joystick position relative to its center in values -100 to 100. The function logs the joystick position to the console.

You can set this up on the robot by running pyinfra inventory.py deploy/deploy_services.py. Now point your phone or computer at your menu again, and select Manual drive.

The following screenshot shows what you should see:

Figure 7.5 – The manual control joystick screen

Figure 7.5 – The manual control joystick screen

Figure 7.5 – The manual control joystick screen

The screen should show the title, with the back button, and below this, a large green joystick. You should be able to drag the inner circle, and when you let go, it will return to the center. But how do you see the console.log output? You’ll need to load the page on your computer for this.

In the browser, right-click on the page, and click I nspect to see the developer panel. See the next screenshot:

Figure 7.6 – Using the JavaScript console with the joystick

Figure 7.6 – Using the JavaScript console with the joystick

Figure 7.6 – Using the JavaScript console with the joystick

The preceding figure shows how to summon the JavaScript console from the developer tools:

Depending on your browser, click the indicated icon/word to show the console.

Move the joystick on the screen using your mouse’s left button.

You should now see the joystick values scrolling on the console, as shown here.

The text you will see will be something like the following:

59 28 manual_drive.html:17
59 32 manual_drive.html:17
59 33 manual_drive.html:17
59 34 3 manual_drive.html:17
60 34 manual_drive.html:17

What you are seeing here first are the coordinates of the joystick. Following this, you see the file name and line number of the console message. On some lines, because the messages are repeated, you will see another number, either in front of the file name, or the whole line – this shows the number of repetitions.

Let’s do a little troubleshooting if there are problems at this point.

If you are not seeing the joystick control, there are a few things you can check:

  • First, ensure you have opened the JavaScript console as seen above.
  • If you see 404 errors, ensure that you have libs/joy.js (and not lib without an s).
  • On the Raspberry Pi, via SSH, do a ls robot_control/libs to see if joy.js is present.
  • Check your PyInfra code to ensure that lib is being sent to the Raspberry Pi.
  • If there aren’t errors, and the joystick isn’t visible or is tiny, double-check the style attribute.
  • If the console output is not showing joystick move output, ensure that the function to log stickData is part of the parameters for the joystick.
  • You should now be able to move the joystick and see the console output.

This is fun, but how about connecting it to the robot to drive it for real? We’ll need MQTT for that, which we’ll cover in the next section.

The phone app runs on HTML and JavaScript. This cannot directly connect to network services like MQTT and, therefore, requires WebSockets.

We will need to configure Mosquitto on the robot to allow WebSockets. We then need to install another JS library, and then connect this to our joystick.

WebSockets will allow JavaScript to open and keep a persistent connection to our robot via MQTT, allowing us to publish and subscribe to messages. WebSockets are the only option to communicate directly from our web app to MQTT. This is not enabled by default in Mosquitto, so we will need to enable this.

We can configure Mosquitto with a configuration file.

Create the file deploy/robot_mosquitto.conf:

password_file /etc/mosquitto/passwd
allow_anonymous false
listener 1883
protocol mqtt
# Websockets
listener 9001
protocol websockets

Mosquitto listens by default on port 1883 using the MQTT protocol. However, when we add a config file, we must explicitly enable that again. We expose the WebSocket MQTT port on 9001. Mosquitto won’t enable WebSockets without the password file specified and anonymous connections turned off.

Let’s use PyInfra to set this file up in the deploy/deploy_mqtt.py file. First, we need to import the files task:

from pyinfra.operations import \
apt, systemd, server, files

Then we can add this task to update the file before the system.service task:

mosquitto_files = files.put(
name="Configure mosquitto",
src="deploy/robot_mosquitto.conf",
dest="/etc/mosquitto/conf.d/robot.conf",
_sudo=True
)
if mosquitto_packages.changed or mosquitto_files.changed:
# restart mosquitto
systemd.service(
name="Restart/enable mosquitto",
service="mosquitto",
running=True,
restarted=True,
daemon_reload=True,
_sudo=True,
)

The mosquitto_files task copies over the conf file into /etc/mosquitto/conf.d, where Mosquitto will read it as configuration when it starts. We need to ensure it restarts to pick up this new configuration, so the next line will restart it when either mosquitto_packages or mosquitto_files has changed.

Power the Raspberry Pi from a desk power supply for this test. Use another terminal in the top folder of the project to run pyinfra inventory.py deploy/deploy_mqtt.py. The operation should end in a summary like this:

--> Results:
Groups: inventory / robots
[learnrob3.local] Changed: 2 No change: 1 Errors: 0

Mosquitto is now listening for phone MQTT connections. Let’s extend our page to connect to it.

Our web app will need a library to handle MQTT connections. The library mqtt.js is designed for this. In deploy/deploy_services.py, add the following after the joy.js download:

files.download(
name="Download mqtt js",
src="https://unpkg.com/[email protected]/dist/mqtt.esm.js",
dest="robot_control/libs/mqtt.js"
)

This will download an ECMAScript Modules (ESM) variant of mqtt.js, which will let us import it into our code.

We will need details for our page to connect back to the robot. Add the file robot_control/.env.js with your robot’s details:

export const env = {
PI_HOSTNAME: "learnrob3.local",
MQTT_USERNAME: "robot",
MQTT_PASSWORD: "robot",
};

These placeholder values should be replaced with your Pi hostname (or IP address for Android phones), along with the MQTT username and password you chose in your deploy/deploy_mqtt.py file.

The file .env.js contains secrets, and so should not be added to Git. Add it to .gitignore instead with echo .env.js >> .gitignore.

This creates a data structure named env and exports it, so when this JS file is imported, we can use these values.

We will consume these values in a new file robot_control/mqtt_client.js, which will print errors from mqtt.js when we connect. Add the file robot_control/mqtt_client.js:

import { env } from "./.env.js";
import mqtt from "./libs/mqtt.js";
export function connect() {
let client = mqtt.connect(\`ws://${env.PI_HOSTNAME}:9001\`, {
username: env.MQTT_USERNAME,
password: env.MQTT_PASSWORD,
});
client.on("connect", () => {
console.log("Connected to MQTT broker");
});
client.on("error", (err) => {
console.log("Error connecting to MQTT broker");
console.log(err);
});
return client;
}

This code imports our environment from .env.js, and then mqtt. Only exported items are available to the module when importing.

This mqtt_client.js file exports a connect function. The connect function first creates an mqtt client, using our env details. The client.on calls set up handlers to print messages to a JavaScript console when client events happen, so we can see mqtt connecting.

This app has no security mechanism, authentication, or passwords. It is beyond this book’s scope but is worth serious consideration for further research if you plan to use this on shared Wi-Fi.

This code would let us connect, but we need to wire it into the manual drive joystick to make it do something useful for us.

Connecting the manual drive joystick via MQTT

Section titled “Connecting the manual drive joystick via MQTT”

Our joystick code needs to be changed to send data via MQTT instead of just printing it. There’s a little conversion needed too.

The following code is the script section from robot_control/manual_drive.html, with the new code highlighted:

<script type="module">
import { connect } from './mqtt_client.js';
let mqttClient = connect();
var joystick = new JoyStick(
'joydiv',
{} ,
function(stickData) {
console.log(stickData.x, stickData.y);
let speed = stickData.y / 100;
let direction = stickData.x / 100;
console.log("Speed:", speed, "Direction:", direction);
mqttClient.publish("motors/wheels", JSON.stringify(
[speed + direction, speed - direction]
));
}
);
</script>

The script here starts by importing the mqtt_client.js library we made earlier. We then use the connect function to make an mqttClient variable, holding our link.

We then divide both x and y by 100, to give speed and direction values in the -1 to 1 scale our robot expects. We log that too.

We use mqttClient.publish to send this to the motors/wheels topic. We must use the JavaScript function JSON.stringify to convert data to a JSON string. This motors/wheels topic and format are the same as the path behaviors used in Chapter 6*, Drive and Turn – Moving Motors with MQTT and Python*.

Use pyinfra inventory.py deploy/deploy_services.py to send this to the robot. You’ll need to refresh the browser tab with the joystick or point your phone browser at it. You should now be able to use the joystick to drive the robot. Let’s troubleshoot any problems before we extend our system further.

If you see failures to connect or timeouts, try the following:

  • If you see 503 errors from unpkg during installation, rerun deploy_services – these sometimes happen if it’s busy.
  • It may take a second or so to connect, please wait when loading the page.
  • Ensure you have used the script type module – the MQTT import will not work without it.
  • Verify the hostname, username, and password.
  • Android doesn’t support .local addresses; you will have to use an IP address for the Raspberry Pi.
  • Check that MQTT has been set up, with WebSockets enabled. Run the PyInfra commands in the Enabling MQTT WebSockets section above.
  • Verify that Mosquitto is running via SSH to Raspberry Pi with systemctl status mosquitto. The third line of output should look like this:
    Active: active (running)
    You should also see this line near the bottom:
    Loading config file /etc/mosquitto/conf.d/robot.conf
    If not, double-check the deploy/robot_mosquitto.conf file, and run pyinfra.
  • We can see if Mosquitto has hit any issues, and if our app has connected to it. In an SSH session to the robot, type sudo tail /var/log/mosquitto/mosquitto.log to see Mosquitto’s internal log.

We can now drive our robot with the phone! Put your thumb on the pad, push up to go forward, and then pull left or right to turn the robot.

Our robot has autonomous path driving behavior, and we plan to add more. We aren’t going to drive it manually all the time. Let’s add more control options to our web app.

Adding more control options to the web app

Section titled “Adding more control options to the web app”

Our application has let us take control of driving the robot, but we can let it do more. We can extend it to start and stop behaviors, and even turn off the robot. Let’s see how we can use what we’ve learned with Python, MQTT, HTML, and JavaScript to build this launcher.

The launcher will make use of the common mqtt_behavior code. Add the file robot/launcher_service.py, starting with the following code:

import subprocess
from common.mqtt_behavior import connect, publish_json
def print_message(client, userdata, msg):
print(f"{msg.topic} {msg.payload}")
def start_systemd_unit(client, userdata, msg):
unit_name = msg.payload.decode()
subprocess.run(["systemctl", "start", unit_name])
print(unit_name, "started")
def stop_systemd_unit(client, userdata, msg):
unit_name = msg.payload.decode()
subprocess.run(["systemctl", "stop", unit_name])
print(unit_name, "stopped")
def poweroff(client, userdata, msg):
print("Powering off")
subprocess.run(["poweroff"])
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
client.subscribe("launcher/#")
client.publish("leds/set", "[1, 0, 0, 255]")
client = connect(on_connect=on_connect, start_loop=False)
client.message_callback_add("launcher/#", print_message)
client.message_callback_add("launcher/start", start_systemd_unit)
client.message_callback_add("launcher/stop", stop_systemd_unit)
client.message_callback_add("launcher/poweroff", poweroff)
client.loop_forever()

This code makes use of many concepts we’ve already seen. However, the subprocess module is new. This is a Python library for starting other programs, namely systemctl and poweroff. By having MQTT handlers that interact with these commands, we make them available to our robot menu.

The launcher/start and stop messages take a unit name as their payload, and pass this along to systemctl to start or stop the relevant service.

The poweroff message will ignore the payload.

It’s optimistically publishing a message for an LED to a leds/set topic (something to handle in inventor_hat_service?).

To deploy it, let’s add it and something for it to launch into the deploy/deploy_services.py file:

code = files.put(
name="Update launcher code",
src="robot/launcher_service.py",
dest="robot/launcher_service.py")
deploy_service("launcher_service","robot/launcher_service.py",
True, common.changed or code.changed)

We said we’d use it to run a behavior path but to make that available to systemctl, it also needs a service:

code = files.put(
name="Update behavior_path code",
src="robot/behavior_path.py",
dest="robot/behavior_path.py")
deploy_service("behavior_path","robot/behavior_path.py",
False, common.changed or code.changed)

This looks a lot like our other services, but auto_start is set to False, so this will only start when asked by systemctl. Running pyinfra inventory.py deploy/deploy_services.py will make the launcher available on the Raspberry Pi.

Splitting our system into services means we can target modifications or troubleshooting to specific parts of the robot and app system.

Now we need to add it to our app.

Making a control page for the drive path behavior

Section titled “Making a control page for the drive path behavior”

We already have a link for a behavior path but no file for it to go to, so let’s add the file robot_control/behavior_path.html to connect that link to our launcher:

<!DOCTYPE html>
<html>
<head>
<title>Robot control - Drive path</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Robot control - Drive path</h1>
<a href="index.html">Back to menu</a><br>
<button id="start">Start</button>
<script type="module">
import { connect } from './mqtt_client.js';
let mqttClient = connect();
document.getElementById("start")
.addEventListener(
"click",
function() {
mqttClient.publish("launcher/start", "behavior_path.service");
}
);
</script>
</body>
</html>

This page starts with the usual title, CSS, and viewport. We then have a button tag with id set to start, which will appear on the screen as a clickable button. The JavaScript loads the mqtt client, then finds the start button, and adds an event listener.

An event listener in JavaScript lets it handle something happening in the browser – in this case, when the button is clicked. It will then call the function given inside, which will publish the launcher/start message, which will cause the launcher to start the behavior.

Try this on the robot with pyinfra inventory.py deploy/deploy_services.py. You will need to reload the index menu to see the new button.

From the menu, click the Drive path text, and then, on that page, click on Start to start the behavior and the robot should start to drive in a path.

Troubleshooting steps for this are similar to those for connecting the joystick via MQTT. We can complete our phone control system by adding an off button to the app.

We have many parts in place to add this button. The launcher is ready to accept power-off messages, and we can add a menu item and power-off page to do it. The code for the power-off page should now look pretty familiar. We’ll have a page with a Turn off button to confirm the action, so accidental clicks are less likely.

Add the file robot_control/power_off.html (you should be able to copy/paste the behavior path page and change a few things):

<!DOCTYPE html>
<html>
<head>
<title>Robot control - Power off</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Robot control - Power off</h1>
<a href="index.html">Back to menu</a><br>
<button id="turn_off">Turn off</button>
<script type="module">
import { connect } from './mqtt_client.js';
let mqttClient = connect();
document.getElementById("turn_off")
.addEventListener(
"click",
function() {
mqttClient.publish("launcher/poweroff", "");
}
);
</script>
</body>
</html>

This complete page example uses the elements we’ve now seen before:

  • The doctype declaration
  • A html element enclosing the whole page
  • A head with information about the page
    • A page title for the tab
      • A link to the stylesheet
      • The meta viewport to make it scale correctly
  • A body with our visible page
    • A heading line
      • A link back to the main menu
      • A button to perform the action, with an ID
      • A script to turn the button press into an mqtt action.

We will also need to add a link to the main menu in robot_control/index.html:

<ul>
<li><a href="manual_drive.html">Manual drive</a></li>
<li><a href="behavior_path.html">Drive path</a></li>
<li><a href="power_off.html">Power off</a></li>
</ul>

We can now send this page to the robot with pyinfra, using pyinfra inventory.py deploy/deploy_services.py.

You can now manually drive the robot from your screen or phone, and when you are done, go back to the main menu and use the power-off option. You now only need an SSH session when debugging!

After powering off, wait for the lights to stop flashing and pull out the USB-C plug.

Congratulations! The robot is now set up for remote control via MQTT.

In this chapter, we’ve designed and built a menu and joystick mobile web application to control our robot.

We looked at how systemd can be used to automatically start the services our robot needs to run. We gave the HAT service a way to indicate being ready on the robot with an LED and then set it up to automatically start when you turn on the robot.

You’ve seen how HTML, CSS, and JavaScript can be used for mobile applications, and how it can use MQTT to link to our robot.

Your robot has now gained the ability to be driven manually. It may take you a while to get used to handling it, and you will find yourself manually correcting for veer (motors behaving slightly differently).

We can launch other behaviors and turn it off too. You’ve made the robot fully controllable with your phone!

In the next chapter, we will look at how we’ll add distance sensing to our robot, and program it to avoid obstacles.

You could enhance the system in many ways. Here are some suggestions for building further:

  • The Inventor HAT Mini has LEDs. We’ve used one to show it’s on. Extend the Inventor HAT service to subscribe to and handle an leds/set topic with an LED index, r, g, and b values.
  • The styles are not quite what we designed. Take a look at https://www.w3schools.com/Css/ to find out more about ways to style elements. This is a deep rabbit hole!
  • Consider how to secure this. The services should get their passwords from a config, or an EnvFile (supported by systemd) set up by PyInfra.

There is suggested code for the first two challenges in the GitHub repository for this book. In the repository, go to main/chapter‑7/complete‑plus‑challenges. To access the repository link, follow the steps in the Download the example code files section in the Preface.

We will be using code based on these challenges in the next chapter. We cover the third challenge in more detail in Chapter 18, Taking Your Robot Programming Skills Further.

To find out more about the topics covered in this chapter, here are some suggestions:

  • Responsive Web Design with HTML5 and CSS: Build future-proof responsive websites using the latest HTML5 and CSS techniques, Fourth Edition can be used to learn HTML5 and CSS web design and make this interface more pleasing.
  • For getting more familiar with the JavaScript technologies used here, freeCodeCamp (https://www.freecodecamp.org/) is a valuable resource with self-learning modules.
  • There is a chapter on understanding systemd in Mastering Linux Network Administration, Jay LaCroix, published in 2015.
  • A full reference for systemd services can be found on the freedesktop manuals at https://www.freedesktop.org/software/systemd/man/systemd.service.html.