## ##########################################################
## @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!
## ##########################################################