mqtt_03.py

#!/usr/bin/python3
# ===================================================================
#
# ===================================================================

import user_interface as ui
import paho.mqtt.client as mqtt


broker        = 'localhost'
instance      = 'tom'
topic_default = 'light'
topic_root    = '/test/house'


if not ui.running_python3():
    print()
    print('Must run Python3 - exit program')
    print()
    sys.exit()

ui.clear_screen()
print()
print(f'Broker       : {broker}')
print(f'topic_default: {topic_default}')
print(f'topic_root   : {topic_root}')
print()

print(f'creating new client instance {instance}')
client = mqtt.Client(instance)

print(f'connecting to broker at {broker}')
client.connect(broker)

while True:                # loop

    print()
    t = ui.get_user_input('Enter topic: ')

    if not t:              # empty string?
        t = topic_default

    tt = f'{topic_root}/{t}'

    print()
    v = ui.get_user_input('Enter value: ')

    if not v:              # empty string?
        break

    print()
    print(f'publish "{v}" to "{tt}"')
    client.publish(tt,v)