Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
mqtt mbox example
# An example of a mailbox client that wakes up every
# few seconds and checks for messages and then goes
# back to sleep.
#
# License: This code has been donated to the public domain
#
# Dov Grobgeld <dov.grobgeld@gmail.com>
# 2020-08-08 Sat
import paho.mqtt.client as mqtt #import the client1
import time
############
def on_message(client, userdata, message):
print("message:", message.topic + ': ' + str(message.payload.decode("utf-8")))
########################################
print('I\'m listening for mbox messages !')
broker_address="127.0.0.1"
client_name='mbox'
is_first=True
while 1:
client = mqtt.Client(client_name, clean_session=is_first)
is_first=False
print("polling")
client.on_message=on_message #attach function to callback
client.connect(broker_address) #connect to broker
client.subscribe('mbox/#',qos=1)
client.loop_start()
time.sleep(0.1) # How long should this time be?
client.loop_stop()
# client.loop(0.1) # why doesn't this do the same as the previous three lines?
client.disconnect()
time.sleep(5)
#!/usr/bin/python3
# send a message to a mbox through mqtt
import paho.mqtt.client as mqtt #import the client1
import time
broker_address='127.0.0.1'
client = mqtt.Client('MBoxClient')
client.connect(broker_address)
counter = 1
while True:
print('Press Enter to send msg #'+str(counter)+': ', end='')
a=input()
if a.startswith('q'):
break
client.publish("mbox/mail","Hello "+str(counter), qos=1)
counter += 1
client.disconnect()
print('done!')
@dov

This comment has been minimized.

Copy link
Owner Author

@dov dov commented Aug 8, 2020

This example shows how to create a "Mail Box" service through mqtt. The mbox_receive does the following loop:

  1. Connects to broker
  2. Receive new mail
  3. Goes to sleep

A real application of this would be a battery powered ESP8266 chip that e.g. controls an IR LED. By sleeping most of the time, we can draw very little power from the battery.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.