diff --git a/mqtt/mqttSingleTest.py b/mqtt/mqttSingleTest.py new file mode 100644 index 0000000..153edd2 --- /dev/null +++ b/mqtt/mqttSingleTest.py @@ -0,0 +1,49 @@ +# python 3.6 + +import random +import time + +from paho.mqtt import client as mqtt_client + +name = 'test' +broker = '192.168.0.196' +port = 1883 +topic = "home/switch/test/config" +# generate client ID with pub prefix randomly +client_id = f'python-mqtt-{random.randint(0, 1000)}' +username = 'mqtt' +password = 'falrenforbreakfast' + +def connect_mqtt(): + def on_connect(client, userdata, flags, rc): + if rc == 0: + print("Connected to MQTT Broker!") + else: + print("Failed to connect, return code %d\n", rc) + + client = mqtt_client.Client(client_id) + client.username_pw_set(username, password) + client.on_connect = on_connect + client.connect(broker, port) + return client + + +def publish(client): + msg = '{"name": "test", "device_class": "switch", "state_topic": "home/switch/test/state"}' + result = client.publish(topic, msg) + # result: [0, 1] + status = result[0] + if status == 0: + print(f"Send `{msg}` to topic `{topic}`") + else: + print(f"Failed to send message to topic {topic}") + + +def run(): + client = connect_mqtt() + client.loop_start() + publish(client) + + +if __name__ == '__main__': + run() diff --git a/mqtt/mqttTest.py b/mqtt/mqttTest.py new file mode 100755 index 0000000..8072a01 --- /dev/null +++ b/mqtt/mqttTest.py @@ -0,0 +1,53 @@ +# python 3.6 + +import random +import time + +from paho.mqtt import client as mqtt_client + + +broker = '192.168.0.196' +port = 1883 +topic = "homeassistant/switch/test/config" +# generate client ID with pub prefix randomly +client_id = f'python-mqtt-{random.randint(0, 1000)}' +username = 'mqtt' +password = 'falrenforbreakfast' + +def connect_mqtt(): + def on_connect(client, userdata, flags, rc): + if rc == 0: + print("Connected to MQTT Broker!") + else: + print("Failed to connect, return code %d\n", rc) + + client = mqtt_client.Client(client_id) + client.username_pw_set(username, password) + client.on_connect = on_connect + client.connect(broker, port) + return client + + +def publish(client): + msg_count = 0 + while True: + time.sleep(1) + msg = f"messages: {msg_count}" + result = client.publish(topic, msg) + # result: [0, 1] + status = result[0] + if status == 0: + print(f"Send `{msg}` to topic `{topic}`") + else: + print(f"Failed to send message to topic {topic}") + msg_count += 1 + + +def run(): + client = connect_mqtt() + client.loop_start() + publish(client) + + +if __name__ == '__main__': + run()