I'm using Loboris port on my ESP32 Wroom module (bare module) and I'm trying to connect to ThingSpeak - but after editing sample from wiki (Loboris one) - I'm getting only "Not connected" status.
My module is already connected to local wifi and have internet connectivity; passwords, channel name etc are correct - double checked all of that.
Any ideas what I'm doing wrong? Anyone have some experience with ThingSpeak MQTT and could share some working example?
My code:
Code: Select all
My_MQTT_API_Key = 'XXXXX'
My_Channel_ID = 'XXXXX'
My_Write_API_Key = 'XXXXX'
import network
import utime
def datacb(msg):
print("[{}] Data arrived from topic: {}, Message:\n".format(msg[0], msg[1]), msg[2])
thing = network.mqtt("thingspeak", "mqtt://mqtt.thingspeak.com", user="ESP32tst", password=My_MQTT_API_Key, cleansession=True, data_cb=datacb)
# or secure connection
#thing = network.mqtt("thingspeak", "mqtts://mqtt.thingspeak.com", user="anyName", password="ThingSpeakMQTTid", cleansession=True, data_cb=datacb)
thingspeakChannelId = My_Channel_ID # enter Thingspeak Channel ID
thingspeakChannelWriteApiKey = My_Write_API_Key # EDIT - enter Thingspeak Write API Key
thingspeakFieldNo = 1
thingSpeakChanelFormat = "json"
pubchan = "channels/{:s}/publish/{:s}".format(thingspeakChannelId, thingspeakChannelWriteApiKey)
pubfield = "channels/{:s}/publish/fields/field{}/{:s}".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey)
subchan = "channels/{:s}/subscribe/{:s}/{:s}".format(thingspeakChannelId, thingSpeakChanelFormat, thingspeakChannelWriteApiKey)
subfield = "channels/{:s}/subscribe/fields/field{}/{:s}".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey)
thing.start()
tmo = 0
while thing.status()[0] != 2:
utime.sleep_ms(100)
tmo += 1
if tmo > 80:
print("Not connected")
break
# subscribe to field
thing.subscribe(subfield)
# publish to channel
# Payload can include any of those fields separated b< ';':
# "field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value"
thing.publish(pubchan, "field1=25.2;status=On line")
# Publish to field
thing.publish(pubfield, "24.5")