# PyPortal IoT Plant Monitor with Google Cloud IoT Core and CircuitPython

## Overview

Warning: 

![](https://cdn-learn.adafruit.com/assets/assets/000/080/128/medium800/sensors_IMG_7822.jpg?1566952255)

 **Turn your black thumb into a green thumb** by building an**&nbsp;internet-enabled plant monitoring system by combining [Google Cloud IoT Core](https://cloud.google.com/iot/) with CircuitPython.**

This smart-planter&nbsp; **monitors your plant's vitals** on the PyPortal's screen, **logs this data to a Google Cloud** registry for long-term storage and even **&nbsp;correctly waters your plants remotely** by controlling a peristaltic water pump.

**Using Google Cloud IoT with your CircuitPython IoT projects&nbsp;allows you to quickly prototype** &nbsp;(and even _mass_-prototype)&nbsp; **advanced internet-of-things devices** &nbsp;and connect them to the Google Cloud Platform.&nbsp;

## Google Cloud IoT

[Google Cloud IoT](https://cloud.google.com/solutions/iot/) provides a complete solution for collecting, processing, analyzing, and visualizing data from IoT devices in real time:

- **Device management** , with per-device authentication and management.
- **Data aggregation&nbsp;** with Cloud IoT Pub/Sub&nbsp;
- **Scalable** - Google Cloud IoT is serverless and scales instantly.

Connecting CircuitPython to Google Cloud IoT [unlocks over 100 products and services available from Google Cloud Services](https://cloud.google.com/products/). Some of these services are&nbsp;_especially_ useful with IoT projects, such as:

- **Analyze your data** &nbsp;with [Dataflow](https://cloud.google.com/dataflow/), [BigQuery](https://cloud.google.com/bigquery/), or&nbsp;[BigTable](https://cloud.google.com/bigtable/)
- **Machine Learning** with [Cloud AutoML](https://cloud.google.com/automl/)

![sensors_GCP.jpg](https://cdn-learn.adafruit.com/assets/assets/000/079/927/medium640/sensors_GCP.jpg?1566827497)

## CircuitPython

**CircuitPython is perfect for building Internet-of-Things projects**. This project uses the [ESP32SPI CircuitPython](https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI) library, which can use the ESP32 as a WiFi-coprocessor.

We've built a **[CircuitPython Google Cloud IoT Core](https://github.com/adafruit/Adafruit_CircuitPython_GC_IOT_Core)** helper module to make interacting with Google's Cloud IoT MQTT Broker _incredibly_ simple. Provisioning CircuitPython for Google Cloud IoT Core is as simple as adding your device's settings to a file. Our library even handles JSON Web Token ([JWT](https://jwt.io)) generation.

**You can rapidly update your code without having to compile** and store WiFi, device configuration, and secret keys on the device. This means that there's no editing code and re-uploading whenever you move the PyPortal to another network - just update a file and you're set.&nbsp;

![sensors_blinka.png](https://cdn-learn.adafruit.com/assets/assets/000/080/073/medium640/sensors_blinka.png?1566936617)

## Prerequisite Guides

If you're new to CircuitPython, take a moment to walk through the following guides to get you started and up-to-speed:

- [Welcome to CircuitPython](https://learn.adafruit.com/welcome-to-circuitpython)
- [PyPortal Introduction Guide](https://learn.adafruit.com/adafruit-pyportal)
- [MQTT in CircuitPython](https://learn.adafruit.com/mqtt-in-circuitpython)

## Parts
### Adafruit PyPortal - CircuitPython Powered Internet Display

[Adafruit PyPortal - CircuitPython Powered Internet Display](https://www.adafruit.com/product/4116)
 **PyPortal** , our easy-to-use IoT device that allows you to create all the things for the “Internet of Things” in minutes. Make custom touch screen interface GUIs, all open-source, and Python-powered using&nbsp;tinyJSON / APIs to get news, stock, weather, cat photos,...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4116)
[Related Guides to the Product](https://learn.adafruit.com/products/4116/guides)
![Front view of a Adafruit PyPortal - CircuitPython Powered Internet Display with a pyportal logo image on the display. ](https://cdn-shop.adafruit.com/640x480/4116-00.jpeg)

### Adafruit STEMMA Soil Sensor - I2C Capacitive Moisture Sensor

[Adafruit STEMMA Soil Sensor - I2C Capacitive Moisture Sensor](https://www.adafruit.com/product/4026)
Most low cost soil sensors are _resistive_ style, where there's two prongs and the sensor measures the conductivity between the two. These work OK at first, but eventually start to oxidize because of the exposed metal. Even if they're gold plated! The resistivity measurement...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4026)
[Related Guides to the Product](https://learn.adafruit.com/products/4026/guides)
![Demo Shot of the Adafruit STEMMA Soil Sensor - I2C Capacitive Moisture Sensor in a small potted plant, with wires connecting it to an Adafruit Metro.](https://cdn-shop.adafruit.com/640x480/4026-01.jpg)

### Peristaltic Liquid Pump with Silicone Tubing - 12V DC Power

[Peristaltic Liquid Pump with Silicone Tubing - 12V DC Power](https://www.adafruit.com/product/1150)
Move fluid safely from here to there with this very nice little pump. Unlike most liquid pumps, [this is a peristaltic type - the pump squishes the silicone tubing that contains the liquid instead of impelling it directly](http://en.wikipedia.org/wiki/Peristaltic_pump). The upshot?...

In Stock
[Buy Now](https://www.adafruit.com/product/1150)
[Related Guides to the Product](https://learn.adafruit.com/products/1150/guides)
![Peristaltic Liquid Pump with Silicone Tubing ](https://cdn-shop.adafruit.com/640x480/1150-07.jpg)

## Materials

You'll need some extra parts and supplies to finish this project. If you do not have them already, pick some up from Adafruit.

### Part: PN2222 Transistor
quantity: 1
NPN Bipolar Transistors (PN2222) - 10 pack
[PN2222 Transistor](https://www.adafruit.com/product/756)

### Part: 1N4148 Diode
quantity: 1
1N4148 Signal Diode - 10 pack
[1N4148 Diode](https://www.adafruit.com/product/1641)

### Part: 220 ohm resistor
quantity: 1
Through-Hole Resistors - 220 ohm 5% 1/4W - Pack of 25
[220 ohm resistor](https://www.adafruit.com/product/2780)

### Part: Breadboard
quantity: 1
Half-size breadboard
[Breadboard](https://www.adafruit.com/product/64)

### Part: Breadboarding Wire
quantity: 1
Breadboarding wire bundle
[Breadboarding Wire](https://www.adafruit.com/product/153)

### Part: Female DC Power adapter
quantity: 1
Female DC Power adapter - 2.1mm jack to screw terminal block
[Female DC Power adapter](https://www.adafruit.com/product/368)

### Part: 12VDC 1000mA Switching Power Adapter
quantity: 1
12V DC 1000mA (1A) regulated switching power adapter
[12VDC 1000mA Switching Power Adapter](https://www.adafruit.com/product/798)

### Part: PyPortal Stand
quantity: 1
Adafruit PyPortal Desktop Stand Enclosure Kit
[PyPortal Stand](https://www.adafruit.com/product/4146)

### Part: USB Cable
quantity: 1
Pink and Purple Braided USB A to Micro B Cable - 2 meter long
[USB Cable](https://www.adafruit.com/product/4148)

# PyPortal IoT Plant Monitor with Google Cloud IoT Core and CircuitPython

## PyPortal Wiring

Warning: 

## Connecting the STEMMA Soil Sensor
We recommend using a Female-to-Female STEMMA Connector and plugging it in between the PyPortal and the STEMMA Soil Sensor. No soldering is involved - just connect the cable between the Stemma Soil Sensor and the PyPortal I2C port.

### Part: STEMMA Cable
quantity: 1
STEMMA Cable - 150mm/6" Long 4 Pin JST-PH Cable–Female/Female
[STEMMA Cable](https://www.adafruit.com/product/3568)

The cable makes the following connections between the PyPortal's I2C port and the STEMMA Soil Sensor:

- **PyPortal 3.3V&nbsp;** to&nbsp; **Sensor VIN**
- **PyPortal GND** &nbsp;to&nbsp; **Sensor GND**
- **PyPortal SCL&nbsp;** to&nbsp; **Sensor SCL**
- **PyPortal SDA** &nbsp;to&nbsp; **Sensor SDA**

![sensors_wireless_output-onlinepngtools_(1).png](https://cdn-learn.adafruit.com/assets/assets/000/080/044/medium640/sensors_wireless_output-onlinepngtools_%281%29.png?1566930694)

## Connecting the&nbsp;Peristaltic Liquid Pump
Add a ground and power wire to the end of the DC motor using&nbsp;[alligator clips](https://www.adafruit.com/product/4304) or by soldering wires directly to the terminals.

![sensors_1150-05.jpg](https://cdn-learn.adafruit.com/assets/assets/000/080/060/medium640/sensors_1150-05.jpg?1566932461)

![](https://cdn-learn.adafruit.com/assets/assets/000/080/159/medium800/sensors_Pasted_Image_8_28_19__10_31_AM.png?1567002816)

 **Make the following connections:**

1. Connect the&nbsp;JST PH 3-Pin to Male Header Cable to the D3 STEMMA connector on the PyPortal.
2. Connect the&nbsp;header cable's power (red) and ground (black) to the breadboard's red and blue power rails.
3. Ensuring the flat side of the transistor is facing towards the PyPortal; Connect the emitter to the GND rail.&nbsp;
4. Connect the transistor's **base** to one lead of the 220ohm resistor. Connect the other lead of the resistor to the **white** &nbsp;(yellow in this wiring diagram) male header cable.
5. Connect the female DC power adapter to the power and ground rails on the **opposite side of the breadboard**.
6. Connect the left and right&nbsp; **ground** rails together.
7. Connect the DC motor's **power** (green in this diagram) to the red power rail.&nbsp;
8. Connect one lead of a&nbsp;1N4148 diode to the transistor's collector lead.
9. Connect one end of the motor to the **striped diode lead**. Connect the motor's other terminal to the&nbsp; un-striped diode lead.
10. **Re-read the notes above the diagram to ensure you did not make any errors while connecting components.&nbsp;** It does&nbsp; **not** &nbsp;matter which way you connect the motor's leads for now.

When you're ready, stick the STEMMA Soil sensor into your plant's soil. Be sure to leave the&nbsp; **white** &nbsp;portion of the sensor not covered by soil. You may also want to position the sensor at the edge of your planter.

![](https://cdn-learn.adafruit.com/assets/assets/000/080/067/medium800/sensors_IMG_6219.jpg?1566934710)

Affix one end of the silicone tubing from the end of the pump to the planter (tape, putty or glue work great), positioning it away from the soil sensor.

![](https://cdn-learn.adafruit.com/assets/assets/000/080/068/medium800/sensors_IMG_7782_MOV.png?1566934790)

Insert the other end of the silicone tubing into a water bottle. The pump will be fed from the water bottle. Select the largest/widest bottle you have.

# PyPortal IoT Plant Monitor with Google Cloud IoT Core and CircuitPython

## Google Cloud Setup

Warning: 

You'll need an account to access the Google Cloud platform. **Head over to [https://cloud.google.com](https://cloud.google.com/)&nbsp;and make a new account**.

Warning: 

## Google Cloud IoT API Setup
Once logged in, **navigate to&nbsp;[https://console.cloud.google.com/iot](https://console.cloud.google.com/iot)**.

**Click Enable&nbsp;** to enable the Cloud IoT API. It may take some time for the API to set up.

![](https://cdn-learn.adafruit.com/assets/assets/000/079/814/medium800/sensors_enable_api.png?1566576378)

The Google Cloud IoT API links with your existing Google Cloud Services projects.

If you already have a project, **select your project using the Select a project dropdown.**

If you do not have a project, or would like to create a new one for this guide, select&nbsp; **Create a project&nbsp;** from the Select a project dropdown. **Fill out the project name.**

**Click Create**

![](https://cdn-learn.adafruit.com/assets/assets/000/079/815/medium800/sensors_create_project.png?1566576439)

## Setup Project Registry
The header of your Google Cloud dashboard will display the project you created.

**Click the navigation menu.&nbsp;** From the navigation menu,&nbsp; **click IoT Core**.

![sensors_click.png](https://cdn-learn.adafruit.com/assets/assets/000/079/817/medium640/sensors_click.png?1566576713)

![sensors_click2.png](https://cdn-learn.adafruit.com/assets/assets/000/079/819/medium640/sensors_click2.png?1566576726)

You'll need to create a registry for your devices. A registry is&nbsp;a "container of devices...created in a specific cloud region, and belongs to a cloud project".&nbsp;

**Click Create Registry**

![](https://cdn-learn.adafruit.com/assets/assets/000/079/823/medium800/sensors_create_Reg_1.png?1566576963)

 **Set the Registry ID** to the name of your container. The Registry ID _must_&nbsp; start with a lower case letter.

**Select the Region** closest to where your devices will be physically located.

You'll be connecting using the MQTT protocol to Cloud IoT Core. **Under Protocol, select MQTT**.

![sensors_reg_2.png](https://cdn-learn.adafruit.com/assets/assets/000/079/824/medium640/sensors_reg_2.png?1566577054)

Underneath the Default telemetry topic dropdown,&nbsp; **Create a new Default telemetry topic**.

**Name the topic _events._**

_Then,&nbsp;_ **Create a new Device State topic. Name&nbsp;the topic _state_.**

![sensors_create_tel_topic.png](https://cdn-learn.adafruit.com/assets/assets/000/079/828/medium640/sensors_create_tel_topic.png?1566577341)

![sensors_create_tel_topic_2.png](https://cdn-learn.adafruit.com/assets/assets/000/079/829/medium640/sensors_create_tel_topic_2.png?1566577350)

Stackdriver Logging allows you to monitor and visualize network traffic as it comes into your Google IoT Core registry, in real-time.&nbsp;

**Set the Stackdriver Logging level for this registry to Debug**. This will enable Stackdriver logging for each device created in the registry.

**Click Create**

![](https://cdn-learn.adafruit.com/assets/assets/000/079/830/medium800/sensors_reg_3.png?1566577359)

Now that you created your registry, it's time to add a device to it!&nbsp;

From the&nbsp;_Registry details_&nbsp;page,&nbsp; **click Devices**.

From the device page, click&nbsp; **Create A Device**

![sensors_devices.png](https://cdn-learn.adafruit.com/assets/assets/000/079/832/medium640/sensors_devices.png?1566579729)

![sensors_device_2.png](https://cdn-learn.adafruit.com/assets/assets/000/079/833/medium640/sensors_device_2.png?1566579750)

 **Create a Device ID**. This value is permanently tied to the device, make sure you like it before clicking Create.

Ensure that the public key format selected is&nbsp;_RS256_&nbsp;since CircuitPython authenticates with the server using a RS256 private key.

**Do not fill out the Public key value** , you'll create one later in this guide.

**Click Create**

![sensors_create_device_3.png](https://cdn-learn.adafruit.com/assets/assets/000/079/834/medium640/sensors_create_device_3.png?1566580132)

Ensure your Device Details page displays a green checkmark underneath Device communication.

- _If you see a red X_, **click Edit Device** and **select allow device communication**.

![](https://cdn-learn.adafruit.com/assets/assets/000/079/836/medium800/sensors_device_page.png?1566580166)

Congrats - you've successfully set up Google Cloud IoT Core with a new device!

# PyPortal IoT Plant Monitor with Google Cloud IoT Core and CircuitPython

## PyPortal CircuitPython Setup

To use all the amazing features of your PyPortal with CircuitPython, you must first install a number of libraries. This page covers that process.

# Adafruit CircuitPython Bundle

Download the Adafruit CircuitPython Library Bundle. You can find the latest release here:

[Latest Adafruit CircuitPython Library Bundle](https://circuitpython.org/libraries)
Download the **adafruit-circuitpython-bundle-\*.x-mpy-\*.zip** bundle zip file where **\*.x MATCHES THE VERSION OF CIRCUITPYTHON YOU INSTALLED** , and unzip a folder of the same name. Inside you'll find a **lib** folder. You have two options:

- You can add the **lib** folder to your **CIRCUITPY** drive. This will ensure you have _all the drivers_. But it will take a bunch of space on the 8 MB disk  
- Add each library as you need it, this will reduce the space usage but you'll need to put in a little more effort.

At a minimum we recommend the following libraries, in fact we more than recommend. They're basically required. So grab them and install them into **CIRCUITPY/lib** now!

- **adafruit\_esp32spi** - This is the library that gives you internet access via the ESP32 using (you guessed it!) SPI transport. You need this for anything Internet
- **adafruit\_requests** - This library allows us to perform HTTP requests and get responses back from servers. GET/POST/PUT/PATCH - they're all in here!
- adafruit\_connection\_manager - used by adafruit\_requests.
- **adafruit\_pyportal** - This is our friendly wrapper library that does a lot of our projects, displays graphics and text, fetches data from the internet. Nearly all of our projects depend on it!
- **adafruit\_portalbase** &nbsp;- This library is the base library that adafruit\_pyportal library is built on top of.
- **adafruit\_touchscreen** - a library for reading touches from the resistive touchscreen. Handles all the analog noodling, rotation and calibration for you.
- **adafruit\_io** - this library helps connect the PyPortal to our free datalogging and viewing service
- **adafruit\_imageload** - an image display helper, required for any graphics!
- **adafruit\_display\_text** - not surprisingly, it displays text on the screen
- **adafruit\_bitmap\_font** - we have fancy font support, and its easy to make new fonts. This library reads and parses font files.
- **adafruit\_slideshow** - for making image slideshows - handy for quick display of graphics and sound
- **neopixel** - for controlling the onboard neopixel
- **adafruit\_adt7410** - library to read the temperature from the on-board Analog Devices ADT7410 precision temperature sensor (not necessary for Titano or Pynt)
- **adafruit\_bus\_device** - low level support for I2C/SPI
- **adafruit\_fakerequests** &nbsp;- This library allows you to create fake HTTP requests by using local files.

# PyPortal IoT Plant Monitor with Google Cloud IoT Core and CircuitPython

## Create Your settings.toml File

CircuitPython works with WiFi-capable boards to enable you to make projects that have network connectivity. This means working with various passwords and API keys. As of [CircuitPython 8](https://circuitpython.org/downloads), there is support for a **settings.toml** file. This is a file that is stored on your **CIRCUITPY** drive, that contains all of your secret network information, such as your SSID, SSID password and any API keys for IoT services. It is designed to separate your sensitive information from your **code.py** file so you are able to share your code without sharing your credentials.

CircuitPython previously used a **secrets.py** file for this purpose. The **settings.toml** file is quite similar.

Warning: Your **settings.toml** file should be stored in the main directory of your **CIRCUITPY** drive. It should not be in a folder.

## CircuitPython **settings.toml** File

This section will provide a couple of examples of what your **settings.toml** file should look like, specifically for CircuitPython WiFi projects in general.

The most minimal **settings.toml** file must contain your WiFi SSID and password, as that is the minimum required to connect to WiFi. Copy this example, paste it into your **settings.toml** , and update:

- `your_wifi_ssid`
- `your_wifi_password`

```auto
CIRCUITPY_WIFI_SSID = "your_wifi_ssid"
CIRCUITPY_WIFI_PASSWORD = "your_wifi_password"
```

Many CircuitPython network-connected projects on the Adafruit Learn System involve using Adafruit IO. For these projects, you must _also_ include your Adafruit IO username and key. Copy the following example, paste it into your settings.toml file, and update:

- `your_wifi_ssid`
- `your_wifi_password`
- `your_aio_username`
- `your_aio_key`

```auto
CIRCUITPY_WIFI_SSID = "your_wifi_ssid"
CIRCUITPY_WIFI_PASSWORD = "your_wifi_password"
ADAFRUIT_AIO_USERNAME = "your_aio_username"
ADAFRUIT_AIO_KEY = "your_aio_key"
```

Some projects use different variable names for the entries in the **settings.toml** file. For example, a project might use `ADAFRUIT_AIO_ID` in the place of `ADAFRUIT_AIO_USERNAME`. **If you run into connectivity issues, one of the first things to check is that the names in the settings.toml file match the names in the code.**

Warning: Not every project uses the same variable name for each entry in the **settings.toml** file! Always verify it matches the code.

## **settings.toml** File Tips
Here is an example **settings.toml** file.

```auto
# Comments are supported
CIRCUITPY_WIFI_SSID = "guest wifi"
CIRCUITPY_WIFI_PASSWORD = "guessable"
CIRCUITPY_WEB_API_PORT = 80
CIRCUITPY_WEB_API_PASSWORD = "passw0rd"
test_variable = "this is a test"
thumbs_up = "\U0001f44d"
```

In a **settings.toml** file, it's important to keep these factors in mind:

- Strings are wrapped in double quotes; ex: `"your-string-here"`
- Integers are _ **not** _ quoted and may be written in decimal with optional sign (`+1`, `-1`, `1000`) or hexadecimal (`0xabcd`).
  - Floats (decimal numbers), octal (`0o567`) and binary (`0b11011`) are not supported.

- Use `\u` escapes for weird characters, `\x` and `\ooo` escapes are not available in **.toml** files
  - Example: `\U0001f44d` for 👍 (thumbs up emoji) and `\u20ac` for € (EUR sign)

- Unicode emoji, and non-ASCII characters, stand for themselves as long as you're careful to save in "UTF-8 without BOM" format

&nbsp;

&nbsp;

When your&nbsp; **settings.toml&nbsp;** file is ready, you can save it in your text editor with the **.toml** &nbsp;extension.

![adafruit_products_dotToml.jpg](https://cdn-learn.adafruit.com/assets/assets/000/117/071/medium640/adafruit_products_dotToml.jpg?1671034293)

## Accessing Your **settings.toml** Information in **code.py**
In your **code.py** file, you'll need to `import` the `os` library to access the **settings.toml** file. Your settings are accessed with the `os.getenv()` function. You'll pass your settings entry to the function to import it into the **code.py** file.

```python
import os

print(os.getenv("test_variable"))
```

![](https://cdn-learn.adafruit.com/assets/assets/000/117/072/medium800/adafruit_products_tomlOutput.jpg?1671034496)

In the upcoming CircuitPython WiFi examples, you'll see how the **settings.toml&nbsp;** file is used for connecting to your SSID and accessing your API keys.

# PyPortal IoT Plant Monitor with Google Cloud IoT Core and CircuitPython

## Internet Connect!

# Connect to WiFi

OK, now that you have your&nbsp; **settings.toml** file set up - you can connect to the Internet.

To do this, you need to first install a few libraries, into the lib folder on your **CIRCUITPY** drive. Then you need to update **code.py** with the example script.

Thankfully, we can do this in one go. In the example below, click the **Download Project Bundle** button below to download the necessary libraries and the **code.py** file in a zip file. Extract the contents of the zip file, open the directory **examples/** and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your **CIRCUITPY** drive.

Your **CIRCUITPY** drive should now look similar to the following image:

![CIRCUITPY](https://adafruit.github.io/Adafruit_CircuitPython_Bundle/esp32spi_esp32spi_simpletest.py.png )

Info: Update to CircuitPython 9.2.x or later to use this example.

https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/blob/main/examples/esp32spi_simpletest.py

And save it to your board, with the name **code.py**.

Don't forget you'll also need to create the **settings.toml** file as seen above, with your WiFi ssid and password.

In a serial console, you should see something like the following. For more information about connecting with a serial console, view the guide [Connecting to the Serial Console](https://learn.adafruit.com/welcome-to-circuitpython/kattni-connecting-to-the-serial-console).

```terminal
&gt;&gt;&gt; import wifitest
ESP32 SPI webclient test
ESP32 found and in idle mode
Firmware vers. 1.7.5
MAC addr: 24:C9:DC:BD:0F:3F
	HomeNetwork             RSSI: -46
	HomeNetwork             RSSI: -76
	Fios-12345              RSSI: -92
	FiOS-AB123              RSSI: -92
	NETGEAR53               RSSI: -93
Connecting to AP...
Connected to HomeNetwork 	RSSI: -45
My IP address is 192.168.1.245
IP lookup adafruit.com: 104.20.39.240
Ping google.com: 30 ms
Fetching text from http://wifitest.adafruit.com/testwifi/index.html
----------------------------------------
This is a test of Adafruit WiFi!
If you can read this, its working :)
----------------------------------------

Fetching json from http://wifitest.adafruit.com/testwifi/sample.json
----------------------------------------
{'fun': True, 'company': 'Adafruit', 'founded': 2005, 'primes': [2, 3, 5], 'pi': 3.14, 'mixed': [False, None, 3, True, 2.7, 'cheese']}
----------------------------------------
Done!
```

Going over the example above, here's a breakdown of what the program is doing:

- Initialize the ESP32 over SPI using the SPI port and 3 control pins:

```python
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

#...

else:
    spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
```

- Get the socket pool and the SSL context, and then tell the `adafruit_requests` library about them.

```python
pool = adafruit_connection_manager.get_radio_socketpool(esp)
ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
requests = adafruit_requests.Session(pool, ssl_context)
```

- Verify an ESP32 is found, checks the firmware and MAC address

```auto
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
    print("ESP32 found and in idle mode")
print("Firmware vers.", esp.firmware_version)
print("MAC addr:", ":".join("%02X" % byte for byte in esp.MAC_address))
```

- Perform a scan of all access points it can see and print out the name and signal strength.

```python
for ap in esp.scan_networks():
    print("\t%-23s RSSI: %d" % (ap.ssid, ap.rssi))
```

- Connect to the AP we've defined here, then print out the local IP address. Then attempt to do a domain name lookup and ping google.com to check network connectivity. (Note sometimes the ping fails or takes a while; this isn't a big deal.)

```python
print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(ssid, password)
    except OSError as e:
        print("could not connect to AP, retrying: ", e)
        continue
print("Connected to", esp.ap_info.ssid, "\tRSSI:", esp.ap_info.rssi)
print("My IP address is", esp.ipv4_address)
print(
    "IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com"))
)
```

Now we're getting to the really interesting part of the example program. We've written a library for web fetching web data, named [adafruit\_requests](https://github.com/adafruit/Adafruit_CircuitPython_Requests). It is a lot like the regular Python library named [requests](https://requests.readthedocs.io/en/latest/). This library allows you to send HTTP and HTTPS requests easily and provides helpful methods for parsing the response from the server.

- Here is the part of the example program is fetching text data from a URL.

```python
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"  # Further up in the program

# ...

print("Fetching text from", TEXT_URL)
r = requests.get(TEXT_URL)
print('-' * 40)
print(r.text)
print('-' * 40)
r.close()
```

- Finally, here the program is fetching some JSON data. The `adafruit_requests` library will parse the JSON into a Python dictionary whose structure is the same as the structure of the JSON.

```auto
JSON_URL = "http://wifitest.adafruit.com/testwifi/sample.json"   # Further up in the program

# ...

print("Fetching json from", JSON_URL)
r = requests.get(JSON_URL)
print('-' * 40)
print(r.json())
print('-' * 40)
r.close()
```

# Advanced Requests Usage

Want to send custom HTTP headers, parse the response as raw bytes, or handle a response's http status code in your CircuitPython code?

We've written an&nbsp;example to show advanced usage of the requests module below.

To use with CircuitPython, you need to first install a few libraries, into the lib folder on your **CIRCUITPY** drive. Then you need to update **code.py** with the example script.

Thankfully, we can do this in one go. In the example below, click the **Download Project Bundle** button below to download the necessary libraries and the **code.py** file in a zip file. Extract the contents of the zip file, open the directory **examples/** and then click on the directory that matches the version of CircuitPython you're using and copy the contents of that directory to your **CIRCUITPY** drive.

https://github.com/adafruit/Adafruit_CircuitPython_Requests/blob/main/examples/esp32spi/requests_esp32spi_advanced.py

Your **CIRCUITPY** drive should now look similar to the following image:

![CIRCUITPY](https://adafruit.github.io/Adafruit_CircuitPython_Bundle/requests_esp32spi_requests_esp32spi_advanced.py.png )

# WiFi Manager

The way the examples above connect to WiFi works but it's a little finicky. Since WiFi is not necessarily so reliable, you may have disconnects and need to reconnect. For more advanced uses, we recommend using the `WiFiManager` class. It will wrap the connection/status/requests loop for you - reconnecting if WiFi drops, resetting the ESP32 if it gets into a bad state, etc.

Here's a more advanced example that shows using the `WiFiManager` and also how to fetch the current time from a web source.

https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/blob/main/examples/esp32spi_localtime.py

# Further Information

For more information on the basics of doing networking in CircuitPython, see this guide:

### Networking in CircuitPython

[Networking in CircuitPython](https://learn.adafruit.com/networking-in-circuitpython)
# PyPortal IoT Plant Monitor with Google Cloud IoT Core and CircuitPython

## Code Setup

Warning: 

## CircuitPython Library Installation

First make sure you are running the&nbsp;[latest version of Adafruit CircuitPython](https://circuitpython.org/board/pyportal/)&nbsp;for your board.

Next you'll need to install the necessary libraries&nbsp;to use the hardware--carefully follow the steps to find and install these libraries from&nbsp;[Adafruit's CircuitPython library bundle](https://circuitpython.org/libraries)&nbsp;matching your version of CircuitPython. PyPortal requires at least CircuitPython version 4.0.0.

Connect your PyPortal to your computer using a known good data+power USB cable. The board should show up in your operating system file explorer/finder as a flash drive names **CIRCUITPY**.

Before continuing make sure your board's **lib** folder on **CIRCUITPY** has the following files and folders **&nbsp;** copied over.

- **adafruit\_binascii.mpy**
- **adafruit\_imageload**
- **adafruit\_bitmap\_font**
- **adafruit\_itertools**
- **adafruit\_rsa**
- **adafruit\_bus\_device**
- **adafruit\_jwt.mpy**
- **adafruit\_seesaw**
- **adafruit\_logging.mpy**
- **neopixel.mpy**
- **adafruit\_esp32spi**
- **adafruit\_minimqtt**
- **adafruit\_gc\_iot\_core.mpy**
- **adafruit\_ntp.mpy**
- **adafruit\_register**

## Add CircuitPython Code and Project Assets

In the embedded code element below, click on the&nbsp; **Download Project Bundle** button, and save the .zip archive file to your computer.

Then, **uncompress the .zip file** , it will unpack to a folder named **PyPortal\_GC\_IOT\_CORE\_PLANT\_MONITOR**.

Copy the contents of the **PyPortal\_GC\_IOT\_CORE\_PLANT\_MONITOR** directory to your PyPortal **CIRCUITPY** drive.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/PyPortal/PyPortal_GCP_IOT_Planter/code.py

This is what the final contents of the&nbsp; **CIRCUITPY** &nbsp;drive will look like:

![CIRCUITPY](https://adafruit.github.io/Adafruit_Learning_System_Guides/PyPortal_PyPortal_GCP_IOT_Planter.png )

## Install Mu Editor&nbsp;

This guide requires you to edit and interact with CircuitPython code. While you can use any text editor of your choosing,&nbsp;&nbsp; **Mu** is a simple code editor that works with the Adafruit CircuitPython boards. It's written in Python and works on Windows, MacOS, Linux and Raspberry Pi. The serial console is built right in, so you get immediate feedback from your board's serial output!

Before proceeding, **click the button below to install the Mu Editor**. There are versions for PC, mac, and Linux.

[Install Mu Editor](https://learn.adafruit.com/welcome-to-circuitpython/installing-mu-editor)
## Settings File Setup

Open the **settings.toml** file on your **CIRCUITPY** drive using Mu. You're going to edit&nbsp;the file to enter your local WiFi credentials along with data about your Google Cloud Services Project and IoT Core configuration.

Make the following changes to the code below in the **settings.toml** file:

- **Replace&nbsp;`MY_WIFI_SSID `** with the **name of your WiFi SSID**
- **Replace `MY_WIFI_PASSWORD `** with your **WiFi's password**
- **Replace `MY_GCS_PROJECT_ID`** &nbsp;with **the name of your Google Cloud Services project.**
- **Replace `MY_GCS_PROJECT_REGION` with the project's region**.
- **Replace&nbsp;`MY_IOT_REGISTRY`** &nbsp;with **the name of your Cloud IoT registry.**
- **Replace `MY_IOT_DEVICE` with the name of the device you created in your Cloud IoT registry.**

```auto
# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it

CIRCUITPY_WIFI_SSID="MY_WIFI_SSID"
CIRCUITPY_WIFI_PASSWORD="MY_WIFI_PASSWORD"
project_id="MY_GCS_PROJECT_ID"
cloud_region="MY_GCS_PROJECT_REGION"
registry_id="MY_IOT_REGISTRY"
device_id="MY_IOT_DEVICE"
```

## Authenticating with Google Cloud IoT Core - the JWT
CircuitPython authenticates with Google's MQTT API using a special security key called a [JSON Web Token (JWT)](https://cloud.google.com/iot/docs/how-tos/credentials/jwts).&nbsp;

A JSON Web Token is a [JSON](https://www.json.org/) dictionary containing statements (_claims_) about the device. In our case, it looks like the following:

```auto
token = {
  # The time that the token was issued at
  'iat': issue_time,
  # The time the token expires.
  'exp': expiration_time,
  # Your Project Identifier
  'aud': project_id
}
```

We are not going to create this JWT manually, the Google Core IoT CircuitPython module handles this automatically for you using the [CircuitPython JWT module](https://github.com/adafruit/Adafruit_CircuitPython_JWT).

- For more information about JWTs,&nbsp;[check out JWT.io's excellent introduction page](https://jwt.io/introduction/).

## Creating a RSA Key Pair
The final step in generating a JWT involves signing the JWT with a private key. This ensures that the key will only be used to communicate with a public key.

Your CircuitPython device will hold the device's&nbsp;_private_ RSA, while Google Cloud IoT holds the device's _public_ RSA key

While the [CircuitPython RSA module](https://github.com/adafruit/Adafruit_CircuitPython_RSA) can generate RSA keys, it cannot save the key pairs to the device's filesystem.&nbsp;

We'll be generating a RSA key pair on our computer using a Python script.

**Click _decode\_key\_priv.py_** &nbsp; **to download the code** below and **save the code to your desktop**.

https://github.com/adafruit/Adafruit_CircuitPython_RSA/blob/main/util/decode_priv_key.py

You'll need a local installation of Python ([click here to download and install the Python distribution for your operating system](https://www.python.org/downloads/)) to run this script.

You'll also need to **install the** [**python-rsa library**](https://github.com/sybrenstuvel/python-rsa), you can do this by typing the following into your terminal:

```
pip install rsa
```
Once installed, run the code&nbsp;from your desktop:

`python3 decode_key_priv.py`

![](https://cdn-learn.adafruit.com/assets/assets/000/079/841/medium800/sensors_decode_scriot.png?1566582359)

If the script runs successfully, it'll create two files on your desktop - **rsa\_public.pem** and **rsa\_private.pem**. These are your public and private RSA keys. You'll use them in the next step.

It'll also output the decoded private key to your terminal. The private key should have _five_ integer values.

Modify your **rsa\_private\_key.py** file by copying and pasting the output from the code into the file:

```auto
# Replace the value with your generated RSA Private Key
private_key = (24438159363269526254144311871580579031858357859966324445350326786364998912771634237547789185814277400858631944952065597018819979449812397621834604674421573629778503529017607686952918724898685881544477812184759676064843937596886704154729857293596401786101074754877589082423154083489847915661860834755738610786688547912322386416918350317006245900073735354143276892049027125601443947584374912401061688828446039255462953272156360234392950941978497936249124410101311599817221805182114152095007037371899964182199631346414794479580997760720063537930724219713985584071493296120508892403130706628712278713361122757185268631117,
               65531,
               16011940782440353652943478520006562150052609770159665100376017092734074695430275633005814541997117225275335393994868497733923278721561016736829240348500272695770159475350047668916159269529419591276986698433153493297288534421934404632560234252209126031023393655102364697792853446832385820201112413513111592950042350642403708159079499430564775961436272409066068179381765892260252909360654617051331730162665742415598304194771289070036798676791361721996492207147874480559927670849388398727297101629122127273532260070125100209595266819508897273144318330256879686971164694481555143431693246541875462896679755259675697969793,
               171180510224532714639208966958930887752631657983050450948053675977812070176625671098825502436380896087798236950227432035881066562828394842137169407540235290205801047834085254364601442602722583477726608017578416412915568120972286874859375397533049118528847434756643019078803240871975917780146737832789354797749,
               142762310320270325250889040291289810070312245928207105466534900926375358526304862222284449091864287073322237001651192479298990227289938371837057243365681576671132453564694769006817561479289703593958730636340134647097544182128899145836621518733215831051979336393263185036416885910092387701460789142994244341633)
```

## Adding your RSA Public Key to Google Cloud IoT Core

After the _private_ _key_ is set up on your CircuitPython device,&nbsp;you'll also need to add the _public key_ to the IoT Core Device.&nbsp;

To view the public key data, enter the following into your terminal:

`less rsa_public.pem`

It should print the RSA Public Key data to your terminal.

**Copy the output** starting with_&nbsp;-----BEGIN PUBLIC KEY-----&nbsp;_ **to your clipboard**.

![sensors_less.png](https://cdn-learn.adafruit.com/assets/assets/000/079/843/medium640/sensors_less.png?1566582764)

 **Navigate to the IoT Core Device details page**. Under&nbsp;_Authentication_,&nbsp; **click Add public key**.

Specify the public key format to be **RS256** and **paste the public key data into the Public key value text box**.

**Click Add Public Key&nbsp;** to add the authentication key to your device.

![sensors_Device_details_-_circuitpython_-_Google_Cloud_Platform.png](https://cdn-learn.adafruit.com/assets/assets/000/079/842/medium640/sensors_Device_details_-_circuitpython_-_Google_Cloud_Platform.png?1566582910)

![sensors_add_auth_key.png](https://cdn-learn.adafruit.com/assets/assets/000/079/845/medium640/sensors_add_auth_key.png?1566582979)

With the private key stored on your CircuitPython device and the public key stored in Google IoT Core, you're ready to run your code!

# PyPortal IoT Plant Monitor with Google Cloud IoT Core and CircuitPython

## Code Usage

Warning: 

## Connecting to Google Cloud IoT Core
When the PyPortal starts up, it will first load the&nbsp; **gcp\_splash.bmp** &nbsp;image in the&nbsp; **images** &nbsp;folder on your&nbsp; **CIRCUITPY** &nbsp;drive. This is a "loading screen" while the code waits for the fonts and display objects load on the screen.

![sensors_gcp_splash.bmp](https://cdn-learn.adafruit.com/assets/assets/000/080/086/medium640/sensors_gcp_splash.bmp?1566944299)

Opening the REPL will help you view what's happening in the code. First, the code attempts to load the PyPortal's graphical interface

```auto
Loading GCP Graphics...
Displaying splash screen
Set icon to  /images/gcp_splash.bmp
Setting up labels...
Graphics loaded!
```

Next, the code will create a JWT. This will take a while as the code needs to grab the network time, generate a JWT, and sign the JWT with your private key.&nbsp;

```auto
Generating JWT...
Your JWT is: SUPER_LONG_JSON_WEB_TOKEN
```

Once the JWT is created, the code will attempt to connect to Google Cloud IoT.

```auto
Connecting to WiFi...
Connected!
Attempting to connect to mqtt.googleapis.com
```

When the PyPortal connects with Google Cloud, it'll print out that it's connected and attempt to subscribe to the device's default command topic (more on this later!)

```auto
Connected to Google Cloud IoT!
Flags: 0
RC: 0
Subscribed to /devices/pyportal/commands/# with QOS level 1
```

## Viewing Sensor data on PyPortal
You should see the PyPortal&nbsp;display update to display the temperature value and moisture level.

The status indicator at the bottom of the PyPortal will display when it's sending data to Google IoT. The PyPortal only sends data to Google Cloud IoT every&nbsp;`SENSOR_DELAY` minutes. Adjust this value in the code to increase or decrease the delay.

![sensors_ezgif.com-gif-maker.gif](https://cdn-learn.adafruit.com/assets/assets/000/080/089/medium640thumb/sensors_ezgif.com-gif-maker.jpg?1566945140)

## Viewing Data from Google Cloud Platform
You can view the data published to the feeds by your CircuitPython device. **Navigate to the Pub/Sub** page&nbsp;for your project at&nbsp;[https://console.cloud.google.com/cloudpubsub](https://console.cloud.google.com/cloudpubsub/).

In the topic list, **click the topic used by your IoT Core Registry**.&nbsp;&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/079/891/medium800/sensors_pub_sub.png?1566597438)

Next to _Topic details,&nbsp;_ **click Pull Messages**.&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/079/893/medium800/sensors_pull_msgs.png?1566597571)

 **Select the Cloud Pub/Sub subscription** you created earlier and **click PULL**.

You should see the message, along with the device identifier and the time which the PyPortal published the message.&nbsp;&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/080/032/medium800/sensors_data_published.png?1566926318)

You can also view the MQTT commands sent from your PyPortal to Google Cloud.&nbsp; **From the device page, click View logs** next to Stackdriver Logging.

![](https://cdn-learn.adafruit.com/assets/assets/000/079/876/medium800/sensors_Device_details_-_cpyiot_-_Google_Cloud_Platform.png?1566594240)

While the code is running on the PyPortal, the Logger displays incoming MQTT commands.

![](https://cdn-learn.adafruit.com/assets/assets/000/079/877/medium800/sensors_Logs_Viewer_-_cpyiot_-_Google_Cloud_Platform.png?1566594303)

If your code is idle (you aren't publishing data or subscribing to topics), you should see the device pinging the MQTT broker every 59 seconds (MiniMQTT sets this by default). The device does this to remain connected to the broker (effectively telling it, _"hey, I'm still here!")._

- If you'd like to ping the server less often to reduce network load or save battery, [you can manually set the MQTT client's KeepAlive value when you initialize the client object](https://circuitpython.readthedocs.io/projects/minimqtt/en/latest/api.html#adafruit_minimqtt.MQTT).

![](https://cdn-learn.adafruit.com/assets/assets/000/079/878/medium800/sensors_Logs_Viewer_-_cpyiot_-_Google_Cloud_Platform.png?1566594466)

## Sending Commands from Google IoT Core to your PyPortal

If your plant is parched, you can water it from across the world! Google Cloud IoT Core supports cloud-to-device communication.&nbsp;The provided code automatically subscribes to the default command topic ( **commands/#** ). Any incoming command will be handled by the code's&nbsp;`message()` method.

_Let's water your plant!_

With your PyPortal connected to Cloud IoT Core, **navigate to the&nbsp;_Device details_ page**. **Click the SEND COMMAND button** on the IoT Core page header.

![](https://cdn-learn.adafruit.com/assets/assets/000/079/864/medium800/sensors_Device_details_-_cpyiot_-_Google_Cloud_Platform.png?1566590030)

The Send Command API allows you to send command data as either plaintext or base64-encoded text.&nbsp;

A typical rule-of-thumb in building internet-of-things projects is to send data as a _single_ command, even if you're sending _multiple_ commands.

To do this, you'll use the [JSON file format](https://en.wikipedia.org/wiki/JSON) to construct a command containing information about the pump. The resulting JSON command will look something like the following:

`{"power":  true, "pump_time": 3}`

with `power` representing the pump's state and `pump_time` representing the duration the pump is on for (in seconds).

Now that you have a command, **enter the command** into the Command data text field and **click SEND COMMAND&nbsp;** to send your command to the PyPortal.

![](https://cdn-learn.adafruit.com/assets/assets/000/080/031/medium800/sensors_Device_details_-_cpyiot_-_Google_Cloud_Platform.png?1566922287)

You should see the message appear in the CircuitPython REPL:

```auto
Turning pump on for 3 seconds...
Plant watered!
Turning pump off
```

The pump should also turn on and water the plant for the duration you specified.

![](https://cdn-learn.adafruit.com/assets/assets/000/080/034/medium800thumb/sensors_ezgif.com-video-to-gif_%2814%29.jpg?1566928409)

The pump we're using is a peristaltic type pump - the pump _squishes_ the silicone tubing that contains the liquid instead of impelling it directly. This pump will take a while to&nbsp;move water into the tube, compress it, and push it out the other tube for your plant.

When sending a water pump message to your PyPortal - consider how long this process will take. You could send a message with a large time to determine this value. This'll value depends on a few factors including the length of your tubing and the power of your pump's motor.

 **That's it** - you have a working IoT Planter powered by Google Cloud IoT Core and CircuitPython! The next section will discuss how this code works.

# PyPortal IoT Plant Monitor with Google Cloud IoT Core and CircuitPython

## Code Walkthrough

## Importing CircuitPython Libraries
Warning: 

```auto
import time
import json
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import board
import busio
import digitalio
import gcp_gfx_helper
import neopixel
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
from adafruit_gc_iot_core import MQTT_API, Cloud_Core
from adafruit_minimqtt import MQTT
from adafruit_seesaw.seesaw import Seesaw
from digitalio import DigitalInOut
```

The code first imports all of the modules required to run the code. Some of these libraries are&nbsp;[CircuitPython core modules](https://circuitpython.readthedocs.io/en/4.x/shared-bindings/index.html)&nbsp;(they're "burned into" the firmware) and some of them you dragged into the library folder.

The code for this project&nbsp;imports a&nbsp;_special_&nbsp;`adafruit_gc_iot_core`&nbsp;library. To help simplify managing communication between your PyPortal and Google IoT Core's interfaces, we wrote a CircuitPython helper module called [Adafruit\_CircuitPython\_GC\_IOT\_Core](https://github.com/adafruit/Adafruit_CircuitPython_GC_IOT_Core)

- For more information about using the MQTT protocol with CircuitPython - check out our [MQTT in CircuitPython guide on this topic here](https://learn.adafruit.com/mqtt-in-circuitpython).

We've also included a&nbsp; **gcp\_gfx\_helper.py** &nbsp;file which handles displaying the status of the code on the PyPortal's display.

## Configuring the PyPortal's WiFi Hardware

The next chunk of code grabs information from a **settings.toml** file including wifi configuration. Then, it&nbsp;sets up the ESP32's SPI connections for use with the PyPortal. The&nbsp;`wifi`&nbsp;object is set up here too - it's used later in the code to communicate with the IoT Hub.

```auto
# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# PyPortal ESP32 Setup
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
status_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.WiFiManager(
    esp, ssid, password, status_pixel=status_pixel
)
```

## Configuring the Soil Sensor and Water Pump

An I2C busio device is set up and linked to the soil sensor's address (`0x36`). The water pump is configured as a digitalio output, since you'll be controlling the pump using the "transistor switch" circuit.

```auto
# Soil Sensor Setup
i2c_bus = busio.I2C(board.SCL, board.SDA)
ss = Seesaw(i2c_bus, addr=0x36)

# Water Pump Setup
water_pump = digitalio.DigitalInOut(board.D3)
water_pump.direction = digitalio.Direction.OUTPUT
```

## Configuring the Graphical Helper

The graphics helper, which manages' the PyPortal's display is created. If you wish to display the temperature in Fahrenheit instead of Celsius, add `is_celsius=True` to the method call.

```auto
gfx = gcp_gfx_helper.Google_GFX()

```

## Connection Callback Methods

The following methods are used as MQTT client callbacks. They only execute when the broker (Google Cloud MQTT)&nbsp; communicates with your PyPortal.

- For a complete [explanation of how MiniMQTT's callback methods work, click here](https://learn.adafruit.com/mqtt-in-circuitpython/code-walkthrough#minimqtt-callback-methods-6-7).

```auto
# Define callback methods which are called when events occur
def connect(client, userdata, flags, rc):
    # This function will be called when the client is connected
    # successfully to the broker.
    print('Connected to Google Cloud IoT!')
    print('Flags: {0}\nRC: {1}'.format(flags, rc))
    # Subscribes to commands/# topic
    google_mqtt.subscribe_to_all_commands()

def disconnect(client, userdata, rc):
    # This method is called when the client disconnects
    # from the broker.
    print('Disconnected from Google Cloud IoT!')

def subscribe(client, userdata, topic, granted_qos):
    # This method is called when the client subscribes to a new topic.
    print('Subscribed to {0} with QOS level {1}'.format(topic, granted_qos))


def unsubscribe(client, userdata, topic, pid):
    # This method is called when the client unsubscribes from a topic.
    print('Unsubscribed from {0} with PID {1}'.format(topic, pid))


def publish(client, userdata, topic, pid):
    # This method is called when the client publishes data to a topic.
    print('Published to {0} with PID {1}'.format(topic, pid))


def message(client, topic, msg):
    # This method is called when the client receives data from a topic.
    try:
        # Attempt to load a JSON command
        msg_dict = json.loads(msg)
        # Handle water-pump commands
        if msg_dict['pump_time']:
            handle_pump(msg_dict)
    except:
        # Non-JSON command, print normally
        print("Message from {}: {}".format(topic, msg))
```

## Connecting to Cloud IoT Core

We created a helper class within the&nbsp;`adafruit_gc_iot_core` module to assist creating the project identifier and handling authentication. Cloud IoT Core's settings (`Cloud_Core`) are initialized. The JWT (JSON Web Token) used for authenticating with the server is generated for you automatically using [the CircuitPython JWT module](https://github.com/adafruit/Adafruit_CircuitPython_JWT)&nbsp;and the private RSA key you provided earlier.

```auto
# Initialize Google Cloud IoT Core interface
google_iot = Cloud_Core(esp, secrets)

# JSON-Web-Token (JWT) Generation
print("Generating JWT...")
jwt = google_iot.generate_jwt()
print("Your JWT is: ", jwt)
```

After the JWT has been successfully created, we'll set up a new MiniMQTT client for communicating with the Google MQTT API. This client uses a few variables from the `google_iot` object we created earlier, along with the JWT we just generated.

The code also initializes the Google MQTT API client, an interface which simplifies using MiniMQTT to communicate with Google Core IoT.

```auto
# Set up a new MiniMQTT Client
client = MQTT(socket,
              broker=google_iot.broker,
              username=google_iot.username,
              password=jwt,
              client_id=google_iot.cid,
              network_manager=wifi)

# Initialize Google MQTT API Client
google_mqtt = MQTT_API(client)
```

The connection callback methods created earlier are connected to the `google_mqtt` client and the code attempts to connect to Google Cloud IoT Core.

```auto
# Connect callback handlers to Google MQTT Client
google_mqtt.on_connect = connect
google_mqtt.on_disconnect = disconnect
google_mqtt.on_subscribe = subscribe
google_mqtt.on_unsubscribe = unsubscribe
google_mqtt.on_publish = publish
google_mqtt.on_message = message

print('Attempting to connect to %s' % client.broker)
google_mqtt.connect()
```

Once Google's MQTT broker successfully connects with your client, it'll call the `connect()` callback method. This method subscribes to the device's default commands topic (`commands/#`). Any data sent to this topic will be received by the code's `message()`&nbsp;callback.&nbsp;&nbsp;

```auto
def connect(client, userdata, flags, rc):
    # This function will be called when the client is connected
    # successfully to the broker.
    print('Connected to Google Cloud IoT!')
    print('Flags: {0}\nRC: {1}'.format(flags, rc))
    # Subscribes to commands/# topic
    google_mqtt.subscribe_to_all_commands()
```

## Main Loop

The main loop takes the current time and compares it to the desired `SENSOR_DELAY` time in minutes (set at the top of the code).

If the time has exceeded `SENSOR_DELAY`, the code reads the moisture level and temperature from the STEMMA soil sensor. Then, it displays the values of the soil sensor on the PyPortal using the `gfx`&nbsp;module.&nbsp;

```auto
if now - initial &gt; (SENSOR_DELAY * 60):
  # read moisture level
  moisture_level = ss.moisture_read()
  # read temperature
  temperature = ss.get_temp()
  # Display Soil Sensor values on pyportal
  temperature = gfx.show_temp(temperature)
  gfx.show_water_level(moisture_level)
```

Then the `temperature` and `moisture_level` are published to the device's default events topic. We added a two second delay between publishing to ensure we don't get throttled by Google's MQTT broker.

Then, the timer will set itself to the current `time.monotonic` value.

```auto
print('Sending data to GCP IoT Core')
gfx.show_gcp_status('Publishing data...')
google_mqtt.publish(temperature, "events")
time.sleep(2)
google_mqtt.publish(moisture_level, "events")
gfx.show_gcp_status('Data published!')
print('Data sent!')
# Reset timer
initial = now
```

If the `SENSOR_DELAY` time has not yet elapsed, we'll poll the Google MQTT broker to ensure we retain communication with the broker. `google_mqtt.loop()` pings Google's MQTT broker and listenings for a response back from it. It also queries the broker for any messages received (such as a message from Google Cloud IoT telling the pump to turn on).&nbsp;

All of this code is wrapped inside a try/except control flow. If the WiFi module fails at any point, the program will execute the&nbsp;`except`&nbsp;and reset the module before going back to the top of the&nbsp;`try`.

## Handling the Water Pump Messages

One interesting chunk of this code that we haven't yet discussed is _How is data from google cloud received&nbsp;by the PyPortal_?

Since the code is subscribed to all messages from the `device/commands/#`&nbsp;topic, every message will be received by the `message()` method.&nbsp;

Since we're sending the PyPortal a message from Google Cloud in JSON format, we attempt to decode if the incoming message is a JSON dictionary.&nbsp;

If it is a JSON command, the code looks for the `pump_time` key in the JSON dictionary. If it's found, the JSON dictionary is passed to a `handle_pump` method.

If it's not a JSON command, the code will simply print out the message and the topic it was received on.&nbsp;

```auto
def message(client, topic, msg):
    # This method is called when the client receives data from a topic.
    try:
        # Attempt to decode a JSON command
        msg_dict = json.loads(msg)
        # Handle water-pump commands
        if msg_dict['pump_time']:
            handle_pump(msg_dict)
    except:
        # Non-JSON command, print normally
        print("Message from {}: {}".format(topic, msg))
```

The `handle_pump` method parses the `pump_status` and `pump_time` from the command's JSON dictionary.

If the pump command is enabling the pump, the code will print that it is starting the pump for `pump_time` and start a timer. While the timer is not expired, it'll turn on the pump by setting `water_pump.value` to `True`.

Once the timer expires, the screen will output that the plant is watered and the pump will be disabled.

```auto
def handle_pump(command):
    """Handles command about the planter's
    watering pump from Google Core IoT.
    :param json command: Message from device/commands#
    """
    print("handling pump...")
    # Parse the pump command message
    # Expected format: {"power": true, "pump_time":3}
    pump_time = command['pump_time']
    pump_status = command['power']
    if pump_status:
        print("Turning pump on for {} seconds...".format(pump_time))
        start_pump = time.monotonic()
        while True:
            gfx.show_gcp_status('Watering plant...')
            cur_time = time.monotonic()
            if cur_time - start_pump &gt; pump_time:
                # Timer expired, leave the loop
                print("Plant watered!")
                break
            water_pump.value = True
    gfx.show_gcp_status('Plant watered!')
    print("Turning pump off")
    water_pump.value = False
```


## Featured Products

### Adafruit PyPortal - CircuitPython Powered Internet Display

[Adafruit PyPortal - CircuitPython Powered Internet Display](https://www.adafruit.com/product/4116)
 **PyPortal** , our easy-to-use IoT device that allows you to create all the things for the “Internet of Things” in minutes. Make custom touch screen interface GUIs, all open-source, and Python-powered using&nbsp;tinyJSON / APIs to get news, stock, weather, cat photos,...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4116)
[Related Guides to the Product](https://learn.adafruit.com/products/4116/guides)
### Peristaltic Liquid Pump with Silicone Tubing - 12V DC Power

[Peristaltic Liquid Pump with Silicone Tubing - 12V DC Power](https://www.adafruit.com/product/1150)
Move fluid safely from here to there with this very nice little pump. Unlike most liquid pumps, [this is a peristaltic type - the pump squishes the silicone tubing that contains the liquid instead of impelling it directly](http://en.wikipedia.org/wiki/Peristaltic_pump). The upshot?...

In Stock
[Buy Now](https://www.adafruit.com/product/1150)
[Related Guides to the Product](https://learn.adafruit.com/products/1150/guides)
### Adafruit STEMMA Soil Sensor - I2C Capacitive Moisture Sensor

[Adafruit STEMMA Soil Sensor - I2C Capacitive Moisture Sensor](https://www.adafruit.com/product/4026)
Most low cost soil sensors are _resistive_ style, where there's two prongs and the sensor measures the conductivity between the two. These work OK at first, but eventually start to oxidize because of the exposed metal. Even if they're gold plated! The resistivity measurement...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4026)
[Related Guides to the Product](https://learn.adafruit.com/products/4026/guides)
### AdaBox011 - PyPortal

[AdaBox011 - PyPortal](https://www.adafruit.com/product/4061)
Reach out beyond your desk - to the stars and beyond - with **PyPortal**! This ADABOX features a new, easy-to-use IoT device that allows you to customize and create your very own "Internet of Things" portal. We take CircuitPython to the max, pairing a SAMD51 chip with a...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/4061)
[Related Guides to the Product](https://learn.adafruit.com/products/4061/guides)
### Pink and Purple Braided USB A to Micro B Cable - 2 meter long

[Pink and Purple Braided USB A to Micro B Cable - 2 meter long](https://www.adafruit.com/product/4148)
This cable is&nbsp;super-fashionable&nbsp;with a woven pink and purple Blinka-like pattern!

First let's talk about the cover and over-molding. We got these in custom colors, and if you&nbsp;_have_&nbsp;to have visible cables, then you might as well have the nicest fabric-bound...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/4148)
[Related Guides to the Product](https://learn.adafruit.com/products/4148/guides)
### Adafruit PyPortal Desktop Stand Enclosure Kit

[Adafruit PyPortal Desktop Stand Enclosure Kit](https://www.adafruit.com/product/4146)
PyPortal is&nbsp;our easy-to-use IoT device that allows you to create all the things for the “Internet of Things” in minutes. Create little pocket universes of joy that connect to something good.

And now that you've made a cool internet-connected project...

In Stock
[Buy Now](https://www.adafruit.com/product/4146)
[Related Guides to the Product](https://learn.adafruit.com/products/4146/guides)
### STEMMA Cable - 4 Pin JST-PH 2mm Cable–Female/Female

[STEMMA Cable - 4 Pin JST-PH 2mm Cable–Female/Female](https://www.adafruit.com/product/3568)
This 4-wire cable is a little over 150mm / 6" long and fitted with JST-PH female 4-pin connectors on each end. These types of JST cables are commonly found on small rechargeable battery packs, RC receivers and transmitters, tiny cameras, and other small electronic devices

We're...

Out of Stock
[Buy Now](https://www.adafruit.com/product/3568)
[Related Guides to the Product](https://learn.adafruit.com/products/3568/guides)
### NPN Bipolar Transistors (PN2222) - 10 pack

[NPN Bipolar Transistors (PN2222) - 10 pack](https://www.adafruit.com/product/756)
Transistors are powerful little electronic switches, and we really like these NPN transistors whenever we need to control medium-power electronics such as small motors, solenoids, or IR LEDs. We find them so handy, they come in a pack of 10!

Each transistor is a general-purpose...

In Stock
[Buy Now](https://www.adafruit.com/product/756)
[Related Guides to the Product](https://learn.adafruit.com/products/756/guides)

## Related Guides

- [Adafruit STEMMA Soil Sensor - I2C Capacitive Moisture Sensor](https://learn.adafruit.com/adafruit-stemma-soil-sensor-i2c-capacitive-moisture-sensor.md)
- [Adafruit PyPortal - IoT for CircuitPython](https://learn.adafruit.com/adafruit-pyportal.md)
- [PyPortal US Election Calendar](https://learn.adafruit.com/pyportal-electioncal-us.md)
- [Program CircuitPython USB Devices with iPhone & iPad](https://learn.adafruit.com/use-circuitpython-devices-with-iphone-ipad.md)
- [Arcada Animated GIF Display](https://learn.adafruit.com/pyportal-animated-gif-display.md)
- [PyPortal Thingiverse Viewer](https://learn.adafruit.com/pyportal-thingiverse-viewer.md)
- [Adafruit IO Basics: Schedule Actions](https://learn.adafruit.com/adafruit-io-basics-scheduled-triggers.md)
- [Where's My Friend? A Location-Aware Display with PyPortal and ItsASnap](https://learn.adafruit.com/where-s-my-friend-a-location-display-frame-with-pyportal.md)
- [PyPortal IoT Plant Monitor with AWS IoT and CircuitPython](https://learn.adafruit.com/pyportal-iot-plant-monitor-with-aws-iot-and-circuitpython.md)
- [Melting Picture Frame for PyPortal IoT images](https://learn.adafruit.com/pyportal-art-display.md)
- [PyPortal Reddit Stats Trophy](https://learn.adafruit.com/pyportal-reddit-stats-trophy.md)
- [Program in Logo on an Apple II](https://learn.adafruit.com/program-logo-on-an-apple-ii.md)
- [PyPortal Word of the Day Display](https://learn.adafruit.com/pyportal-word-of-the-day-display.md)
- [CircuitPython Display Support Using displayio](https://learn.adafruit.com/circuitpython-display-support-using-displayio.md)
- [PyPortal Pet Planter with Adafruit IO](https://learn.adafruit.com/pyportal-pet-planter-with-adafruit-io.md)
- [Custom Fonts for CircuitPython Displays](https://learn.adafruit.com/custom-fonts-for-pyportal-circuitpython-display.md)
