Re: Connecting to AWS with MQTT
Posted: Wed Jul 10, 2019 2:20 am
how you generate the certs files?
Please see the new forum at
https://forum.micropython.org/
Code: Select all
# certificate and private key
KEY_PATH = "/619e3d582c-private.pem.key"
CERT_PATH = "/619e3d582c-certificate.pem"
with open(KEY_PATH, 'r') as f:
PVT_KEY = f.read()
with open(CERT_PATH, 'r') as f:
CERT_KEY = f.read()
client = MQTTClient(client_id="esp32_micropython_shafik",
server="xxxxxxxxxxxxxxxx-ats.iot.eu-west-1.amazonaws.com",
port = 8883,
keepalive = 10000,
ssl = True,
ssl_params = {
"cert": CERT_KEY,
"key": PVT_KEY,
"server_side":False
} )
Code: Select all
from umqtt.robust import MQTTClient
import peripherals as prph
import sys
def broker_connect_aws():
# Certificates, keys and MQTT variables
certificate_file = "/xxxx1be767-certificate.pem.crt"
private_key_file = "/xxxx1be767-private.pem.key"
mqtt_client_id = "esp32"
mqtt_port = 8883
mqtt_topic = "ESP32_Temp_F"
mqtt_host = "xxxx80on2gc4gt-ats.iot.us-west-2.amazonaws.com" # Rest API Endpoint
# Open and read certificates and keys
with open(private_key_file, "r") as f:
private_key = f.read()
with open(certificate_file, "r") as f:
certificate = f.read()
# Set up MQTT client
mqtt_client = MQTTClient(client_id=mqtt_client_id,
server=mqtt_host,
port=mqtt_port,
keepalive=10000,
ssl=True,
ssl_params={"cert": certificate,
"key": private_key,
"server_side": False
})
# Connect to AWS IoT Broker and Publish
try:
print('try to connect to mqtt on aws')
mqtt_client.connect()
print('****PUBLISH TO AWS IoT****')
mqtt_client.publish(mqtt_topic, "{}F".format(str(prph.esp32_temp()))) # Read & Pub ESP32 internal temp
mqtt_client.disconnect() # <-- without this line the code connects and publishes but the message doesn't seem to be received
except Exception as e:
print('Could not connect to AWS IoT Broker {}{}'.format(type(e).__name__, e))
print('<<<Going to esp32 Deep Sleep mode>>>')
prph.esp32_dpslp(10)
sys.exit()