fizista / micropython-umqtt.robust2

MIT License
49 stars 7 forks source link

Unable to Publish message to AWS IoT Cloud #11

Closed vivekmystrey closed 1 year ago

vivekmystrey commented 2 years ago

With umqtt.robust2 is unable to publish messages to AWS IoT Cloud and there is no error too, while with umqtt.robust it works properly.

Have used micropython version - v.1.19 and his error is common with both ESP32-C3 and ESP32-S3.

FYI, have created flash directory in the root folder and copied AWS IoT device - certificate, private key, public key and policy file in it.

And, below is my code snippet:

#AWS MQTT client cert example for esp8266 or esp32 running MicroPython 1.9
from umqtt.robust2 import MQTTClient
import time
import network
from time import sleep
import usocket as socket
import ujson

#Certs for ESP8266
CERT_FILE = "/flash/ESP32-Core.cert.pem"
KEY_FILE = "/flash/ESP32-Core.private.key"

#if you change the ClientId make sure update AWS policy
MQTT_CLIENT_ID = "basicPubSub"
MQTT_PORT = 8883

MQTT_KEEPALIVE_INTERVAL = 45
THING_NAME = "ESP32-Core1"
SHADOW_GET_TOPIC = "$aws/things/" + THING_NAME + "/shadow/get"
#SHADOW_UPDATE_TOPIC = "$aws/things/" + THING_NAME + "/shadow/update"
SHADOW_UPDATE_TOPIC = "/sdk/test/Python"

RESPONSE_RECEIVED = False

#if you change the topic make sure update AWS policy
MQTT_TOPIC = "esp8266-topic"

#Change the following three settings to match your environment
MQTT_HOST = "***********-ats.iot.us-east-1.amazonaws.com"
WIFI_SSID = "**********"
WIFI_PW = "**************"

mqtt_client = None

def connect_mqtt():
    try:
        with open(KEY_FILE, "r") as f:
            key = f.read()

        print("MQTT received KEY")

        with open(CERT_FILE, "r") as f:
            cert = f.read()

        print("MQTT received CERTIFICATE")

        mqtt_client = MQTTClient(client_id=MQTT_CLIENT_ID, server=MQTT_HOST, port=MQTT_PORT, keepalive=5000, ssl=True, ssl_params={"cert":cert, "key":key, "server_side":False})
        mqtt_client.connect()
        mqtt_client.set_callback(sub_cb)
        print("MQTT is connected")
        while True:
            print("Publish Message")
            a = {"message": "Hello from IoT console"}
            mqtt_client.publish(SHADOW_UPDATE_TOPIC, ujson.dumps(a))
            print("Message Published")
            mqtt_client.wait_msg()

    except Exception as e:
        print('Cannot connect to MQTT ' + str(e))
        raise

def connect_wifi(ssid, pw):
    wlan = network.WLAN(network.STA_IF)

    if(wlan.isconnected()):
        wlan.disconnect()
    nets = wlan.scan()

    if not wlan.isconnected():

        wlan.active(True)
        wlan.connect(WIFI_SSID, WIFI_PW)
        while not wlan.isconnected():
            pass
    print("Connected as:", wlan.ifconfig())

try:
    print("Connecting to WIFI...")
    connect_wifi(WIFI_SSID, WIFI_PW)
    print("Connecting to MQTT...")
    connect_mqtt()
    print("OK")

except Exception as e:
    print(str(e))
fizista commented 2 years ago

See an example of using this library: https://github.com/fizista/micropython-umqtt.robust2/blob/master/example_sub_robust.py

There it is shown how to operate it without wait_msg(). I should probably remove this method completely.

vivekmystrey commented 2 years ago

Thanks for the update. I don't see any reference for publish messages in the above reference. Have retried by following the script and still have the same issue:


#AWS MQTT client cert example for esp8266 or esp32 running MicroPython 1.9
from umqtt.robust2 import MQTTClient
import time
import network
import machine
from machine import Pin, ADC
from time import sleep
import usocket as socket
import ujson

