Created
August 3, 2021 13:43
-
-
Save shantanoo-desai/67ecdf4832f4d35a2520ecea2ed77e91 to your computer and use it in GitHub Desktop.
Simple Paho MQTT Python Script to simultaneously publish/subscribe to a broker
This file contains hidden or 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
#!/bin/bash | |
/usr/bin/docker run --name=mosquitto-broker -p 1883:1883 \ | |
-v $(pwd)/mosquitto/mosquitto.conf:/mosquitto/config/mosquitto.conf \ | |
eclipse-mosquitto:2.0 | |
exit 0 |
This file contains hidden or 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
listener 1883 0.0.0.0 | |
allow_anonymous true |
This file contains hidden or 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
import paho.mqtt.client as mqtt | |
import logging | |
import time | |
logging.basicConfig(level=logging.INFO) | |
logger = logging.getLogger(__name__) | |
UNIQUE_ID = "MY_UNIQUE_CLIENT_ID" | |
SUB_TOPIC = "sensors/test" | |
PUB_TOPIC = "sensors/data" | |
BROKER = 'localhost' | |
PORT = 1883 | |
# Define Callbacks | |
def on_connect(mqttc, obj, flags, rc): | |
if rc == 0: | |
logger.debug(f"Connected to Broker with RC={rc}") | |
else: | |
logger.error(f"Error connecting to Broker") | |
def on_message(mqttc, obj, msg): | |
logger.info(f"Incoming Message: {str(msg.payload)}") | |
def on_publish(mqttc, obj, mid): | |
logger.info(f"Published Message with ID: {mid}") | |
def on_subscribe(mqttc, obj, mid, granted_qos): | |
logger.debug(f"Subscribed: {mid}, qos={granted_qos}") | |
def on_disconnect(mqttc, obj, rc): | |
if rc == 0: | |
logger.debug(f"Disconnected from Broker with RC: {rc}") | |
def main(): | |
mqttc = mqtt.Client(client_id=UNIQUE_ID) | |
mqttc.enable_logger(logger) | |
mqttc.on_message = on_message | |
mqttc.on_connect = on_connect | |
mqttc.on_publish = on_publish | |
mqttc.on_subscribe = on_subscribe | |
logger.info("Connecting to MQTT Broker") | |
mqttc.connect(BROKER, PORT) | |
logger.info("Subscribing to Topics") | |
mqttc.subscribe(SUB_TOPIC, qos=0) | |
mqttc.loop_start() | |
try: | |
loop = True | |
while loop: | |
try: | |
time.sleep(6.0) | |
mqttc.publish(PUB_TOPIC, "test") | |
except: | |
logger.error("error during publishing") | |
loop = False | |
except Exception as e: | |
logger.error(f"Error:{e}") | |
mqttc.disconnect() | |
mqttc.loop_stop() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment