Created
August 8, 2020 18:10
-
-
Save dov/d0dd06d702e5e456f8022774b4089f1b to your computer and use it in GitHub Desktop.
mqtt mbox example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This example shows how to create a "Mail Box" service through mqtt. The mbox_receive does the following loop:
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.