Implementing the Chat- Tool

For this program you need two command prompts on each side: one for the sender and one for the receiver. On each side, start the receiver first, then the transmitter in the second window. Type messages into the sender and watch them appear on the other side.

The programs are identical, the only difference are the topics used for subscribing and publishing.

Commuication Principle

Raspi Sender

import sys
import paho.mqtt.client as mqtt

# start the program
client = mqtt.Client("RaspiSender")  # create new instance
client.connect("192.168.2.110")  # connect to broker

# start loop für  MQTT client
client.loop_start()  # start the loop

# loop forever
while True:
    messageToSend = input("Your message please:")
    if messageToSend == "end":
        sys.exit()
    client.publish("chattool/raspi", messageToSend)

Raspi Receiver

import sys
import paho.mqtt.client as mqtt


# callback for incoming MQTT Messages
def messageReceived(client, userdata, message):
    data = message.payload.decode("utf-8")
    print(data)

# start the program
client = mqtt.Client("RaspiReceiver")  # create new instance
client.connect("192.168.2.110")  # connect to broker
client.subscribe("chattool/computer")

# start loop für  MQTT client
client.loop_start()  # start the loop

# callback for incoming MQTT Messages
client.on_message = messageReceived

input("Press Enter to stop ... \n")

Computer Sender

import sys
import paho.mqtt.client as mqtt

# callback for incoming MQTT Messages
def messageReceived(client, userdata, message):
    data = message.payload.decode("utf-8")
    print(data)

# start the program
client = mqtt.Client("computerSender")  # create new instance
client.connect("192.168.2.110")  # connect to broker

# start loop für  MQTT client
client.loop_start()  # start the loop

# callback for incoming MQTT Messages
client.on_message = messageReceived

# loop forever
while True:
    messageToSend = input("Your message please:")
    if messageToSend == "end":
        sys.exit()
    client.publish("chattool/computer", messageToSend)

Computer Receiver

import sys
import paho.mqtt.client as mqtt

# callback for incoming MQTT Messages
def messageReceived(client, userdata, message):
    data = message.payload.decode("utf-8")
    print(data)


# start the program
client = mqtt.Client("computerReceiver")  # create new instance
client.connect("192.168.2.110")  # connect to broker
client.subscribe("chattool/raspi")

# start loop für  MQTT client
client.loop_start()  # start the loop

# callback for incoming MQTT Messages
client.on_message = messageReceived

input("Press Enter to stop ... \n")