c.set_callback(sub_cb) # Connect to server, requesting not to clean session for this # client. If there was no existing session (False return value # from connect() method), we perform the initial setup of client # session - subscribe to needed topics. Afterwards, these # subscriptions will be stored server-side, and will be persistent, # (as we use clean_session=False). # # There can be a problem when a session for a given client exists, # but doesn't have subscriptions a particular application expects. # In this case, a session needs to be cleaned first. See # example_reset_session.py for an obvious way how to do that. # # In an actual application, it's up to its developer how to # manage these issues. One extreme is to have external "provisioning" # phase, where initial session setup, and any further management of # a session, is done by external tools. This allows to save resources # on a small embedded device. Another extreme is to have an application # to perform auto-setup (e.g., clean session, then re-create session # on each restart). This example shows mid-line between these 2 # approaches, where initial setup of session is done by application, # but if anything goes wrong, there's an external tool to clean session. if not c.connect(clean_session=False): print("New session being set up") c.subscribe(b"foo_topic") while 1: c.wait_msg() c.disconnect()
if ap_if.active(): ap_if.active(False) CLIENT_ID = ubinascii.hexlify(machine.unique_id()) c = MQTTClient(client_id=CLIENT_ID, server=config['mqtt']['server'], user=config['mqtt']['user'], password=config['mqtt']['password'], port=config['mqtt']['port'], ssl=config['mqtt']['ssl']) c.connect() topic_prefix = config['mqtt']['topic_prefix'] adc = ADC(0) def publish(c, k, v): c.publish(topic_prefix + k, str(v), True) while True: light = adc.read() print('Light: %s' % light) publish(c, "light", light) time.sleep_ms(1000) c.disconnect()
def Emit(self): emi = MQTTClient('emiter', "192.168.110.51") emi.connect() emi.publish("test/msg", "from nodeMCU !") emi.disconnect()
# Advertencia: una conexión segura usa aproximadamente 9k bytes de la pila # (aproximadamente 1/4 de la pila de micropython en la plataforma ESPXX) MQTT_URL = b'galiot.galileo.edu' MQTT_USER = b'node' #cambiar el node MQTT_TOPIC = b'rgb' client = MQTTClient(client_id=mqtt_client_id, server=MQTT_URL, ssl=False) print('conectado al servidor MQTT') try: client.connect() except Exception as e: print('no se pudo conectar al servidor MQTT {}{}'.format( type(e).__name__, e)) sys.exit() mqtt_feedname = bytes('/{:s}/{:s}'.format(MQTT_USER, MQTT_TOPIC), 'utf-8') client.set_callback(cb) client.subscribe(mqtt_feedname) # espere hasta que se hayan publicado los datos en la fuente IO de Adafruit while True: try: client.wait_msg() except KeyboardInterrupt: print('Ctrl-C pressed...exiting') client.disconnect() sys.exit()