Skip to content
Miloš Viktorović
  • Home
  • Coaching
    • Coaching
    • Introduction to Agile
    • Practical (Remote) Agile
  • Posts & Publications
    • Publications
    • Flying
    • Blog
  • Projects
    • Research Project
    • Student IoT kit
    • CODES
  • About
  • Contact

[CODE] mqtt_messenger_example.py

## ##########################################################
## @title: MQTT Messenger Example
## @author: Milos Viktorovic
## @email: m.viktorovic@tue.nl
## @version: 1.0b [13-11-19]
## ##########################################################


from time import sleep
import paho.mqtt.client as mqtt_client
import paho.mqtt.subscribe as mqtt_subscribe

# user variables
offline = False  ## ste to True if working offline, as it allows the script to continue even if MQTT cannot connect
client_id = "StudentGroup_X"
mqtt_host = "broker.hivemq.com"
mqtt_port = 1883
publishing_topic = "testtopic/python101-milos/"
subscription_topic = "testtopic/python101-milos/"
qos = 2 # MQTT QoS level
num_of_tries_mqtt = 3  # maximum number of tries for MQTT connection

connectedFlag = False  # tracks if client is connected
subscribedFlag = False  # tracks if client is subscribed to a topic

received_messages = "" # Var to keep all previously received messages

## ##########################################################
## Defining Functions to handle MQTT events
## MQTT function on_message https://pypi.org/project/paho-mqtt/#subscribe-unsubscribe
## ##########################################################


def on_message(client, userdata, message):
    # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
    # print("Received message '" + str(message.payload) + "' on topic '"
    #       + message.topic + "' with QoS " + str(message.qos))
    # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
    global received_messages ## Global required in order to be able to make changes
    received_messages = received_messages + '\n' + str(message.payload)


def on_subscribe(client, userdata, mid, granted_qos):
    global subscribedFlag  ## Global required in order to be able to make changes
    subscribedFlag = True
    print(client, " subscribed!")


def on_unsubscribe(client, userdata, mid):
    global subscribedFlag
    subscribedFlag = False
    print(client, " unsubscribed!")


def on_connect(client, userdata, flags, rc):
    global connectedFlag
    connectedFlag = True
    print(">>>>>>>>>> Success! MQTT connected! >>>>>>>>>>>")


def on_disconnect(client, userdata, rc):
    global connectedFlag
    connectedFlag = False
    print(">>>>>>>>>> Attention! MQTT disconnected! >>>>>>>>>>>")



## ##########################################################
print("### DEBUG: Script Started! ###")
## ##########################################################
client_id = input("Set your id (and press Enter!) >>> " + '\n')

## ##########################################################
## Connecting to a broker and subscribing to a topic
## ##########################################################
try:
    # print("DEBUG: Trying to connect to MQTT")
    # creating MQTT client
    mqtt = mqtt_client.Client(client_id)
    print("DEBUG: Client created!")

    # connecting to MQTT server

    print("DEBUG: Attempting to connect")
    mqtt.connect(host=mqtt_host, port=mqtt_port)
    print("DEBUG: MQTT connected!")

    # Executes previous MQTT command by running the network loop  More info : https://pypi.org/project/paho-mqtt/#network-loop
    mqtt.loop_start()  # runs the network loop with a timeout of 5sec

    # Assign event handling functions
    mqtt.on_connect = on_connect
    mqtt.on_disconnect = on_disconnect
    mqtt.on_subscribe = on_subscribe
    mqtt.on_unsubscribe = on_unsubscribe
    mqtt.on_message = on_message  # define function that executes on message arrival

    # After successful connection, tries to subscribe to a topic
    print("DEBUG: Trying to subscribe to '" + subscription_topic + "'")
    mqtt.subscribe(
        [(subscription_topic + "all", qos), (subscription_topic + client_id, qos)])  # subscribes to the desired topic

    # Executes previous MQTT command by running the network loop  More info : https://pypi.org/project/paho-mqtt/#network-loop
    mqtt.loop()
    sleep (2)

except Exception as e:
    print("MQTT connection error! ERROR: " + str(e))

    mqtt = False
    # print("Check your network connectivity and MQTT setings!")
    # exit()

## ##########################################################
## Starting main part of the script!
## ##########################################################

# Pre-initialize variables for payload
msg_1 = ""
receiver = "all"

# Main loop
while True:

    # Reinicialise receiver every time
    receiver = "all"

    try:
        print('\n'*10) # 10 new lines on the screen! Better option is to clear screen, but this behaves differently on Linux and Win, so we will not complicate
        print(received_messages)
        print("____________________________________________________________________________")

        msg_1 = input("Type your message (or leave blank) and press Enter! >>> " + '\n')

        if connectedFlag:
            # print("DEBUG: Trying to publish message!")
            if msg_1 != '':
                ## If we want to send messages to the specific person, we should type message in format "@Student_Y Hello there!"

                if msg_1[0] == '@':  # detects weather the message is intended for the specific receiver
                    if len(msg_1.split(" ", 1)) > 1: # check if the format is proper: "@receiver message"
                        receiver, msg_1 = msg_1.split(" ", 1)  # splits receiver ID from the message
                        receiver = receiver[1:]

                msg_1 = client_id + "->" + receiver + ": " + msg_1 # Just nicely formatting the message
                # print("DEBUG: message: " + msg_1)
                # print("DEBUG: receiver: " + receiver)
                ##
                mqtt.publish(topic = publishing_topic + receiver,
                             payload = msg_1,
                             qos = qos
                             )

            # loop network to receive messages
            #mqtt.loop(timeout=1.0)  # runs the network loop with a timeout of 1sec
            # if there is a message, it will be processed through function on_message
    except Exception as e:
        print("Error occurred! ERROR: " + str(e))
        print("(script is continuing)")
        sleep(5) # allow user to read error message

    # sleep (2) # wait 2sec before next readout

## ##########################################################
## THE END!
## ##########################################################
  • [CODE] GrovePi_plus-Example.py
  • [CODE] iot_simulator.py
  • [CODE] GrovePi_plus-startup
  • [CODE] mqtt_and_csv.py
  • [CODE] mqtt_messenger_example.py
  • [CODE] test_IoT.py

Recent Posts

  • Schnitzel flight! EHEH – EDRK
    Schnitzel flight! EHEH – EDRK
    03-Sep-2021
  • Private Pilot License – My journey to PPL!
    Private Pilot License – My journey to PPL!
    22-Apr-2021
  • Solo Cross-country Navigation flight (Big Triangle) EHEH ⇒ EHMZ ⇒ EHSE ⇒ EHEH
    Solo Cross-country Navigation flight (Big Triangle) EHEH ⇒ EHMZ ⇒ EHSE ⇒ EHEH
    13-Dec-2020
  • Spin & acrobatics on Super Decathlon
    Spin & acrobatics on Super Decathlon
    19-Oct-2020
  • Flight log EHEH-EHSE (via Rotterdam)
    Flight log EHEH-EHSE (via Rotterdam)
    19-Oct-2020

Recent Posts

  • Schnitzel flight! EHEH – EDRK
  • Private Pilot License – My journey to PPL!
  • Solo Cross-country Navigation flight (Big Triangle) EHEH ⇒ EHMZ ⇒ EHSE ⇒ EHEH

Archives

  • September 2021
  • April 2021
  • December 2020
  • October 2020
  • August 2020
  • June 2020
  • May 2020
  • January 2020
  • May 2019
Milos Viktorovic © 2025
By Posterity Theme
  • Home
  • Coaching
    • Coaching
    • Introduction to Agile
    • Practical (Remote) Agile
  • Posts & Publications
    • Publications
    • Flying
    • Blog
  • Projects
    • Research Project
    • Student IoT kit
    • CODES
  • About
  • Contact