#Certs for ESP8266
CERT_FILE = "/flash/ESP32-Core.cert.pem"
KEY_FILE = "/flash/ESP32-Core.private.key"

#if you change the ClientId make sure update AWS policy
MQTT_CLIENT_ID = "basicPubSub"
MQTT_PORT = 8883

MQTT_KEEPALIVE_INTERVAL = 45
THING_NAME = "ESP32-Core1"
SHADOW_UPDATE_TOPIC = "/sdk/test/Python"

RESPONSE_RECEIVED = False

#if you change the topic make sure update AWS policy
MQTT_TOPIC = "esp8266-topic"

#Change the following three settings to match your environment
MQTT_HOST = "*******************-ats.iot.us-east-1.amazonaws.com"
WIFI_SSID = "*************"
WIFI_PW = "************"

mqtt_client = None

def sub_cb(topic, msg, retained, duplicate):
    print((topic, msg, retained, duplicate))

def connect_mqtt():
    try:
        with open(KEY_FILE, "r") as f:
            key = f.read()

        print("MQTT received KEY")

        with open(CERT_FILE, "r") as f:
            cert = f.read()

        print("MQTT received CERTIFICATE")

        mqtt_client = MQTTClient(client_id=MQTT_CLIENT_ID, server=MQTT_HOST, port=MQTT_PORT, keepalive=5000, ssl=True, ssl_params={"cert":cert, "key":key, "server_side":False})
        mqtt_client.connect()
        mqtt_client.set_callback(sub_cb)
        print("MQTT is connected")
        a = {"message": "Hello from IoT console"}
        try:
            mqtt_client.publish(SHADOW_UPDATE_TOPIC, ujson.dumps(a))
            print("Publish Message")
        except Exception as e:
            print('Cannot Publish' + str(e))

    except Exception as e:
        print('Cannot connect to MQTT ' + str(e))
        raise

def connect_wifi(ssid, pw):
    wlan = network.WLAN(network.STA_IF)

    if(wlan.isconnected()):
        wlan.disconnect()
    nets = wlan.scan()

    if not wlan.isconnected():

        wlan.active(True)
        wlan.connect(WIFI_SSID, WIFI_PW)
        while not wlan.isconnected():
            pass
    print("Connected as:", wlan.ifconfig())

try:
    print("Connecting to WIFI...")
    connect_wifi(WIFI_SSID, WIFI_PW)
    print("Connecting to MQTT...")
    connect_mqtt()
    print("OK")

except Exception as e:
    print(str(e))

And, below is the output of the script:

.

>>> %Run -c $EDITOR_CONTENT
Connecting to WIFI...
Connected as: ('192.***.*.*', '255.255.255.0', '192.***.*.*', '192.***.*.*')
Connecting to MQTT...
MQTT received KEY
MQTT received CERTIFICATE
MQTT is connected
Publish Message
OK

The publish event is successful, however, still don't see the message in AWS. Please advise, what is wrong here? Why the publish event is successful when the message is not sent?

vivekmystrey commented 2 years ago
image
vivekmystrey commented 2 years ago

Above is the snippet of ESP32-S3 filesystem

vivekmystrey commented 2 years ago

Have, added a line before the message publish

print("Connection Ping", mqtt_client.is_conn_issue())

And, got the following error:

MQTT (connect): MQTTException(1,)

And, sure why the connection is closed?

fizista commented 2 years ago

Why was the connection to the server closed? For example, the data did not reach the server.

You also send data with the parameter qos=0, and this means no guarantee of packet delivery. The packet sent, but whether it arrived, you do not know.

You are not using the full capabilities of the library (see the example code), so the library will not try to connect again.

Change the library settings to code debug mode:

mqtt_client.DEBUG=1

then you will know more.

fizista commented 2 years ago

Also, I don't see the main.py script. If your code is running from boot.py then it might affect the program.

fizista commented 1 year ago

There is a new version of umqtt-simple2=v2.2.0.

Probably the problems have been fixed in this library, please let us know if they still occur.