Skip to content
ImagineWorld

Protecting Robot Code with Git

node_idnode-book_learn-robotics-programming_chapter-04-protecting-robot-code-with-git
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num4
chapter_titleProtecting Robot Code with Git
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 4 — Protecting Robot Code with Git

Section titled “Chapter 4 — Protecting Robot Code with Git”

We’ve prepared an SD card for a Raspberry Pi, and we’ve planned some features that we will add to this robot. Those features will need us to build robot code and configuration on that same SD card. As you create and customize this robot code, you will invest many hours in getting it to do awesome things that, unless you take precautions, could all suddenly disappear. The programs are not the whole story, as you will also configure Raspberry Pi OS for use on the robot. You want to keep your code and config in case of disaster and to be able to go back if you make changes you regret.

This chapter will help you understand how exactly code or configuration can break and the disasters you might face while customizing code for your robot. We’ll then take a look at the three strategies for preventing this.

In this chapter, you will learn about the following:

  • Understanding how code can be broken or lost
  • Strategy 1 – Keeping code on a PC and uploading it
  • Strategy 2 – Using Git to go back in time
  • Strategy 3 – Automating Raspberry Pi setup with a script

For this chapter, you will require the following:

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.

Understanding how code can be broken or lost

Section titled “Understanding how code can be broken or lost”

Code and its close cousin, configuration, takes time and hard work. Code needs configuration to run, such as Raspberry Pi OS configuration, extra software, and necessary data files. Both need research and learning, to be designed, made, tested, and debugged.

Many bad situations can lead to the loss of code. This happened to me a week before taking robots to a show after weeks of work, and I learned the hard way to take this quite seriously. So, what can happen to your code? Let’s see in the next section.

SD card corruption is when the data on the SD card used to hold your code, Raspberry Pi OS, and anything you’ve prepared on it gets broken. Files become unreadable, or the card becomes unusable. The information on the SD card can be permanently lost.

If a Raspberry Pi unexpectedly loses power, this can damage the SD card, causing data loss. A hot Raspberry Pi doing busy work can slowly bake an SD card, damaging it. SD cards get damaged if something terrible happens electrically to the Pi via the GPIO pins or its power supply. MicroSD cards are also tiny and are quickly lost when not in the Pi.

We all make mistakes. Coding means trying things out. While some work out, some do not, and things break. At those times, you’ll want to go back and see what you’ve changed. You might be able to use differences to find the bug, or if your experiment looks like a dead end, you may want to go back to a known working version.

You can render your robot useless with the wrong configuration, such as the Pi not being on the network or booting anymore. An upgrade to system packages may go wrong and lead to code not working or needing extensive changes to the code for it to work again.

These problems can combine to cause real nightmares. I’ve seen changes in the code lead a robot to damage itself in a way that corrupted the SD card. I once updated packages on the operating system and knocked the power cable out, corrupting the SD card and breaking Raspberry Pi OS 2 weeks before a significant robot event, and it was painful rebuilding it. Many builders only learn this by suffering a few times – let’s try learning the easy way.

We want to back up the code and back up the OS configuration. In the rest of this chapter, we’ll look at some solutions to keep your robot’s software safe from many kinds of disasters. Let’s look at the first strategy for keeping code safe on a PC.

Strategy 1 – Keeping code on a PC and uploading it

Section titled “Strategy 1 – Keeping code on a PC and uploading it”

We’ve got an SSH bridge to our Raspberry Pi. We can use this to transfer our files, letting you write code on your computer, and then upload it. You can choose your editor and have the safety of more than one copy.

Which Editor to use?

Editing code requires software designed for this purpose. We recommend VS Code or PyCharm for Python. They also have integrated terminals. We will use the terminal often to interact with our headless robot.

We’re going to build out some tools to send code to the Raspberry Pi, in Python. Let’s get ourselves some example code to build with:

  1. First, make yourself a folder on the PC to store your robot project code in; for example, my_robot_project. From this point onward, file and folder names on your computer will be relative to this robot project folder. For example, the path robot/ will be a folder within my_robot_project or the name you gave it.
  2. Because we will have parts running on the robot, and parts to manage it from our computer, make a robot subfolder.
  3. Let’s make a test file, using your editor, that will just print a bit of text. Put this code into a file named robot/hello.py:
    print("Raspberry Pi is alive!")
    For Python beginners, this code runs a print function, which puts text onto the console. It has specifics for what it will print in brackets (), with the only item being a string – a bunch of characters in quotation marks: "something to print".

You now have the first file to run on your robot.

We are going to use PyInfra. PyInfra runs shell and other commands to set things up on a remote system, like the Raspberry Pi. It allows you to make changes and detect if changes are needed. We’ll use it for more complicated purposes, but for now, let’s start by getting it set up to copy our code to the robot so we can run it there:

Although outside the scope of this book, if you are installing Python tools on a computer, it’s good practice to put them in a Python environment. The poetry tool is good for this. Files for poetry are included in the chapter’s code.

  1. Start a terminal on your computer, and type pip install pyinfra. You may need to restart your terminal to be able to use the pyinfra command. PyInfra lets us use code to manage our Raspberry Pi.
  2. We need to create a file listing our robot’s details (we’ll add more to it) named inventory.py in the my_robot_project folder, above the robot folder:
    robots = [
    ("hostname.local", {"ssh_user": "your username"})
    ]
    You should use your robot hostname and username. In Python terms, we’ve created a list of targets (robots), although there’s only one, PyInfra, that can deal with multiple targets. In that list is a small group (a Python tuple) of the target hostname followed by any special attributes. The special attribute data is between the curly braces - {}. Each attribute is a key name (ssh_user) and then a bit of data, a value. This set of "key": "value" pairs in Python is known as a dictionary.
  3. Ensure your terminal is in the my_robot_project folder. We can copy our files to the Pi in the terminal with this command:
    pyinfra inventory.py files.sync src=robot dest=robot
    We are syncing our local source (src) folder, my_robot_project/robot, to the remote destination (dest) folder, robot. You will see the code evaluate the state of the files, and synchronize it over to the robot:
    --> Loading config...
    --> Loading inventory...
    --> Connecting to hosts...
    [learnrob3.local] Connected
    --> Preparing operation...
    [learnrob3.local] Ready: sync
    --> Proposed changes:
    Groups: robots / inventory
    [learnrob3.local] Operations: 1 Change: 1 No change: 0
    --> Beginning operation run...
    --> Starting operation: Files/Sync (src=robot, dest=robot)
    [learnrob3.local] Success
    --> Results:
    Groups: robots / inventory
    [learnrob3.local] Changed: 1 No change: 0 Errors: 0
    This is a sync operation. It detects that there is a change to make to the files on the Raspberry Pi, and then makes this change. Note this output will have your hostname instead. Running it again should result in No change: 1 until you change a file.
  4. To run this code, use SSH to log in to the Pi using the username and hostname you chose again:
  5. Then try the following command:
    danny@learnrob3:~ $ python robot/hello.py
    Raspberry Pi is alive!

Remote editing is initially more convenient; however, you must then remember to copy code back to the PC. We’ll also see later how PyInfra from the PC will let us manage more than the code on the Raspberry Pi.

Making a file we can reuse to update the code

Section titled “Making a file we can reuse to update the code”

We can make a file for updating code, which we can keep for later. Add a deploy directory, and in the deploy/update_code.py file, add the following:

from pyinfra.operations import files
files.sync(src="robot", dest="robot", delete=True, exclude=("*.pyc", "__pycache__", ".vscode"))

This script will perform the sync, and also ensure certain files are excluded from it. This sends over any changed files in the robot folder, storing them in a robot folder on the Raspberry Pi. With delete=True, it will also handle files being renamed or removed.

We can now update our code from our computer with pyinfra inventory.py deploy/update_code.py. This command line means using the inventory from inventory.py, run the operations in the PyInfra script deploy/update_code.py. The Python code here has a from <library> import <symbol>. When you see import in Python, it means we are bringing in functionality from some other code to use in our code – in this case, file syncing.

Putting this PyInfra code into a Python script instead of a bare command comes with a few benefits:

  • This is a building block to chain together more complex installations and operations.
  • We will be able to let the script remember the options as they become more complex too.
  • This code will only make changes when a file is different. This property is known as idempotency. This has the effect that when we chain things together, later actions may only need to run when earlier operations made changes, making updates faster.

These benefits will become more apparent as our PyInfra deploy folder grows. Let’s just troubleshoot any problems.

If you are having trouble, look at the messages from PyInfra:

  • If you see pyinfra: command not found, ensure you have run pip install pyinfra. You may need to restart the terminal for it to be available.
  • If you see Usage: pyinfra [OPTIONS] INVENTORY OPERATIONS, then this means you likely missed inventory.py before naming the pyinfra script.
  • If you see Could not resolve hostname (some hostname.local), this means that either the hostname in your inventory doesn’t match the robot, the robot is turned off, or it is not reachable from your computer network for some reason.
  • If you see Authentication error, this may mean your inventory username does not match the one you are using for SSH, which you can correct in the inventory.py file. If this username is correct, it may also mean that you do not have a matching SSH key. You will need to check when setting this up and making the SD card in C hapter 3*, Preparing a Headless Raspberry Pi for a Robot*.
  • If you see ‑‑> pyinfra error: No deploy file: deploy/update_code.py, then check you have named the file, that you put it in the deploy folder, and that you have spelled it the same way for pyinfra.
  • If you see something like this, then this likely means there is a mistake in your deploy/update_code.py file. Check it carefully against the example code:
    An internal exception occurred:
    File "deploy/update_code.py", line 3
    files.sync(src="robot", dest="

You should now have troubleshot most of the common problems, and be able to sync code this way.

This strategy is a great start to making code safer. By working on your laptop/PC and copying/syncing to the Pi, you’ve guaranteed that the robot is not the only copy of up-to-date code and can be sure the code you see on your computer is the code you have on the Pi. You can also use any code editor you like on the PC and spot some errors before they even get to the Raspberry Pi. Next, let’s see how we can track changes to our code.

Strategy 2 – Using Git to go back in time

Section titled “Strategy 2 – Using Git to go back in time”

Git is a popular source control system that keeps a history of changes you’ve made to code. You can review changes, restore older versions, and keep a commented log of why you made the changes. Git also lets you store code in more than one location in case your hard drive fails. Git stores code and its history in repositories, or repos. You can make branches – copies of the code to try ideas – and later merge those back to the main branch.

I will get you started, but this section can only scratch the surface of what you can do with Git. Let’s begin:

  1. Install Git by following the instructions at https://git-scm.com/book/en/v2/Getting-Started-Installing-Git for your computer. If you are using Windows or macOS, I would suggest using the GitHub app for easier setup.
  2. Git requires you to set your identity using a command line on your computer:
    > git config --global user.name "<Your Name>"
    > git config --global user.email <your email address>
  3. We can then initialize our project by making sure we are in the project folder (my_robot_project) with:
    > git init && git checkout -b main
    Initialized empty Git repository in C:/Users/danny/workspace/my_robot_project/.git/
  4. We can add our code files:
    > git add inventory.py robot/hello.py deploy/update_code.py
  5. What is added needs to be committed. We can see what we’ll commit with:
    > git status
    On branch main
    Untracked files:
    (use "git add <file>..." to include in what will be committed)
    .vscode/
    pyinfra-debug.log
    No commits yet
    Changes to be committed:
    (use "git rm --cached <file>..." to unstage)
    new file: deploy/update_code.py
    new file: inventory.py
    new file: robot/hello.py
    You may see some items in red in an untracked files section – things like .vscode, debug logging files, and other temporary files. This is to be expected.
  6. We can turn these files into a commit. This makes a “checkpoint” in history:
    > git commit -m "Initial"
    [main (root-commit) d9d9995] Initial
    3 files changed, 7 insertions(+)
    create mode 100644 deploy/update_code.py
    create mode 100644 inventory.py
    create mode 100644 robot/hello.py
    The ‑m part specifies a log message for this commit. In the following message, the series of numbers d9d9995 will be unique for every commit – yours will be different.
  7. We can now see our commit by getting the history log:
    > git log
    commit d9d9995b7cf6937e168e93be3d56f9eaf71143e2 (HEAD -> main)
    Author: Your Name <[email protected]>
    Date: <todays date and time>
    Initial

We now have our initial git commit and can see the history. Let’s make it more interesting by adding another change to the code.

Let’s modify the code in robot/hello.py, changing it to this:

import socket
print(f"{socket.gethostname()} is alive!")

We can send this over to the Pi again with pyinfra inventory.py deploy/update_code.py. When you run it on the Pi, it will now say <your hostname> is alive!. What about Git? Let’s see how this code is different from before:

> git diff
diff --git a/robot/hello.py b/robot/hello.py
index f7cf60e..c859766 100644
--- a/robot/hello.py
+++ b/robot/hello.py
@@ -1 +1,3 @@
-print("Hello, world!")
+import socket
+print(f"{socket.gethostname()} is alive!")

The preceding is Git’s way of showing the differences. Git interprets the changes as taking away a print line, and in its place adding an import and then a print line. We can add this into Git to make a new version, and then use git log again to see both versions:

> git add robot\hello.py
> git commit -m "Show the robot hostname"
[main 500b580] Show the robot hostname
1 file changed, 3 insertions(+), 1 deletion(-)
> git log
commit 500b58093bb6827c612479e85cc3620756fef50e (HEAD -> main)
Author: Your Name <[email protected]>
Date: Thu Nov 23 20:41:40 2023 +0000
Show the robot hostname
commit d9d9995b7cf6937e168e93be3d56f9eaf71143e2
Author: Your Name <[email protected]>
Date: Thu Nov 23 20:26:17 2023 +0000
Initial

With this method, you can go back to previous versions and compare them, protecting yourself against changes you might regret.

The figure below shows how code changes look when code is in GitHub, to illustrate what Git can track:

Figure 4.1 – Code changes in Git

Figure 4.1 – Code changes in Git

Figure 4.1 – Code changes in Git

Figure 4.1 shows a Git history, with black dots representing commits, and arrows between them representing time. The oldest is at the top. There is an initial commit adding our deploy folder, inventory, and robot folder. The next commit is where we modify the robot/hello.py script to add the hostname.

The final change was an erroneous “whoops” added in a file. Try it – but don’t commit it. We don’t want that change. We can undo that and not commit it. Use git diff again to see the difference before committing it:

> git diff
diff --git a/deploy/update_code.py b/deploy/update_code.py
index dce14d6..3bf2f43 100644
--- a/deploy/update_code.py
+++ b/deploy/update_code.py
@@ -1,3 +1,5 @@
from pyinfra.operations import files
-files.sync(src="robot", dest="robot", delete=True, exclude=("*.pyc", "__pycache__", ".vscode"))
+files.sync(src="robot", dest="
+ whoops
+robot", delete=True, exclude=("*.pyc", "__pycache__", ".vscode"))

If we don’t want it, we can pick up what we had before:

> git checkout deploy/update_code.py
Updated 1 path from the index

This will bring back the version you last committed, without an incorrect change. You can run git diff again:

> git diff
>

If there are no changes, git diff shows no output.

We have only just scratched the surface of the power of Git. See the Further reading section for references on how to do far more with Git. Editors like VS Code and PyCharm include Git integrations.

Now that we can go back and forward in time with our code, we can be more confident in making changes. Just remember to commit frequently – especially after making something work! Next, let’s see how to keep the configuration and installed packages.

Strategy 3 – Automating Raspberry Pi setup with a script

Section titled “Strategy 3 – Automating Raspberry Pi setup with a script”

Git and copying code are great for keeping code safe, but they don’t help you reinstall and reconfigure Raspberry Pi OS on a card. However, we’ve already brought in a powerful tool – PyInfra. This can be used to manage configuration and software on the Raspberry Pi that will support our robot.

This can let us automate everything, as a headless system, and recreate things if it all goes wrong.

We’ll need a few helper scripts (alongside update_code.py) in the deploy folder and one to make a new robot running all the other tasks.

Let’s start by making update packages and then installing some Python basics on the robot that we’ll need for later.

When you’ve installed Raspberry Pi OS on an SD card, the packages and package index can be out of date. It’s common to update them before installing other packages.

We can make a script to manage this for us. Create the file deploy/update_packages.py with the following:

from pyinfra.operations import apt
apt.update(
name="Update apt cache",
_sudo=True,
)
apt.upgrade(
name="Upgrade all packages",
_sudo=True,
)

PyInfra is built out of operations. We’ve previously used the files.sync operation to send files over. This code imports the apt operations, using apt.update to update the package index, and apt.upgrade to install updated packages from that index. Notice they also have a _sudo=True option, running as the superuser.

PyInfra commands have a pattern of pyinfra <inventory> <operations>. Run this with pyinfra inventory.py deploy/update_packages.py to update all packages. Here’s an excerpt of what to expect:

--> Proposed changes:
Groups: inventory / robots
[learnrob3.local] Operations: 2 Change: 2 No change: 0
--> Beginning operation run...
--> Starting operation: Update apt cache
[learnrob3.local] Success
--> Starting operation: Upgrade all packages
[learnrob3.local] Success
--> Results:
Groups: inventory / robots
[learnrob3.local] Changed: 2 No change: 0 Errors: 0

This will look a lot like a code change, with a different count of operations. It shouldn’t take very long because we did an update at the end of C hapter 3*, Preparing a Headless Raspberry Pi for a Robot*.

Let’s check that everything works before we carry on.

If the operations PyInfra performs run into any trouble, it will report them on the console:

--> Starting operation: Update apt cache
[learnrob3.local] Reading package lists...
[learnrob3.local] E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
[learnrob3.local] E: Unable to lock directory /var/lib/apt/lists/
[learnrob3.local] W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
[learnrob3.local] W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)
[learnrob3.local] Error: executed 0/1 commands
--> pyinfra error: No hosts remaining!

You should first check with the problems in the Getting started with P y I nfra section.

You may also see Could not open lock file. This means you have missed the _sudo=True option. A normal user is not able to make this change and needs to sudo to become a superuser to be able to perform this update.

You should now have this working so far. We are going to need more packages on our robot. Let’s see how to do that.

Some of the code we’ll run on our robot will need base packages. This is an operation that, once complete, won’t change.

Make a deploy/base_packages.py file with the following:

from pyinfra.operations import apt
apt.packages(
name="Install python pip and i2c tools",
packages=["python3-pip", "python3-smbus", "i2c-tools"],
_sudo=True,
)

This code imports the apt set of operations again. The packages operation will ensure that a list of packages is present, and only change if they are missing. We have python3‑pip, to install Python packages, python3‑smbus for i2c bus access, and i2c‑tools, which we’ll use for debugging i2c.

When you run this, it’ll take a short while to install the packages, then you’ll see:

--> Preparing Operations...
Loading: deploy/base_packages.py
[learnrob3.local] Ready: deploy/base_packages.py
--> Proposed changes:
Groups: robots / inventory
[learnrob3.local] Operations: 1 Change: 1 No change: 0
--> Beginning operation run...
--> Starting operation: Install python and i2c tools
[learnrob3.local] Success
--> Results:
Groups: robots / inventory
[learnrob3.local] Changed: 1 No change: 0 Errors: 0

You will modify and rerun this script if more base packages are needed. If you run it again without changes, PyInfra will know that no change is needed:

--> Proposed changes:
Groups: inventory / robots
[learnrob3.local] Operations: 1 Change: 0 No change: 1
--> Beginning operation run...
--> Starting operation: Install python and i2c tools
[learnrob3.local] No changes
--> Results:
Groups: inventory / robots
[learnrob3.local] Changed: 0 No change: 1 Errors: 0

This is idempotency, an important concept that means our PyInfra deployments only make changes when a change is needed.

We’ve made a collection of scripts – what if we want to make them all together?

We have a few deployment things to do here: updating code, updating packages, and setting up Python packages. If we wanted to recreate the SD card, we could use a larger one, or if there was corruption, we’d want to run them all against this target. This will save a lot of setup time, and can also be used to create new Raspberry Pi robots.

Create the deploy/deploy_all.py file:

from deploy import \
update_packages, \
base_packages, \
update_code

We can run this with pyinfra inventory.py deploy/deploy_all.py:

--> Proposed changes:
Groups: robots / inventory
[learnrob3.local] Operations: 4 Change: 2 No change: 2
--> Beginning operation run...
--> Starting operation: Update apt cache
[learnrob3.local] Success
--> Starting operation: Upgrade all packages
[learnrob3.local] Success
--> Starting operation: Install python and i2c tools
[learnrob3.local] No changes
--> Starting operation: Files/Sync (src=robot, dest=robot, delete=True)
[learnrob3.local] No changes
--> Results:
Groups: robots / inventory
[learnrob3.local] Changed: 2 No change: 2 Errors: 0

It collects the 4 operations from our files (the update has 2 operations) and runs them all. The update/upgrade operations will always run because they are not idempotent, and they always check for potential updates. However, the base packages and code operations show no changes, which is correct as we’ve made no changes.

You’ve started to build tools to help you set up and restore your robot’s code and settings. We want to carry on building the habit of putting things in Git. Whenever you have something that works, this is a good time to add things to Git.

Run the following to add our tools to Git:

> git add deploy/*.py
> git status
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: deploy/base_packages.py
new file: deploy/deploy_all.py
new file: deploy/update_packages.py
> git commit -m "More deployment tools"
[chapter-4 6b7718d] More deployment tools
3 files changed, 22 insertions(+)
create mode 100644 deploy/base_packages.py
create mode 100644 deploy/deploy_all.py
create mode 100644 deploy/update_packages.py

Great, your deployments are now safely in the Git history, so you can extend them and track what you’ve changed. While it may be tempting to change things and files by hand on the Raspberry Pi, avoiding it means you can use this method to answer the questions “What did I just do?”, “How did I make that work?”, or even “Why doesn’t that work now – what changed?”. When we need it, we’ll use this to modify other configurations on the Raspberry Pi.

Before you remove power from the Pi, do not forget to SSH into your Raspberry Pi, and issue sudo poweroff to finish the session.

You’ve now seen how PyInfra, combined with Git gives us a powerful, reliable, and repeatable way to manage our Raspberry Pi.

In this chapter, you have learned how to look after your code and configuration. You have seen how things can go wrong, and the strategies to protect your work from them. You have a starting point with PyInfra (over SSH) and Git that you can use together to be experimental and fearless about changes to your robot.

You can edit code or configuration on your computer, giving you a copy other than what is on the robot and letting you use powerful editors. You can use Git to go back in time, so you can wind back from mistakes and experiments, or just see the differences. You can use PyInfra to take a fresh Raspberry Pi OS install and turn it into a copy of your robot, restoring it to where things were if it goes wrong.

In the next chapter, we’ll start to build a basic robot. We’ll assemble the robot chassis with motors and wheels, determine what power systems to use, and then test fit the overall shape of our robot. Bring a screwdriver!

You can try these to deepen your understanding:

  1. Make a change to hello.py – maybe update or personalize this message.
  2. Use pyinfra to update it, then SSH to run it.
  3. Use git diff to inspect your difference.
  4. Use git add and git commit to put it into your history.
  5. I recommend finding out more about how Git can be used to look after your code. Use the Further reading section to find out more about Git, and ways to work it into your coding workflow. Git can be complicated, but it is a tool worth learning.
  6. Consider making yourself a GitHub account, and using GitHub guides to keep a copy of your code there. This will further protect you against problems on your computer.

You can get more information to continue your journey with the following resources: