MQTT with ESP8266 and Micropython

Hi, good morning…

I need help to send data from ESP8266 to Losant using Micropython. Could you send me a code example? I can connect in Losant but con not send the data…
Below my code:

topic = “losant/” + CHANNEL_ID + “/state”
payload = { “data” : { “Temperatura” : 34 } }

Connect Wi-Fi, this function work well

do_connect()

client = MQTTClient(CHANNEL_ID,SERVER,1883,WRITE_API_KEY,API_KEY_PASS)

print(‘connect server…’)
client.connect() # In the Losant show me connect, okey

I tried two method tho send data and not work

#client.publish(’/sala01/Temperatura’ , ‘55’)
client.publish( topic, payload)

time.sleep(30)
client.disconnect()

2021-01-25_08h42_22

Hi @Marcelo_Bohrer,

Can you tell me which MicroPython library you’re using for MQTT in this project?

Thank you,
Heath

Hi,

Well, I am novice in Micropython… You refer this lib below

import network
import time
import random
import dht
from umqtt.simple import MQTTClient
from machine import Pin

Hi,

Does not work. I can connect at Losant but I can not send or publish the payload.

Hey @Marcelo_Bohrer ,

Could you post the full contents of your script? ( removing keys or other confidential information )

That way, we can take a look at how you’re attempting to publish/subscribe and offer some advice.

import network
import time
import random
from umqtt.simple import MQTTClient

 
WiFi_SSID = "...."
WiFi_PASS = "..."

SERVER = "broker.losant.com"

CHANNEL_ID    = "..."
WRITE_API_KEY = "..."
API_KEY_PASS  = '...'


topic = "losant/" + CHANNEL_ID + "/state"


#
# Define payload, just a example
#
payload = { "Temperatura": 34  } 
 

def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    print('is connected? ', wlan.isconnected())
    if not wlan.isconnected():
       print('connecting to network...')
       wlan.connect(WiFi_SSID, WiFi_PASS)
       print('is connected? ', wlan.isconnected())
       
       while not wlan.isconnected():
          pass
          print('network config:', wlan.ifconfig())   


#
# Connect Wi-Fi, OK
#

do_connect()



client = MQTTClient(CHANNEL_ID,SERVER,1883,WRITE_API_KEY,API_KEY_PASS)

print('connect server ok ...')

#
# Until here work well. I can connect at Losant
#

client.connect()



# I did this command and no way
#client.publish('/sala01/Temperatura' , '55') 


#
# Here is my problem... I can not send data, I don't know what I am doing wrong.
#
client.publish( topic, payload)

time.sleep(30)

# After time disconnect ok
client.disconnect()

    
print('Fim...The End...')

Hi,

I am using this…

from umqtt.simple import MQTTClient

@Marcelo_Bohrer,

In your Losant Application, in the overview section, you have your Application Log on the right side. When a device connects and reports will be information there, and if there is an issue, errors will be displayed there. It will look something like this:

image

What do you see in your application log when this script runs?

Thank you,
Heath