Pycom Documentation
  • Introduction
  • Pycom Products
  • Getting Started
    • Introduction
    • Hardware Setup
      • LoPy
      • LoPy 4
      • SiPy
      • GPy
      • FiPy
      • WiPy
    • Software
      • Drivers
      • Updating Firmware
      • Pymakr
    • Programming the modules
      • Introduction to MicroPython
      • MicroPython Examples
      • Your first Pymakr project
      • REPL
        • Serial USB (UART)
        • Telnet REPL
      • FTP
      • Safe boot
    • Device Registration
      • Sigfox
      • Cellular
      • LoRaWAN
        • The Things Network
        • Objenious
  • Pymakr Plugin
    • Installation
      • Atom
      • Visual Studio Code
    • Tools/Features
    • Settings
  • Pytrack, Pysense, Pyscan
    • Introduction
    • Installing Software
      • Updating Firmware
      • Installing Drivers - Windows 7
      • Installing Libraries
    • API Reference
      • Pytrack
      • Pysense
      • Pyscan
      • Sleep
  • Tutorials & Examples
    • Introduction
    • All Pycom Device Examples
      • REPL
      • WLAN
      • Bluetooth
      • HTTPS
      • MQTT
      • AWS
      • ADC
      • I2C
      • Onewire Driver
      • Threading
      • RGB LED
      • Timers
      • PIR Sensor
      • Modbus
      • OTA update
      • RMT
      • Socket
      • Touch
    • LoRa Examples
      • LoRa-MAC (Raw LoRa)
      • LoRaWAN with OTAA
      • LoRaWAN with ABP
      • LoRa-MAC Nano-Gateway
      • LoPy to LoPy
      • LoRaWAN Nano-Gateway
      • RN2483 to LoPy
      • LoRa Mesh
      • PyMesh Border Router
    • Sigfox Examples
    • LTE Examples
      • CAT-M1
      • NB-IoT
      • Module IMEI
      • Modem Firmware Update
    • Pytrack Examples
    • Pysense Examples
    • Pyscan Examples
  • Firmware & API Reference
    • Introduction
    • Pycom Modules
      • machine
        • ADC
        • DAC
        • I2C
        • Pin
        • PWM
        • RTC
        • SPI
        • UART
        • WDT
        • Timer
        • SD
        • CAN
        • RMT
      • network
        • WLAN
        • Server
        • Bluetooth
          • GATT
          • GATTCConnection
          • GATTCService
          • GATTCCharacteristic
          • GATTSService
          • GATTSCharacteristic
        • LoRa
          • Pymesh
        • Sigfox
        • LTE
      • AES
      • pycom
    • MicroPython Modules
      • micropython
      • uctypes
      • sys
      • uos
      • array
      • cmath
      • math
      • gc
      • ubinascii
      • ujson
      • ure
      • usocket
      • select
      • utime
      • uhashlib
      • ussl
      • ucrypto
      • ustruct
        • uzlib
      • _thread
      • Builtin
    • Notes
  • Product Info, Datasheets
    • Introduction
    • Development Modules
      • WiPy 2.0
      • WiPy 3.0
      • LoPy
      • LoPy 4
      • SiPy
      • GPy
      • FiPy
    • OEM Modules
      • W01
      • L01
      • L04
      • G01
      • L01 OEM Baseboard Reference
      • Universal OEM Baseboard Reference
    • Expansion Boards and Shields
      • Expansion Board 3.0
      • Pytrack
      • Pysense
      • Pyscan
      • Expansion Board 2.0
      • Deep Sleep Shield
        • Deep Sleep API
    • Notes
  • Pybytes
    • Introduction
    • Getting Started with Pybytes
    • Add a device to Pybytes
      • Connect to Pybytes: Quick Add
      • Connect to Pybytes: Flash Pybytes library manually
      • Add Sigfox device
        • DevKit contract
        • Custom contract
    • Visualise data from your device
    • Integrations
      • Amazon IoT
  • Documentation Notes
    • Introduction
    • Syntax
    • REPL vs Scripts
    • Mesh Networks
  • Advanced Topics
    • Firmware Downgrade
    • CLI Updater
    • SecureBoot and Encryption
    • License
  • Have a question?
    • Ask on the Forum
Powered by GitBook
On this page
  • Getting Started with AWS IoT
  • Creating the message broker (Amazon website):
  • Setting up the device (Pycom device):
  • Configuration (config.py):
  • Subscibe / Publish (main.py)
  • Shadow updater (main.py)
  • Delta Listener (main.py)
  1. Tutorials & Examples
  2. All Pycom Device Examples

AWS

PreviousMQTTNextADC

Last updated 6 years ago

The AWS IoT platform enables devices to connect to the Amazon cloud and lets applications in the cloud interact with Internet-connected things. Common IoT applications either collect and process telemetry from devices or enable users to control a device remotely. Things report their state by publishing messages, in JSON format, on MQTT topics.

For more information see this .

Getting Started with AWS IoT

Creating the message broker (Amazon website):

  • Sign in to the

  • Navigate to the IoT Console by clicking on the

  • In the left navigation pane, choose

  • Click on the create button, give your

  • Click on the device that has been created

  • On the Details page, in the left navigation pane, choose

  • On the Certificates page, choose Create certificate

  • Download all the certificates, then press the Activate and the Attach a Policy buttons.

  • Click on the Create New Policy button

  • On the page, choose a policy name and the actions to authorise.

  • Go to the certificates page, click on the three dots of your certificate and attach the policy to the certificate as shown in the

Setting up the device (Pycom device):

  • Connect to the device via FTP and put the root CA certificate, the client certificate (*.pem.crt) and the private key (*.private.pem.key) in the /flash/cert folder.

  • Put the config.py and the main.py in the device flash

Configuration (config.py):

This file contains the WiFi, certificate paths and application specific settings that need to be updated by the user.

# WiFi configuration
WIFI_SSID = 'my_wifi_ssid'
WIFI_PASS = 'my_wifi_password'

# AWS general configuration
AWS_PORT = 8883
AWS_HOST = 'aws_host_url'
AWS_ROOT_CA = '/flash/cert/aws_root.ca'
AWS_CLIENT_CERT = '/flash/cert/aws_client.cert'
AWS_PRIVATE_KEY = '/flash/cert/aws_private.key'

################## Subscribe / Publish client #################
CLIENT_ID = 'PycomPublishClient'
TOPIC = 'PublishTopic'
OFFLINE_QUEUE_SIZE = -1
DRAINING_FREQ = 2
CONN_DISCONN_TIMEOUT = 10
MQTT_OPER_TIMEOUT = 5
LAST_WILL_TOPIC = 'PublishTopic'
LAST_WILL_MSG = 'To All: Last will message'

####################### Shadow updater ########################
#THING_NAME = "my thing name"
#CLIENT_ID = "ShadowUpdater"
#CONN_DISCONN_TIMEOUT = 10
#MQTT_OPER_TIMEOUT = 5

####################### Delta Listener ########################
#THING_NAME = "my thing name"
#CLIENT_ID = "DeltaListener"
#CONN_DISCONN_TIMEOUT = 10
#MQTT_OPER_TIMEOUT = 5

####################### Shadow Echo ########################
#THING_NAME = "my thing name"
#CLIENT_ID = "ShadowEcho"
#CONN_DISCONN_TIMEOUT = 10
#MQTT_OPER_TIMEOUT = 5

Subscibe / Publish (main.py)

To subscribe to a topic:

  • Go to the AWS Iot page, click on manage and choose your device

  • From the left hand side, choose Activity and then click MQTT client.

# user specified callback function
def customCallback(client, userdata, message):
    print("Received a new message: ")
    print(message.payload)
    print("from topic: ")
    print(message.topic)
    print("--------------\n\n")

# configure the MQTT client
pycomAwsMQTTClient = AWSIoTMQTTClient(config.CLIENT_ID)
pycomAwsMQTTClient.configureEndpoint(config.AWS_HOST, config.AWS_PORT)
pycomAwsMQTTClient.configureCredentials(config.AWS_ROOT_CA, config.AWS_PRIVATE_KEY, config.AWS_CLIENT_CERT)

pycomAwsMQTTClient.configureOfflinePublishQueueing(config.OFFLINE_QUEUE_SIZE)
pycomAwsMQTTClient.configureDrainingFrequency(config.DRAINING_FREQ)
pycomAwsMQTTClient.configureConnectDisconnectTimeout(config.CONN_DISCONN_TIMEOUT)
pycomAwsMQTTClient.configureMQTTOperationTimeout(config.MQTT_OPER_TIMEOUT)
pycomAwsMQTTClient.configureLastWill(config.LAST_WILL_TOPIC, config.LAST_WILL_MSG, 1)

