from paho.mqtt import client as mqtt_client


class ConnectParam:
    host = ''
    port = 1883
    clientId = ''

    def __init__(self, host, port, clientId):
        self.host = host
        self.port = port
        self.clientId = clientId

    def __str__(self):
        return str({'host': self.host, 'port': self.port, 'clientId': self.clientId})


def newClient(param: ConnectParam):
    client = mqtt_client.Client(param.clientId)
    client.connect(param.host, param.port)
    return client


def subscribe(client: mqtt_client, topic: str, on_message):
    client.subscribe(topic)
    client.message_callback_add(topic, on_message)
    client.loop_start()# 需要守护线程
    # client.loop_forever()  # 以阻塞方式启动


def demo():
    p=ConnectParam('192.168.0.210',1883,'0x20010000')
    client=newClient(p)
    client.publish('/1/0/0',bytes('123456','utf-8'))
    def on_message(client, userdata, msg):
        print(msg.payload)
    subscribe(client,'/2/0/0',on_message)
    # 使用demo时需要使用 client.loop_forever()


if __name__ == '__main__':
    demo()