Skip to content

Instantly share code, notes, and snippets.

@dov
Created August 8, 2020 18:10
Show Gist options
  • Save dov/d0dd06d702e5e456f8022774b4089f1b to your computer and use it in GitHub Desktop.
Save dov/d0dd06d702e5e456f8022774b4089f1b to your computer and use it in GitHub Desktop.
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 <[email protected]>
# 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
Copy link
Author

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