#Connect to MQTT Host
if pycomAwsMQTTClient.connect():
    print('AWS connection succeeded')

# Subscribe to topic
pycomAwsMQTTClient.subscribe(config.TOPIC, 1, customCallback)
time.sleep(2)

# Send message to host
loopCount = 0
while loopCount < 8:
    pycomAwsMQTTClient.publish(config.TOPIC, "New Message " + str(loopCount), 1)
    loopCount += 1
    time.sleep(5.0)

Shadow updater (main.py)

# user specified callback functions
def customShadowCallback_Update(payload, responseStatus, token):
    if responseStatus == "timeout":
        print("Update request " + token + " time out!")
    if responseStatus == "accepted":
        payloadDict = json.loads(payload)
        print("Update request with token: " + token + " accepted!")
        print("property: " + str(payloadDict["state"]["desired"]["property"]))
    if responseStatus == "rejected":
        print("Update request " + token + " rejected!")

def customShadowCallback_Delete(payload, responseStatus, token):
    if responseStatus == "timeout":
        print("Delete request " + token + " time out!")
    if responseStatus == "accepted":
        print("Delete request with token: " + token + " accepted!")
    if responseStatus == "rejected":
        print("Delete request " + token + " rejected!")

# configure the MQTT client
pycomAwsMQTTShadowClient = AWSIoTMQTTShadowClient(config.CLIENT_ID)
pycomAwsMQTTShadowClient.configureEndpoint(config.AWS_HOST, config.AWS_PORT)
pycomAwsMQTTShadowClient.configureCredentials(config.AWS_ROOT_CA, config.AWS_PRIVATE_KEY, config.AWS_CLIENT_CERT)

pycomAwsMQTTShadowClient.configureConnectDisconnectTimeout(config.CONN_DISCONN_TIMEOUT)
pycomAwsMQTTShadowClient.configureMQTTOperationTimeout(config.MQTT_OPER_TIMEOUT)

# Connect to MQTT Host
if pycomAwsMQTTShadowClient.connect():
    print('AWS connection succeeded')

deviceShadowHandler = pycomAwsMQTTShadowClient.createShadowHandlerWithName(config.THING_NAME, True)

# Delete shadow JSON doc
deviceShadowHandler.shadowDelete(customShadowCallback_Delete, 5)

# Update shadow in a loop
loopCount = 0
while True:
    JSONPayload = '{"state":{"desired":{"property":' + str(loopCount) + '}}}'
    deviceShadowHandler.shadowUpdate(JSONPayload, customShadowCallback_Update, 5)
    loopCount += 1
    time.sleep(5)

Delta Listener (main.py)

# Custom Shadow callback
def customShadowCallback_Delta(payload, responseStatus, token):
    payloadDict = json.loads(payload)
    print("property: " + str(payloadDict["state"]["property"]))
    print("version: " + str(payloadDict["version"]))

    # configure the MQTT client
pycomAwsMQTTShadowClient = AWSIoTMQTTShadowClient(config.CLIENT_ID)
pycomAwsMQTTShadowClient.configureEndpoint(config.AWS_HOST, config.AWS_PORT)
pycomAwsMQTTShadowClient.configureCredentials(config.AWS_ROOT_CA, config.AWS_PRIVATE_KEY, config.AWS_CLIENT_CERT)

pycomAwsMQTTShadowClient.configureConnectDisconnectTimeout(config.CONN_DISCONN_TIMEOUT)
pycomAwsMQTTShadowClient.configureMQTTOperationTimeout(config.MQTT_OPER_TIMEOUT)

# Connect to MQTT Host
if pycomAwsMQTTShadowClient.connect():
    print('AWS connection succeeded')

deviceShadowHandler = pycomAwsMQTTShadowClient.createShadowHandlerWithName(config.THING_NAME, True)

# Listen on deltas
deviceShadowHandler.shadowRegisterDeltaCallback(customShadowCallback_Delta)

# Loop forever
while True:
    time.sleep(1)

Download the latest sample code from the Pycom .

Update the config file with your WiFi settings, the and the certificate paths.

Choose the you entered in the configuration file.

Messages should be published as shown in the

PDF File
AWS Management Console
AWS IoT link
Register/Manage
device a name and press create
Security
See image
Create Policy
diagram
GitHub Repository
AWS Host
topic name
diagram