I have been working on Pi Pico w board that connects to AWS Iot core using MQTT protocol and my code is working fine when run on IDLE. But the problem is when i save my file as main.py and trying to run it just connecting to internet source . It is unable to establish a MQTT connection .I have also checked the internet connection it is fine and I also placed all the files like private key , cerficate and CA1 file in pi pico w board itself. But I couldn't understand wha'ts the problem is!! This is my code: In this code i just want to place a randomly generated number in the AWS Iot Core.If it works i will continue with the actual implementation of my project.
import wifimgr #This is another python file that takes care of internet connection
import machine
import gc
import network
import ssl
import time
import ubinascii
from machine import Pin, time_pulse_us
import utime as time_t
from simple import MQTTClient
#import config
from random import random
try:
import usocket as socket
except:
import socket
led = machine.Pin('LED', machine.Pin.OUT)
wlan = wifimgr.get_connection()
if wlan is None:
print("Could not initialize the network connection.")
while True:
pass
led.on()
def blink_led():
led.off()
time.sleep(0.2)
led.on()
time.sleep(0.2)
print("Raspberry Pi Pico W OK")
MQTT_CLIENT_ID = ubinascii.hexlify(machine.unique_id())
#PLEASE NOTE THAT ALL FOLLOWING FILES ARE CORRECTLY NAMED IN MY CODE , I HAVE JUST MODIFIED THEM DUE TO PRIVACY CONCERNS
MQTT_CLIENT_KEY = "private.pem.key"
MQTT_CLIENT_CERT = "certificate.pem.crt"
MQTT_BROKER = "endpoint"
MQTT_BROKER_CA = "AmazonRootCA1.pem"
def read_pem(file):
with open(file, "r") as input:
text = input.read().strip()
split_text = text.split("\n")
base64_text = "".join(split_text[1:-1])
return ubinascii.a2b_base64(base64_text)
key = read_pem(MQTT_CLIENT_KEY)
cert = read_pem(MQTT_CLIENT_CERT)
ca = read_pem(MQTT_BROKER_CA)
mqtt_client = MQTTClient(
MQTT_CLIENT_ID,
MQTT_BROKER,
keepalive=60,
ssl=True,
ssl_params={
"key": key,
"cert": cert,
"server_hostname": MQTT_BROKER,
"cert_reqs": ssl.CERT_REQUIRED,
"cadata": ca,
},
)
print(f"Connecting to MQTT broker")
blink_led()
mqtt_client.connect()
blink_led()
# Publishing part
while True:
blink_led()
distance_cm = int(random()*100)
print(distance_cm)
try:
topic = "distance"
payload = str(distance_cm)
mqtt_client.publish(topic, payload)
print(f"Published to {topic}: {payload}")
blink_led()
except Exception as e:
print(f"Error publishing to MQTT: {e}")
I am trying to run my make a MQTT connection with my AWS IOT core so that I don't need any idle and can run it by just connecting my pi pico w to a power source. NOTE:I ALREADY SAVED MY PROGRAM AS main.py