Using IoT Core gateways with a Raspberry Pi
Fengrui Gu | Software Engineer | Google
Contributed by Google employees.
This tutorial shows you how to set up and use gateways on IoT Core. From the documentation, a "gateway is a device that connects less capable devices to IoT Core and performs several tasks on the device's behalf, such as communication, authentication, storage, and processing."
In this tutorial, you create a gateway that manages two devices: a simple LED and a DHT22 sensor. Neither device is directly connected to IoT Core, but receives updates from and publishes telemetry events to the cloud through the gateway.
Architecture
The following diagram gives a high-level overview of how the device/gateway architecture is structured.
Objectives
- Create a new gateway and bind devices to it.
- Demonstrate changing configurations on a device bound to a gateway.
- Demonstrate sending telemetry from a bound device to IoT Core.
Before you begin
This tutorial assumes that you have a Google Cloud account and have completed the setup steps outlined in the IoT Core getting started guide. For quick cleanup, create a new Google Cloud project to use just for this tutorial.
For more information about the different authentication methods that IoT Core offers, see Authenticating over the MQTT bridge.
Costs
This tutorial uses billable components of Google Cloud, including the following:
- IoT Core
- Pub/Sub
This tutorial should not generate any usage that would not be covered by the free tier, but you can use the pricing calculator to generate a cost estimate based on your projected usage.
Required hardware
- Laptop or desktop with
git
andpython3
- Raspberry Pi 3 Model B (Other models should work, but they have not been verified.)
- MicroSD card for Raspberry Pi OS (8GB+ recommended)
- MicroSD card reader
- USB keyboard
- MicroUSB to USB-A cable
- Monitor with HDMI input
- HDMI cable
- LED
- Adafruit DHT22 Temperature/Humidity Sensor
- 10k Ohm resistor
- Breadboard and jumper wires
- Jumper wires
Enable IoT Core and Pub/Sub APIs
Click Enable API for each of the following:
Create a registry
First, create a device registry that will contain your gateway and devices.
- Open the IoT Core console.
- Ensure that the right project is selected in the upper left.
- Click Create a device registry.
- For Registry ID, enter
my-registry
. - Select the region closest to you. For the purposes of this tutorial we'll use
us-central1
. - Ensure that the MQTT protocol is enabled for this registry.
- Under Pub/Sub topics, create a new Pub/Sub topic for Default telemetry topic.
- Click the Select a Pub/Sub topic dropdown.
- Click the Create a topic option.
- Enter a Pub/Sub topic name, such as
gateway-telemetry
.
Do the same for Device state topic, under a different Pub/Sub topic named
gateway-state
.Leave everything else as-is, and click Create.
Set up your gateway
For the purposes of this tutorial, you can use your laptop or desktop as the gateway device, for a simpler setup process. Alternatively, you can use a more realistic device like an additional Raspberry Pi*.
You first generate an RSA public/private key pair, which is used to sign the JWTs for authenticating to IoT Core.
To set up your gateway:
Clone the following repository and change into the directory for this tutorial's code:
git clone https://github.com/GoogleCloudPlatform/community.git cd community/tutorials/cloud-iot-gateways-rpi
Generate an RS256 public/private key pair by running the following:
./generate_keys.sh
In the IoT Core console, click the registry you created.
Under the Gateways tab, click Create Gateway.
For Gateway ID, enter
my-gateway
.Copy the contents of
rsa_public.pem
into the public key text area.For Device authentication method, select Association only. For more details about why this option is used, see Extra notes below.
Click Create.
Export your Google Cloud project ID as an environment variable by running the following:
export GOOGLE_CLOUD_PROJECT=your-project-id-123
Modify the
run-gateway
script by providing arguments forregistry_id
anddevice_id
if you chose different names for those.Download Google's CA root certificate into the same directory if it doesn't exist already:
wget https://pki.goog/roots.pem
Use a virtual environment to keep installations local to a workspace rather than installing libraries onto your system directly:
python3 -m venv env source env/bin/activate
Install the following packages by running the following command:
pip install -r requirements-gateway.txt
Run the following command to start the gateway:
source run-gateway
Keep this process running while you proceed through the next steps. We recommend that you use a new tab or window for each gateway and device.
Find the local IP address of the gateway using
ifconfig
on macOS or Linux oripconfig /all
on Windows. Copy this somewhere as you will need to add this IP address toled-light.py
andthermostat.py
later for connecting devices to the gateway. Your gateway and devices need to be on the same network and be visible to each other.
Raspberry Pi setup
In this tutorial, you use a Raspberry Pi* to manage the LED/temperature sensor. Devices connect to the gateway device through UDP sockets over a local network, which connect to IoT Core through the MQTT bridge. The Raspberry Pi is not really a constrained device, since it has IP connectivity and the ability to sign JWTs, so its use here is mostly for demonstration purposes.
- Download Raspberry Pi software (the full image with Desktop and recommended software) and follow the installation guide to flash Raspberry Pi OS onto your microSD card.
- Insert the microSD card with Raspberry Pi OS into your Raspberry Pi.
- Attach a power source to the Raspberry Pi using the microUSB cable (for example, to a laptop USB port).
- Connect your keyboard and mouse to the Raspberry Pi USB ports.
- Connect the Raspberry Pi to a monitor through the HDMI port.
- Go through the default setup steps for Raspberry Pi OS upon boot.
Open a terminal and make sure that
git
,python3
, and other required dependencies are installed. If not, install them by running the following:sudo apt update && sudo apt upgrade sudo apt install git sudo apt install python3 sudo apt install build-essential libssl-dev libffi-dev python3-dev
Clone the following repository and change into the directory for this tutorial's code:
git clone https://github.com/GoogleCloudPlatform/community.git cd community/tutorials/cloud-iot-gateways-rpi
Create and activate your virtual environment. Make sure to run the last step whenever you open a new tab to activate the virtual environment.
python3 -m virtualenv venv source env/bin/activate
Install Python dependencies by running the following:
pip install -r requirements-pi.txt
Managing devices through configuration updates
Next, you manage an LED light connected to the gateway through IoT Core configuration updates.
- Switch to your browser and open the IoT Core console.
- Click the registry that you created. The gateway that you created should be listed in this registry.
- Click Create Device.
- For Device ID, enter
led-light
. - Leave everything else blank or as-is. You don't need to enter a public key since the device will be authenticated through the gateway.
Bind the device to the gateway:
- Click the browser's button to return to your registry page.
- Click
my-gateway
from the Gateways tab inmy-registry
. - Click the Bound devices tab.
- Click Bind device and then select the box next to
led-light
. - Confirm by clicking Bind in the lower right.
Edit
led-light.py
by adding the IP address of your gateway on line 28:ADDR = ''
.Connect the LED to the Raspberry Pi GPIO Pin 14 and ground using an appropriate resistor.
Ensure that the gateway Python sample is still running on your desktop or laptop.
Run the following from your terminal on the Raspberry Pi:
source run-led-light
Make sure that you see the
>>LED IS OFF<<
messageSwitch back to a browser and go to the IoT Core console.
Select your registry, and then select
led-light
.Click Update Config at the top of the page.
In the configuration text area, enter
ON
orOFF
to toggle the LED state.These are preconfigured valid states that the LED will respond to, defined in
led-light.py
. Sending configuration updates from the IoT Core console toggles the LED device through the gateway device.
Publishing telemetry events through the gateway
In this section, you set up a DHT22 sensor to send telemetry from the sensor through the gateway to IoT Core.
- Repeat steps 1-6 from the previous section, "Managing devices through configuration updates", but use
thermostat
as the Device ID. - Edit
thermostat.py
by adding the IP address of your gateway on line 27:ADDR = ''
Wire the DHT22 sensor to the Raspberry Pi as described in the setup section of this tutorial.
Run the following from a terminal on the Raspberry Pi:
source run-thermostat
If everything is done correctly, you should see the temperature on that terminal updating once per second.
Create a subscription to your telemetry topic to view data
- Open the Pub/Sub dashboard.
- Click the three-dot menu button next to the telemetry topic that you created earlier, and click New subscription.
- Enter a subscription name, such as
my-subscription
. - Make sure that Delivery Type is set to Pull, and leave everything else as-is.
- Click the Create button to create the subscription.
Click the Activate Cloud Shell icon in the upper right area of the Cloud Console window.
In Cloud Shell, enter the following:
gcloud pubsub subscriptions pull my-subscription --auto-ack --limit=100
The topic should have received a lot of messages from both the LED and DHT22. In practice, services that ingest data from Pub/Sub should process that data in regular intervals as telemetry events are published.
Cleanup
To avoid incurring any future billing costs, it is recommended that you delete your project once you have completed the tutorial.
Extra notes
- The reason why Association Only was chosen when creating the gateway is so that the device does not have to store its own JWT when authenticating to IoT Core. You can read more about authentication methods here.
- You can set up a second Raspberry Pi or another internet enabled device to act as the gateway for a more realistic example.
- A slightly less expensive alternative to the DHT22 is the DHT11.
If you encounter issues while installing the packages from
requirements-pi.txt
, make sure you are on the latest version of Raspberry Pi OS. In addition, updating some packages could solve the issue.sudo apt-get install build-essential libssl-dev libffi-dev python-dev
Next steps
*Raspberry Pi is a trademark of the Raspberry Pi Foundation.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see our Site Policies. Java is a registered trademark of Oracle and/or its affiliates.