# PyPortal IoT Plant Monitor with AWS IoT and CircuitPython

## Overview

Danger: This project's code utilizes the AWS IoT Library, which currently does not work CircuitPython or with AirLift hardware, such as the Adafruit PyPortal. As a result, this project does not currently work (but may in the future).

![](https://cdn-learn.adafruit.com/assets/assets/000/082/460/medium800/sensors_IMG_2519-min.png?1571250592)

**Give your succulent some smarts by building an internet-connected plant monitor with [Amazon AWS IoT](https://aws.amazon.com/iot/) and CircuitPython.**

This smart-planter&nbsp; **monitors your plant's vitals** &nbsp;on the PyPortal's screen,&nbsp; **logs data&nbsp;** to Amazon AWS IoT, and **sends an email to your inbox when your plant needs to be watered**!

Using **Amazon AWS IoT with CircuitPython** allows you to **prototype internet-of-things projects faster than ever before**. With CircuitPython, you're able to **instantly provision your device for AWS IoT**  **by dragging and dropping certificates/keys.&nbsp;**

We've adapted [the excellent Monitoring Soil Moisture with AWS IoT And Raspberry Pi guide on the AWS IoT Developer Guide](https://docs.aws.amazon.com/en_pv/iot/latest/developerguide/iot-moisture-tutorial.html) to work with CircuitPython on microcontrollers.

# AWS IoT

[AWS IoT](https://aws.amazon.com/iot/) is an IoT service for those looking for an incredibly scalable and secure Internet-of-Things (IoT) service.

### Integration with the AWS Ecosystem

Connect your CircuitPython device to integrate with Amazon Web Services such as Amazon S3, AWS Lambda, Amazon Kinesis, and more!&nbsp;

### Security

We've tried all the major IoT cloud service providers, and AWS IoT offers a higher level of security. This is due to features such as secure device provisioning, access-resource policies for device MQTT feeds, and a service to continuously monitor and report potential security threats.

![sensors_1_vIe-kMMyoKQKmxa-qUzIeA.png](https://cdn-learn.adafruit.com/assets/assets/000/082/382/medium640/sensors_1_vIe-kMMyoKQKmxa-qUzIeA.png?1571065612)

## 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 an [CircuitPython AWS IoT](https://github.com/adafruit/Adafruit_CircuitPython_AWS_IOT) helper module to make interacting with AWS IoT _incredibly_ simple. Provisioning CircuitPython devices is as simple as adding your device certificate and private RSA key to a file.&nbsp;

**You can rapidly update your code without having to compile** and store WiFi information and AWS IoT device configuration on your microcontroller. 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/082/381/medium640/sensors_blinka.png?1571065478)

## Prerequisite Guides

This is an **intermediate-level** CircuitPython guide. 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,...

In 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)

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

### 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 AWS IoT and CircuitPython

## PyPortal Wiring 

Danger: This project's code utilizes the Azure IoT Library which currently does not work with AirLift hardware, such as the Adafruit PyPortal. As a result, this project does not currently work (but may in the future).

For a more updated guide using CircuitPython and Microsoft Azure IoT, visit https://learn.adafruit.com/getting-started-with-microsoft-azure-and-circuitpython

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's I2C port.

### 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)
![Angled shot of 150mm/6" long 4-Pin JST-PH Cable](https://cdn-shop.adafruit.com/640x480/3568-05.jpg)

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

- **PyPortal 5V** 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**

![wireless_output-onlinepngtools_(1).png](https://cdn-learn.adafruit.com/assets/assets/000/075/912/medium640/wireless_output-onlinepngtools_%281%29.png?1558642532)

_That's it_ - your PyPortal is wired up!

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

![](https://cdn-learn.adafruit.com/assets/assets/000/076/033/medium800/wireless_IMG_4960.jpg?1558727940)

# PyPortal IoT Plant Monitor with AWS IoT and CircuitPython

## AWS IoT Setup

Danger: This project's code utilizes the AWS IoT Library, which currently does not work CircuitPython or with AirLift hardware, such as the Adafruit PyPortal. As a result, this project does not currently work (but may in the future).

The setup required for this guide is a bit lengthy (about 15-30 minutes if you already have an Amazon Web Services account). However, it's mostly setup and you do not need to repeat the entire guide each time you start a new project.

You'll need an AWS account to access the Amazon AWS platform. Head over to [https://aws.amazon.com/iot/](https://aws.amazon.com/iot/) and click&nbsp; **Create an AWS Account&nbsp;** to create an account.

Warning: 

# Create an AWS IoT Policy

AWS uses IoT policies to "give devices permissions to access AWS IoT resources". These resources range from _data_, such as information stored in MQTT topics, to _actions&nbsp;_such as publishing/subscribing to AWS IoT MQTT topics.

Each AWS IoT policy is tied to a device-specific X.509 certificate, which authenticates your CircuitPython device with the AWS IoT server. It's a good security practice to have a _separate_ AWS IoT Policy and X.509 certificate for each CircuitPython device you're connecting to AWS IoT.

From the AWS Management Console, **search for the "IoT Core" service**.

![](https://cdn-learn.adafruit.com/assets/assets/000/082/385/medium800/sensors_AWS_Management_Console.png?1571069154)

The AWS IoT monitor page should open. From here, click&nbsp; **Secure** on the left-hand sidebar.

You should be directed to the AWS IoT Monitor page.

**Click**  **Secure** &nbsp;on the left-hand sidebar.&nbsp;

From the dropdown, **click Policies**.&nbsp;

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/386/medium640/sensors_AWS_IoT.png?1571069290)

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/387/medium640/sensors_AWS_IoT.png?1571069359)

You'll be directed to the AWS IoT Policies page. **Click the Create button** on the header of this page.

![](https://cdn-learn.adafruit.com/assets/assets/000/082/388/medium800/sensors_AWS_IoT.png?1571069437)

 **Set the name of the policy to** _PyPortal-Policy_

**Set the Action** to&nbsp;_iot:\*_

**Set the Resource ARN** to _\*_

- **Note:&nbsp;** We are creating an "allow-all" (by using the _\*_ wildcard) ARN here to keep the guide's instructions simple. If you're actively deploying AWS IoT devices, you'll want to only allow specific actions/topics for specific devices.&nbsp;
  - [Check out the AWS IoT Developer Guide page on AWS IoT Policies for more information](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html)...

Under Effect, **Click Allow&nbsp;** to allow all clients using this policy to connect to AWS IoT.

**Click Create**. You should see the new policy appear under _Policies_ and a green dialog stating that you've successfully created a policy.

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/389/medium640/sensors_AWS_IoT.png?1571069957)

![sensors_policy_success.png](https://cdn-learn.adafruit.com/assets/assets/000/082/391/medium640/sensors_policy_success.png?1571070013)

# Create an AWS IoT Thing

In AWS IoT terms, we're going to register your PyPortal as an AWS IoT Thing. Each device registered to AWS IoT is called a _thing_ and tracked/managed in a _thing registry_.

You'll be creating an AWS IoT Thing named PyPortal.

From the AWS IoT sidebar, **click Manage**.&nbsp;

You should be brought to your Things registry page.

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/394/medium640/sensors_AWS_IoT.png?1571070524)

From the Things registry, **click the Create button**.

![](https://cdn-learn.adafruit.com/assets/assets/000/082/393/medium800/sensors_AWS_IoT.png?1571070484)

You'll be registering a thing, your PyPortal, in your registry.

**Click the _Create a single thing_ button.**

**Name the thing** _PyPortal_.&nbsp; **Click Next.**

![sensors_reg_single_thing.png](https://cdn-learn.adafruit.com/assets/assets/000/082/395/medium640/sensors_reg_single_thing.png?1571070677)

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/396/medium640/sensors_AWS_IoT.png?1571070771)

Next, you'll need to create (or add) a certificate to your PyPortal. This helps authenticate its connection with the AWS IoT server.

- **Click** &nbsp;_One-click certificate creation_.
  - **Note** - if you're [using an ATECC608 breakout to generate a Certificate Signing Request](https://learn.adafruit.com/adafruit-atecc608-breakout/python-circuitpython#self-signed-certificate-demo-3-24), **click** _Use CSR_&nbsp;and **upload**  **the CSR your module generated**.

- After the certificate has been created. **Download the device's certificate and private key to your desktop.**  

  - You _may_ also download the public key, but it's not required for this guide.

- Then, **click Activate** to activate the root CA for AWS IoT.&nbsp; If successfully activated, the text for the button should change to _Deactivate_.
  - You do not need to download the root CA. This certificate, along may other root CA certificates is already burned into your PyPortal's ESP32 already.

- **Click _Attach a policy_**

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/397/medium640/sensors_AWS_IoT.png?1571070946)

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/399/medium640/sensors_AWS_IoT.png?1571071025)

 **Select the _PyPortal-Policy_ you made earlier**. You can click&nbsp;_view_ to verify your policy against the policy in the screenshot below. This step attaches the policy you created to the PyPortal's X.509 certificate.

If everything looks correct, **click Register Thing**.

![](https://cdn-learn.adafruit.com/assets/assets/000/082/400/medium800/sensors_AWS_IoT.png?1571071226)

One last thing - certificates are&nbsp;_inactive&nbsp;_by default. You'll need to activate yours.

- From the AWS IoT sidebar, navigate to **Secure -\> Certificates_.&nbsp;_**
- Your newly generated certificate should appear below as _INACTIVE_.&nbsp;
- **Click the three-bubble icon** &nbsp;to bring up a dropdown menu.
- **Click Activate** , your certificate should show up on this page as _ACTIVE_.

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/401/medium640/sensors_AWS_IoT.png?1571071688)

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/402/medium640/sensors_AWS_IoT.png?1571071699)

With your AWS IoT Device, policy, and certificate created, you can move on.

# Create an Amazon SNS Topic/Subscription

[Amazon's Simple Notification Service (SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) is a way to send notification topics to an endpoint. In this project, you'll be writing to Amazon AWS IoT topics and using Amazon SNS to send notification messages _from_ a topic _to_ your inbox.

From the AWS Management Console, use the search-box to **search for the Simple Notification Service**

![](https://cdn-learn.adafruit.com/assets/assets/000/082/403/medium800/sensors_AWS_Management_Console.png?1571072320)

From the Amazon SNS sidebar, **click Topics**. Then, **click**  **Create Topic**.

![](https://cdn-learn.adafruit.com/assets/assets/000/082/404/medium800/sensors_Simple_Notification_Service.png?1571072427)

- **Name the topic** &nbsp;_moisture_
- **Set the Display name** &nbsp;to&nbsp;_PyPortal Moisture Sensor Topic_

**Click the Create Topic button**.

![sensors_Simple_Notification_Service.png](https://cdn-learn.adafruit.com/assets/assets/000/082/405/medium640/sensors_Simple_Notification_Service.png?1571072583)

Next, you'll need to create a subscription to this topic. This subscription will be updated whenever the topic receives new data (i.e. whenever your PyPortal's moisture sensor sends an update to AWS IoT).

- From the moisture topic page, **click Create Subscription**
- **Set the protocol to Email**
- **Set the Endpoint to your email address**

**Click** _Create Subscription_

![sensors_Simple_Notification_Service.png](https://cdn-learn.adafruit.com/assets/assets/000/082/406/medium640/sensors_Simple_Notification_Service.png?1571072756)

![sensors_Simple_Notification_Service.png](https://cdn-learn.adafruit.com/assets/assets/000/082/407/medium640/sensors_Simple_Notification_Service.png?1571072848)

Check the inbox of the email you entered as an endpoint. You should receive an email to confirm your topic subscription.

**Click** _Confirm Subscription_

Check the inbox of the email you entered as an endpoint. You should receive an email to confirm your topic subscription.

- If you did not receive an email, check your spam folder.

**Click&nbsp;** _ **Confirm**  **Subscription**.&nbsp;_You should be redirected to an AWS link notifying you that your subscription has been confirmed.&nbsp;

![sensors_AWS_Notification_-_Subscription_Confirmation_-_brent_adafruit_com_-_Adafruit_Industries_Mail.png](https://cdn-learn.adafruit.com/assets/assets/000/082/410/medium640/sensors_AWS_Notification_-_Subscription_Confirmation_-_brent_adafruit_com_-_Adafruit_Industries_Mail.png?1571073171)

![sensors_https___sns_us-east-2_amazonaws_com_confirmation_html_TopicArn_arn_aws_sns_us-east-2_168508638036_moisture_Token_2336412f37fb687f5d51e6e241dbca538ac35623df4a3e64601eb2de57057519bb5c9c8614512d47c1a431bad19c87134931f5dd10db8d800979f1d5ed9813a.png](https://cdn-learn.adafruit.com/assets/assets/000/082/411/medium640/sensors_https___sns_us-east-2_amazonaws_com_confirmation_html_TopicArn_arn_aws_sns_us-east-2_168508638036_moisture_Token_2336412f37fb687f5d51e6e241dbca538ac35623df4a3e64601eb2de57057519bb5c9c8614512d47c1a431bad19c87134931f5dd10db8d800979f1d5ed9813a.png?1571073183)

# Create an AWS IoT Rule

One of the advantages of using AWS IoT is the ability to send data from your devices with other AWS services such as S3, Lambda or Amazon ML. You are going to create a rule to send data to the Amazon SNS topic, from AWS IoT.

[For more information about AWS IoT Rules, visit the AWS IoT docs](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html).

To set up a new rule:

- Navigate to your AWS IoT Console and&nbsp; **click Act**.&nbsp;
- **Click the Create button**
- **Name the rule** _MoistureSensorRule_
- **Set the description** to what the rule does when invoked
  - For example, this rule will send an email when the plant's moisture sensor is too low.

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/417/medium640/sensors_AWS_IoT.png?1571076365)

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/418/medium640/sensors_AWS_IoT.png?1571076400)

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/419/medium640/sensors_AWS_IoT.png?1571076627)

Under _Rule query statement,_ **make sure you're** _Using SQL version_ **2016-03-23**.

Copy and paste the SQL statement below into the _Rule query statement_ field:&nbsp;

```python
SELECT * FROM '$aws/things/PyPortal/shadow/update/accepted' WHERE state.reported.moisture &lt; 400
```

AWS IoT rules use a SQL statement to filter messages received on a MQTT topic. This SQL statement selects everything on the AWS IoT MQTT topic _$aws/things/PyPortal/shadow/update/accepted.&nbsp;_Then, it filters the data points on this topic for where the moisture level is less than 400.

For more information about AWS IoT's SQL rules, [visit the AWS IoT SQL Reference page](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-reference.html).

Next, let's select and configure an action to be invoked when this rule is satisfied.

- **Click** _Add action_.
- From _Select an action_, **click Send a message as an SNS push notification**.

On the _Configure action_ page,&nbsp;

- **Select** _moisture_ as the SNS target.
- **Set the message format** to _RAW_.

![sensors_aws_rule_action.png](https://cdn-learn.adafruit.com/assets/assets/000/082/420/medium640/sensors_aws_rule_action.png?1571077200)

![sensors_aws_rule_sns_push.png](https://cdn-learn.adafruit.com/assets/assets/000/082/421/medium640/sensors_aws_rule_sns_push.png?1571077222)

![sensors_sns_action_target_format.png](https://cdn-learn.adafruit.com/assets/assets/000/082/422/medium640/sensors_sns_action_target_format.png?1571077293)

We'll want to create a role to grant AWS access to perform the action.

**Click Create Role** and **name**  **this**  **role** _PyPortalMoistureTopicRole._

**Click the Add action button**.

![sensors_AWS_IoT.png](https://cdn-learn.adafruit.com/assets/assets/000/082/427/medium640/sensors_AWS_IoT.png?1571077637)

![sensors_sns_rule_config.png](https://cdn-learn.adafruit.com/assets/assets/000/082/429/medium640/sensors_sns_rule_config.png?1571077867)

You should be brought back to the&nbsp;_Create a rule_&nbsp;page.&nbsp; **Click Create Rule**.

The&nbsp;_MoistureSensorRule&nbsp;_should appear in your AWS IoT Console's Rules page.

![sensors_moisture_sensor_rule.png](https://cdn-learn.adafruit.com/assets/assets/000/082/430/medium640/sensors_moisture_sensor_rule.png?1571078311)

Congrats, you've set up AWS IoT, configured a device, and configured AWS IoT to send an email when a AWS IoT MQTT topic is updated with a value below a set threshold.

# PyPortal IoT Plant Monitor with AWS IoT and CircuitPython

## Upgrading ESP32 Firmware

Danger: This project's code utilizes the AWS IoT Library, which currently does not work CircuitPython or with AirLift hardware, such as the Adafruit PyPortal. As a result, this project does not currently work (but may in the future).

Warning: 

The ESP32 on your PyPortal is running an older version of the firmware which runs on the ESP32 (named [nina-fw](https://github.com/adafruit/nina-fw)). To use your PyPortal with AWS IoT, you'll need to update the ESP32's firmware the latest version of nina-fw.

**Click the button below for the relevant steps on upgrading the ESP32 on your PyPortal** and continue with the guide when you've successfully upgraded to **nina-fw 1.4.0 or above**.

[Instructions for upgrading the PyPortal's ESP32 Firmware](https://learn.adafruit.com/upgrading-esp32-firmware/upgrade-an-airlift-all-in-one-board)
# PyPortal IoT Plant Monitor with AWS IoT 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 AWS IoT 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 AWS IoT 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 AWS IoT and CircuitPython

## Code Setup

Danger: This project's code utilizes the AWS IoT Library, which currently does not work CircuitPython or with AirLift hardware, such as the Adafruit PyPortal. As a result, this project does not currently work (but may in the future).

# 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.

Use the download project bundle button and instructions below to get the project files and required libraries.

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

Then,&nbsp; **uncompress the .zip file** , it will unpack to a folder named&nbsp; **PyPortal\_AWS\_IOT\_Planter**.

Copy the contents of **PyPortal\_AWS\_IOT\_Planter** directory to your PyPortal&nbsp; **CIRCUITPY** &nbsp;drive.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/PyPortal/PyPortal_AWS_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_AWS_IOT_Planter.png )

# Install the 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)
# Custom URL for AWS
Before you set up the **settings.toml** file for this project, you'll need to retrieve your AWS IOT's custom endpoint URL.

Navigate to your AWS IoT dashboard and **click Settings on the sidebar.&nbsp;** Your custom endpoint will be posted at the _top_ of this page. **Copy this value and save it somewhere safe** , you'll need it in the next step.

![](https://cdn-learn.adafruit.com/assets/assets/000/082/432/medium800/sensors_AWS_IoT.png?1571082867)

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

Update the&nbsp; **settings.toml** &nbsp;file to include your WiFI credentials, and replace the BROKER value with the URL of your AWS IoT custom endpoint.

```auto
CIRCUITPY_WIFI_SSID = "your_wifi_ssid"
CIRCUITPY_WIFI_PASSWORD = "your_wifi_password"
TIMEZONE = "America/New_York"  # http://worldtimeapi.org/timezones
BROKER = "your_AWS_IOT_endpoint_url"
CLIENT_ID = "PyPortal"
```

## Adding your AWS IoT Device Certificate and Key to CIRCUITPY

CircuitPython makes loading your AWS IoT device certificate and private key as easy as drag and drop. _Seriously_ - we're going to drag and drop the two files we downloaded earlier onto the filesystem.

AWS IoT names the certificate and RSA private key randomly (your private key file should look something like: `8a1018d558-private.pem.key`).&nbsp; You're going to rename the key/certificate so they'll be easier to reference them in the code.

**Rename your key from** `RANDOMALPHANUMERICSTRING-private.pem.key` **to** `private.pem.key`

**Rename your certificate from** `RANDOMALPHANUMERICSTRING-certificate.pem.crt` **to** `aws_cert.pem.crt`.

Then, copy them over to the **CIRCUITPY** volume.&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/082/436/medium800/sensors_cert_key_fs.png?1571155927)

With the certificates copied over, you're good to go! Let's continue to the usage section.

# PyPortal IoT Plant Monitor with AWS IoT and CircuitPython

## Code Usage

Danger: This project's code utilizes the AWS IoT Library, which currently does not work CircuitPython or with AirLift hardware, such as the Adafruit PyPortal. As a result, this project does not currently work (but may in the future).

When the PyPortal starts up, it will first load the **aws\_splash.bmp** image in the images folder on your **CIRCUITPY** drive. This is a "loading screen" while the code waits for the fonts and display objects load on the screen.

![sensors_aws_splash.bmp](https://cdn-learn.adafruit.com/assets/assets/000/082/465/medium640/sensors_aws_splash.bmp?1571253731)

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

```python
Loading AWS IoT Graphics...
Displaying splash screen
Set icon to  /images/aws_splash.bmp
Setting up labels...
Graphics loaded!
```

Then, the PyPortal's ESP32 will attempt to connect to the WiFi network defined in the **secrets.py** file. Once connected to a wireless network, the PyPortal will attempt to authenticate with the AWS IOT endpoint with the certificate and private key .

```python
Connecting to WiFi...
Connected!
Attempting to connect to a39rd7hlvdi9mt-ats.iot.us-east-2.amazonaws.com
Connected to AWS IoT!
```

Once connected, the MiniMQTT client subscribes to all messages on the device's shadow topic.

```python
Subscribing to shadow updates...
Subscribed to $aws/things/PyPortal/shadow/update/# with QOS level 1
```

Every `SENSOR_DELAY` minutes, the PyPortal will read the STEMMA sensor's moisture level and temperature. Then, it'll send it to Amazon AWS IoT.

```python
Moisture Level:  380
Temperature: 61°F
Sending data to AWS IoT...
Data sent!
```

Since you subscribed to the `$aws/things/thingName/shadow/update` feed, you'll see a message returned by the `message` callback signifying that the message has been accepted by the Adafruit AWS device shadow.

```python
Message from $aws/things/PyPortal/shadow/update/accepted: {"state":{"reported":{"temp":"61","moisture":"380"}}
```

# 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 AWS IoT. The PyPortal only sends data to AWS IoT every `SENSOR_DELAY`&nbsp;minutes. Adjust this value in the code to increase or decrease the delay.

![sensors_ezgif.com-video-to-gif.gif](https://cdn-learn.adafruit.com/assets/assets/000/082/468/medium640thumb/sensors_ezgif.com-video-to-gif.jpg?1571256892)

# Receiving Emails from AWS IoT and Amazon SNS

Once the moisture level dips below 400 (the limit you set earlier), Amazon Simple Notification Service will send an email to you to remind you to water your plant.

_Want to change this value?_ Simply [edit the AWS IoT Rule you configured earlier in the guide here](https://learn.adafruit.com/pyportal-iot-plant-monitor-with-aws-iot-and-circuitpython/aws-iot-setup?#create-an-aws-iot-rule-3-28).

![](https://cdn-learn.adafruit.com/assets/assets/000/082/458/medium800/sensors_AWS_Notification_Message_-_brent_adafruit_com_-_Adafruit_Industries_Mail.png?1571239712)

# Remember to Check Your Inbox!

AWS SNS will deliver up to a thousand emails to your inbox, free of charge. **After that limit is reached, SNS will charge you $2.00 per 100,000 emails.** &nbsp;

While it's unlikely your PyPortal Plant Monitor will ever reach 1,000 emails per month, it's important to check the email connected to Amazon SNS to ensure your code isn't continuously firing notifications when your plant needs to be watered. You may also want to increase the `SENSOR_DELAY` in your code to check the plant's vitals every few hours, instead of every fifteen minutes.

[Visit the Amazon SNS product page to learn more about its pricing](https://aws.amazon.com/sns/pricing/).

# PyPortal IoT Plant Monitor with AWS IoT and CircuitPython

## Code Walkthrough

Danger: This project's code utilizes the AWS IoT Library, which currently does not work CircuitPython or with AirLift hardware, such as the Adafruit PyPortal. As a result, this project does not currently work (but may in the future).

# Importing CircuitPython Libraries
```python
import os
import time
import json
import board
import busio
from digitalio import DigitalInOut
import neopixel
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_minimqtt import MQTT
from adafruit_aws_iot import MQTT_CLIENT
from adafruit_seesaw.seesaw import Seesaw
import aws_gfx_helper
```

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) (they're "burned into" the firmware) and some of them you dragged into the library folder ( **lib** on the PyPortal's **CIRCUITPY** drive).

The code for this project&nbsp;imports a&nbsp;_special_&nbsp;`adafruit_aws_iot` library. To help simplify managing communication between your PyPortal and AWS IoT's MQTT API, we wrote a CircuitPython helper module called&nbsp;[Adafruit\_CircuitPython\_AWS\_IOT](https://github.com/adafruit/Adafruit_CircuitPython_AWS_IOT)

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

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

# Configuring the PyPortal's ESP32
The next chunk of code grabs information from your **settings.tom** &nbsp;file about your WiFi AP configuration, AWS device identifier and AWS IoT endpoint. The device certificate and RSA private key are read into variables, `DEVICE_CERT` and `DEVICE_KEY`.

```python
# Get device certificate
try:
    with open("aws_cert.pem.crt", "rb") as f:
        DEVICE_CERT = f.read()
except ImportError:
    print("Certificate (aws_cert.pem.crt) not found on CIRCUITPY filesystem.")
    raise

# Get device private key
try:
    with open("private.pem.key", "rb") as f:
        DEVICE_KEY = f.read()
except ImportError:
    print("Key (private.pem.key) not found on CIRCUITPY filesystem.")
    raise
```

Then, it sets up the ESP32's SPI connections for use with the PyPortal along with a `wifi` manager for interfacing with the ESP32.

```python
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
# Verify nina-fw version &gt;= 1.4.0
assert int(bytes(esp.firmware_version).decode("utf-8")[2]) &gt;= 4, "Please update nina-fw to &gt;=1.4.0."

status_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.WiFiManager(
    esp, ssid, password, status_pixel=status_pixel
)
```

# 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&nbsp;`is_celsius=True`&nbsp;to the method call.

```python
# Initialize the graphics helper
print("Loading AWS IoT Graphics...")
gfx = aws_gfx_helper.AWS_GFX()
print("Graphics loaded!")
```

# Connecting to WiFi and&nbsp;AWS IoT

Prior to establishing a connection with the AWS MQTT broker, we'll use the `esp` object to set the AWS device certificate and private key.

```python
# Set AWS Device Certificate
esp.set_certificate(DEVICE_CERT)

# Set AWS RSA Private Key
esp.set_private_key(DEVICE_KEY)
```

Once the certificate and private key have been set, we can connect to the WiFi network _and_ the AWS IoT MQTT broker.

```python
# Connect to WiFi
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")
```

# Configure the STEMMA Sensor

An I2C `busio` device is set up and linked to the soil sensor's address (`0x36`).

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

# MQTT Connection Callback Methods

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

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

```python
# Define callback methods which are called when events occur
# pylint: disable=unused-argument, redefined-outer-name
def connect(client, userdata, flags, rc):
    # This function will be called when the client is connected
    # successfully to the broker.
    print('Connected to AWS IoT!')
    print('Flags: {0}\nRC: {1}'.format(flags, rc))

    # Subscribe client to all shadow updates
    print("Subscribing to shadow updates...")
    aws_iot.shadow_subscribe()


def disconnect(client, userdata, rc):
    # This method is called when the client disconnects
    # from the broker.
    print('Disconnected from AWS 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.
    print("Message from {}: {}".format(topic, msg))
```

# Connecting to AWS IoT

The code first initializes the AWS MQTT client with the endpoint identifier (`broker`) and device identifier (`client_id`).

```python
# Set up a new MiniMQTT Client
client =  MQTT(socket,
               broker = os.getenv("BROKER"),
               client_id = os.getenv("CLIENT_ID"),
               network_manager = wifi)

# Initialize AWS IoT MQTT API Client
aws_iot = MQTT_CLIENT(client)
```

The connection callback methods created earlier are connected to the&nbsp;`aws_iot`&nbsp;client and the code attempts to connect to AWS IoT.

```python
# Connect callback handlers to AWS IoT MQTT Client
aws_iot.on_connect = connect
aws_iot.on_disconnect = disconnect
aws_iot.on_subscribe = subscribe
aws_iot.on_unsubscribe = unsubscribe
aws_iot.on_publish = publish
aws_iot.on_message = message

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

Once AWS IoT's MQTT broker successfully connects with your client, it'll call the&nbsp;`connect()`&nbsp;callback method. This method subscribes to[the device's shadow topic](https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-mqtt.html) and listens for updates (`aws_iot.shadow_subscribe()`). Any data sent to this topic will be received by the code's&nbsp;`message()`&nbsp;callback.&nbsp;&nbsp;

```python
def connect(client, userdata, flags, rc):
    # This function will be called when the client is connected
    # successfully to the broker.
    print('Connected to AWS IoT!')
    print('Flags: {0}\nRC: {1}'.format(flags, rc))

    # Subscribe client to all shadow updates
    print("Subscribing to shadow updates...")
    aws_iot.shadow_subscribe()
```

# Main Loop

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

If the time has exceeded&nbsp;`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&nbsp;`gfx`&nbsp;module.&nbsp;

```python
# Time in seconds since power on
initial = time.monotonic()

while True:
    try:
        gfx.show_aws_status('Listening for msgs...')
        now = time.monotonic()
        if now - initial &gt; (0.1 * 60):
            # read moisture level
            moisture = ss.moisture_read()
            print("Moisture Level: ", moisture)
            # read temperature
            temperature = ss.get_temp()
            print("Temperature:{}F".format(temperature))
            # Display Soil Sensor values on pyportal
            temperature = gfx.show_temp(temperature)
            gfx.show_water_level(moisture)
```

We create a JSON-formatted payload (AWS device shadows require this format) to hold _both_ the moisture and temperature. Then, we update the shadow using the handy `shadow_update()` helper method from the CircuitPython AWS IoT library.&nbsp;

We'll update the display to show data has been published to AWS IoT and set the timer to the current `time.monotonic` value.

```python
print('Sending data to AWS IoT...')
            gfx.show_aws_status('Publishing data...')
            # Create a json-formatted device payload
            payload = {"state":{"reported":
                        {"moisture":str(moisture),
                        "temp":str(temperature)}}}
            # Update device shadow
            aws_iot.shadow_update(json.dumps(payload))
            gfx.show_aws_status('Data published!')
            print('Data sent!')
            # Reset timer
            initial = now
```

If the&nbsp;`SENSOR_DELAY`&nbsp;time has not yet elapsed, we'll poll the AWS MQTT broker to ensure we retain communication with the broker.&nbsp;`aws_iot.loop()`&nbsp;pings AWS IOT's MQTT broker and listenings for a response back from it. It also queries the broker for any messages received.

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`.


## 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,...

In Stock
[Buy Now](https://www.adafruit.com/product/4116)
[Related Guides to the Product](https://learn.adafruit.com/products/4116/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)
### 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)
### 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)

## 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)
- [MQTT in CircuitPython](https://learn.adafruit.com/mqtt-in-circuitpython.md)
- [PyPortal IoT Data Logger with Analog Devices ADT7410, Adafruit IO and CircuitPython](https://learn.adafruit.com/iot-pyportal-data-logger-adafruitio-circuitpython.md)
- [CircuitPython Minesweeper Game](https://learn.adafruit.com/circuitpython-pyportal-minesweeper-game.md)
- [PyPortal IoT Weather Station](https://learn.adafruit.com/pyportal-iot-weather-station.md)
- [PyPortal Hurricane Tracker](https://learn.adafruit.com/pyportal-hurricane-tracker.md)
- [Playing Animated GIF Files in CircuitPython](https://learn.adafruit.com/using-animated-gif-files-in-circuitpython.md)
- [PyPortal IoT Plant Monitor with Microsoft Azure IoT and CircuitPython](https://learn.adafruit.com/using-microsoft-azure-iot-with-circuitpython.md)
- [Daily UV Index PyPortal Display](https://learn.adafruit.com/pyportal-uv-index.md)
- [How to Make Animated Graphics for Hologram Displays](https://learn.adafruit.com/how-to-make-animated-graphics-for-hologram-displays.md)
- [CircuitPython Your Own Adventure](https://learn.adafruit.com/circuit-python-your-own-adventure.md)
- [PyPortal Roku Remote](https://learn.adafruit.com/pyportal-roku-remote.md)
- [League of Legends Level Trophy for PyPortal](https://learn.adafruit.com/league-of-legends-level-trophy-for-pyportal.md)
- [Custom Fonts for CircuitPython Displays](https://learn.adafruit.com/custom-fonts-for-pyportal-circuitpython-display.md)
- [PyPortal Oblique Strategies](https://learn.adafruit.com/pyportal-oblique-strategies.md)
- [PyPortal MQTT Sensor Node/Control Pad for Home Assistant](https://learn.adafruit.com/pyportal-mqtt-sensor-node-control-pad-home-assistant.md)
