Skip to content

Commit f4882f2

Browse files
committed
docs: add native networking example
1 parent 2caabf3 commit f4882f2

File tree

1 file changed

+123
-0
lines changed

1 file changed

+123
-0
lines changed

examples/aws_iot_native_networking.py

+123
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
# SPDX-FileCopyrightText: 2023 ladyada for Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
4+
import time
5+
import ssl
6+
import socketpool
7+
import wifi
8+
import json
9+
import adafruit_minimqtt.adafruit_minimqtt as MQTT
10+
from adafruit_aws_iot import MQTT_CLIENT
11+
12+
# Add a secrets.py to your filesystem that has a dictionary called "secrets". DO NOT share that
13+
# file or commit it into Git or other source control. The "secrets" dictionary should have the
14+
# following keys:
15+
# "ssid" - Your WiFi ssid
16+
# "password" - Your WiFi password
17+
# "device_cert_path" - Path to the Device Certificate from AWS IoT ("<THING_NAME>.cert.pem")
18+
# "device_key_path" - Path to the RSA Private Key from AWS IoT ("<THING_NAME>.private.key")
19+
# "broker" - The endpoint for the AWS IoT broker ("<PREFIX>.iot.<REGION>.amazonaws.com")
20+
# "port" - The port for the "broker" above (8883)
21+
# "client_id" - The client id. Your device's Policy needs to allow this client ("basicPubSub")
22+
#
23+
# pylint: disable=no-name-in-module,wrong-import-order
24+
try:
25+
from secrets import secrets
26+
except ImportError:
27+
print("WiFi secrets are kept in secrets.py, please add them there!")
28+
raise
29+
30+
### Code ###
31+
32+
# Your device's Policy needs to allow this topic
33+
topic = "sdk/test/python"
34+
35+
# Define callback methods which are called when events occur
36+
# pylint: disable=unused-argument, redefined-outer-name
37+
def connect(client, userdata, flags, rc):
38+
# This function will be called when the client is connected
39+
# successfully to the broker.
40+
print("Connected to MQTT Broker!")
41+
print("Flags: {0} - RC: {1}".format(flags, rc))
42+
43+
# Subscribe to topic circuitpython/aws
44+
print("Subscribing to topic {}".format(topic))
45+
aws_iot.subscribe(topic)
46+
47+
48+
def disconnect(client, userdata, rc):
49+
# This method is called when the client disconnects
50+
# from the broker.
51+
print("Disconnected from MQTT Broker!")
52+
53+
54+
def subscribe(client, userdata, topic, granted_qos):
55+
# This method is called when the client subscribes to a new topic.
56+
print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))
57+
58+
# Create a json-formatted message
59+
message = {"message": "Hello from AWS IoT CircuitPython"}
60+
# Publish message to topic
61+
aws_iot.publish(topic, json.dumps(message))
62+
63+
64+
def unsubscribe(client, userdata, topic, pid):
65+
# This method is called when the client unsubscribes from a topic.
66+
print("Unsubscribed from {0} with PID {1}".format(topic, pid))
67+
68+
69+
def publish(client, userdata, topic, pid):
70+
# This method is called when the client publishes data to a topic.
71+
print("Published to {0} with PID {1}".format(topic, pid))
72+
73+
74+
def message(client, topic, msg):
75+
# This method is called when the client receives data from a topic.
76+
print("Message from {}: {}".format(topic, msg))
77+
78+
79+
print("Connecting to %s" % secrets["ssid"])
80+
wifi.radio.connect(secrets["ssid"], secrets["password"])
81+
print("Connected to %s!" % secrets["ssid"])
82+
83+
# Create a socket pool
84+
pool = socketpool.SocketPool(wifi.radio)
85+
ssl_context = ssl.create_default_context()
86+
87+
# Set AWS Device Certificate and AWS RSA Private Key
88+
ssl_context.load_cert_chain(
89+
certfile=secrets['device_cert_path'],
90+
keyfile=secrets['device_key_path']
91+
)
92+
93+
# Set up a MiniMQTT Client
94+
mqtt_client = MQTT.MQTT(
95+
broker=secrets["broker"],
96+
port=secrets["port"],
97+
is_ssl=True, # ssl is required
98+
client_id=secrets["client_id"],
99+
socket_pool=pool,
100+
ssl_context=ssl_context,
101+
)
102+
103+
# Initialize AWS IoT MQTT API Client
104+
aws_iot = MQTT_CLIENT(mqtt_client)
105+
106+
# Connect callback handlers to AWS IoT MQTT Client
107+
aws_iot.on_connect = connect
108+
aws_iot.on_disconnect = disconnect
109+
aws_iot.on_subscribe = subscribe
110+
aws_iot.on_unsubscribe = unsubscribe
111+
aws_iot.on_publish = publish
112+
aws_iot.on_message = message
113+
114+
print("Attempting to connect to %s" % mqtt_client.broker)
115+
aws_iot.connect()
116+
117+
# Start a blocking message loop...
118+
# NOTE: NO code below this loop will execute
119+
# NOTE: Network reconnection is NOT handled within this loop
120+
while True:
121+
aws_iot.loop()
122+
123+
time.sleep(1)

0 commit comments

Comments
 (0)