Add better client example
This commit is contained in:
46
Messaging/clientEx copy.py
Normal file
46
Messaging/clientEx copy.py
Normal file
@@ -0,0 +1,46 @@
|
||||
import paho.mqtt.client as mqtt
|
||||
import time
|
||||
import ssl
|
||||
|
||||
connected = False
|
||||
|
||||
def on_connect(client, userdata, flags, rc):
|
||||
print("Connected with result code " + str(rc))
|
||||
if rc == 0:
|
||||
global connected
|
||||
connected = True
|
||||
|
||||
client.subscribe('hello/test', qos=1)
|
||||
|
||||
def on_message(client, userdata, message):
|
||||
p = str(message.payload)
|
||||
p = message.payload.decode('utf-8', errors="strict")
|
||||
print("Received message '" + p + "' on topic '"
|
||||
+ message.topic + "' with QoS " + str(message.qos))
|
||||
|
||||
mqttc = mqtt.Client()
|
||||
|
||||
# mqttc.tls_set_context(context = ssl.create_default_context())
|
||||
|
||||
mqttc.on_connect = on_connect
|
||||
mqttc.on_message = on_message
|
||||
|
||||
mqttc.connect('10.1.3.123', 1883, 60)
|
||||
|
||||
mqttc.loop_start()
|
||||
|
||||
pub = input("Enter something to publish: ")
|
||||
|
||||
while pub != 'q':
|
||||
if(connected):
|
||||
mqttc.publish('hello/test', pub)
|
||||
pub = input("Enter something to publish: ")
|
||||
print('Message is: ' + pub)
|
||||
else:
|
||||
pub = input('Would you like to reconnect? ')
|
||||
if pub == 'y':
|
||||
mqttc.reconnect()
|
||||
time.sleep(2)
|
||||
|
||||
mqttc.loop_stop()
|
||||
mqttc.disconnect()
|
||||
Reference in New Issue
Block a user