← index #915Issue #218
Related · medium · value 1.831
QUERY · ISSUE

cannot connect to aws iot using umqtt.simple

openby Saranya-karanopened 2024-08-26updated 2024-09-23

My code

import time
import machine
import network
import ujson
from simple1 import MQTTClient

SSID = b'Exxxye'
PASS = b'8xxx766'
CLIENT_ID = b'ixxxxxxxxxxxx6eb63'
AWS_ENDPOINT = b'xxxxx-1.amazonaws.com'

PUB_TOPIC = b'temperature'
SUB_TOPIC = b'temperature'
with open('/pri.der', 'rb') as f:
    DEV_KEY = f.read()

with open('/cert.der', 'rb') as f:
    DEV_CRT = f.read()

light = machine.Pin("LED", machine.Pin.OUT)
light.off()


def wifi_connect():
    print('Connecting to wifi...')
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(SSID, PASS)
    while wlan.isconnected() == False:
        light.on()
        print('Waiting for connection...')
        time.sleep(0.5)
        light.off()
        time.sleep(0.5)
    print('Connection details: %s' % str(wlan.ifconfig()))

def mqtt_subscribe_callback(topic, msg):
    print("Received topic: %s message: %s" % (topic, msg))
    if topic == SUB_TOPIC:
        mesg = ujson.loads(msg)
        if 'state' in mesg.keys():
            if mesg['state'] == 'on' or mesg['state'] == 'ON' or mesg['state'] == 'On':
                light.on()
                print('Light is ON')
            else:
                light.off()
                print('Light is OFF')

def get_rpi_temperature():
    sensor = machine.ADC(4)
    voltage = sensor.read_u16() * (3.3 / 65535)
    temperature = 27 - (voltage - 0.706) / 0.001721
    return temperature


wifi_connect()


mqtt = MQTTClient(
    client_id=CLIENT_ID,
    server=AWS_ENDPOINT,
    port=8883,
    keepalive=120,
    ssl=True,
    ssl_params={'key':DEV_KEY, 'cert':DEV_CRT, 'server_side':False})

mqtt.connect()

mqtt.set_callback(mqtt_subscribe_callback)


mqtt.subscribe(SUB_TOPIC)

while True:
message = b'{"temperature":%s, "temperature_unit":"Degrees Celsius"}' % get_rpi_temperature()
    print('Publishing topic %s message %s' % (PUB_TOPIC, message))

    mqtt.publish(topic=PUB_TOPIC, msg=message, qos=1)

    # Check subscriptions for message
    mqtt.check_msg()
    time.sleep(5)

My error code:

Connecting to wifi...
Connection details: ('192.168.x.xx', '255.255.255.0', '192.168.xx.xx', '192.168.xx.xx')
dbug-msg: 0x9 b'04:4d:51:54:54:04:02:00:78'
dbug-resp: b''
Traceback (most recent call last):
File "<stdin>", line 81, in <module>
File "simple1.py", line 92, in connect
IndexError: bytes index out of range

please someone help me on this..i tried everything

2 comments
kllsamui · 2024-09-23

try first time MicroPython
MQTT TLS ( ssl=True)
and can not connect

env: MicroPython v1.23.0 on 2024-06-02; Raspberry Pi Pico W with RP2040
also test: MicroPython v1.24.0-preview.335.gb08ddbba5 on 2024-09-20; Raspberry Pi Pico W with RP2040

from umqtt.simple import MQTTClient # Metadata-Version: 2.1 Name: umqtt.simple Version: 1.4.0

error:
Traceback (most recent call last):
File "<stdin>", line 47, in <module>
File "/lib/umqtt/simple.py", line 68, in connect
AttributeError: 'bool' object has no attribute 'wrap_socket'

do i need a other /lib/ ?

kllsamui · 2024-09-23

no, a better code did it:
Screenshot 2024-09-23 214645

CANDIDATE · ISSUE

OSError: [Errno 103] ECONNABORTED

closedby Javier96Barreraopened 2017-10-11updated 2017-10-13

Hi, I'm quite new to micropython. I have flashed the 1.9.2 version on my Lolin v3 (Nodemcu 12e).
I load the code using ampy command, then open terminal with Putty, and reset the board. i get this error while trying to use the sentence "connect()":

Traceback (most recent call last):
File "main.py", line 44, in <module>
File "umqtt/simple.py", line 56, in connect
OSError: [Errno 103] ECONNABORTED

MicroPython v1.9.2-8-gbf8f45cf on 2017-08-23; ESP module with ESP8266

import time
import machine
import network
import gc
import dht
from umqtt.robust import MQTTClient

#DHT PIN
d = dht.DHT11(machine.Pin(14))
led = machine.Pin(16, machine.Pin.OUT)
gc.enable()


def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('SSID', 'PASSWORD')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())


for i in range(20):
    do_connect()
    thingspeakChannelId = "MyChannelID"  # Thingspeak Channel ID
    thingspeakChannelWriteapi = "MyWriteKey"  # Write API Key
    myMqttClient = "esp8266_mp"  
    thingspeakIoUrl = "mqtt.thingspeak.com"
    publishPeriodInSec = 15
    print("Control 1")
    c = MQTTClient(myMqttClient, thingspeakIoUrl, 1883)
    print("Control 2")
    d.measure()
    temp = d.temperature()
    humidity = d.humidity()
    print("Control 3")
    credentials = "channels/{:s}/publish/{:s}".format(thingspeakChannelId, thingspeakChannelWriteapi)
    print("Control 4")
    payload = "field1={:.1f}&field2={:.1f}\n".format(temp, humidity)
    print("Control 5")
    c.connect() #HERE
    print("Control 6")
    c.publish(credentials, payload)
    print("Control 7")
    for i in range(5):
        led.low()
        time.sleep(0.05)
        led.high()
        time.sleep(0.05)
    print("Sending data...", gc.mem_free())
    time.sleep(publishPeriodInSec)

    c.disconnect()
machine.reset()

Thanks for your time, if there is any problem regarding the information or post structure, tell me and I will try to fix it.

2 comments
dpgeorge · 2017-10-13

This github issue tracker is mainly for bug reports and code improvements. The report here is more of a problem using the libraries, and help in this area is best asked at https://forum.micropython.org. So please try to ask your question there (or maybe someone had the same issue and already fixed it).

Otherwise, the general thing to try is to verify you have internet connectivity, eg:

>>> import socket
>>> socket.getaddrinfo('micropython.org', 80)
Javier96Barrera · 2017-10-13

Thank you for the reply, I will move this question right now. PS: I checked and yes, i got internet connectivity. Reply: [(2, 1, 0, '', ('176.58.119.26', 80))]

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied