Welcome to the Pycom forum Forum
    • \[\[global:header.categories\]\]
    • \[\[global:header.recent\]\]
    • \[\[global:header.tags\]\]
    • \[\[global:header.popular\]\]
    • Login

    Explore Pybytes | Official Documentation | Report a Firmware Bug/Issue | GitHub

    Improve stability on connection with AWS

    Scheduled Pinned Locked Moved FiPy
    fipyaws iotawsstabilityconnect issues
    1 Posts 1 Posters 33 Views 1 Watching
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • N Offline
      nervencid
      last edited by nervencid

      Hello and sorry for the english:

      I'm trying to use AWS IOT with Python i i'm implementing mqtt client:

      #Importamos los modulos de sistema
      from MQTTLib import AWSIoTMQTTClient
      import gc
      import machine
      from machine import Pin, SD
      import time
      import pycom
      import os
      import sys
      
      #Informacion de sistema
      print(os.uname())
      
      #Recoleccion de basura automatica
      gc.enable()
      
      #Deshabilitamos el LED azul que se activa al inicio
      pycom.heartbeat(False)
      
      ############################################CONFIGURACION DEL WIFI####################################################
      
      #Importamos el modulo personalizado de conexion de wifi
      import connectwifi as cw
      
      #mensaje de inicio
      print('Starting ...')
      #Conectamos al wiFi y pasamos las credenciales
      cw.connect("*****", "*****")
      
      ###############################################CONFIGURACION DE AWS###################################################
      
      #Configuramos el puerto para MQTT cifrado
      AWS_PORT = 8883
      
      #Definimos el 'endpoint' esto es proporcionado por AMAZON
      AWS_HOST = "*****.amazonaws.com"
      
      #Definimos la ubicacion de los certificados, estos tambien son proporcionados por Amazon
      #IMPORTANTE: los nombres de las carpetas DEBEN ser esctrictos para que la
      AWS_ROOT_CA = "/flash/cert/*****.pem"
      AWS_CLIENT_CERT = "/flash/cert/*****.cert.pem"
      AWS_PRIVATE_KEY = "/flash/cert/*****.key"
      
      #Definimos la identificacion del cliente, DEBE SER LA MISMA que la configurada en Amazon
      #Para conexion basada en certificados
      myMQTTClient = AWSIoTMQTTClient("Pycom-client")
      #Para conexion basada en Websockets
      # myMQTTClient = AWSIoTMQTTClient("Pycom-client", useWebsocket=True)
      
      #Configuramos las credenciales
      #Para autenticazion mutua en TLS
      myMQTTClient.configureEndpoint(AWS_HOST, 8883)
      #Para Websockets
      # myShadowClient.configureEndpoint(AWS_HOST, 443)
      #myMQTTClient.configureCredentials(AWS_ROOT_CA, AWS_PRIVATE_KEY, AWS_CLIENT_CERT)
      myMQTTClient.configureCredentials(AWS_ROOT_CA, AWS_PRIVATE_KEY, AWS_CLIENT_CERT)
      
      #Para Websockets solo necesitamos el certificado CA
      #myMQTTClient.configureCredentials(AWS_ROOT_CA)
      
      #Configuraciones adicionales obligatorias
      myMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
      myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
      myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
      myMQTTClient.configureMQTTOperationTimeout(50)  # 5 sec
      
      ##########################################################################################################################
      
      #Especificamos un 'callback' que se ejecutara cada vez que se reciba un mensaje del servidor
      def customCallback(client, userdata, message):
      	print("Mensaje recibido: ")
      	print(message.payload)
      	print("Desde el tema: ")
      	print(message.topic)
      	print("--------------\n\n")
      
      #Creamos un dato para enviar
      dataToSend = "Hola AWS, soy la Pycom!!!"
      
      #Nos suscribimos a un tema para recibir mensajes del servidor
      myMQTTClient.subscribe("topic_2", 1, customCallback)
      
      #Ciclo principal
      while True:
      
          #Nos suscribimos a un tema para recibir mensajes del servidor
          myMQTTClient.subscribe("topic_2", 1, customCallback)
      
          #Corremos el recolector de basura
          gc.collect()
      
          #En cada ciclo tratamos de hacer la conexion y reiniciamos cuando se rompa
          try:
      
              #Conectamos
              myMQTTClient.connect()
      
              #Mensaje de conexion exitosa
              if myMQTTClient.connect():
                  print('AWS connection succeeded')
      
              #Publicamos en continuo notificaciones al servidor
              print("Enviando un dato: ", dataToSend)
              myMQTTClient.publish("topic_1", dataToSend, 0)
      
              #Desconectamos
              myMQTTClient.disconnect()
      
          except OSError as error:
      
              #En caso de error forzamos la reconexion
              print('Error en la conexion: {0} \n Intentanto reconectar...'.format(error))
              machine.reset()
      
      

      However the connection still is very Instability, i receive a timeout or server rejection messages very often, I can send a couple of meessages and receive some others but is difficult to receive messages via subscription and i don't if i should use additional code in order to improve, i don't know if i must use additional code in order to improve.

      Thank you and sorry for the English

      1 Reply Last reply Reply Quote 0

      Hello! It looks like you're interested in this conversation, but you don't have an account yet.

      Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.

      With your input, this post could be even better 💗

      Register Login
      • 1 / 1
      • First post
        Last post

      Pycom on Twitter

      Pycom