import json import uvicorn from fastapi import FastAPI import paho.mqtt.client as mqtt app = FastAPI() class MQTTClient: def __init__(self, broker, port, topic, username, password): self.broker = broker self.port = port self.topic = topic self.username = username self.password = password # 千万不要指定client_id 不然死翘翘 self.client = mqtt.Client() self.client.username_pw_set(self.username, self.password) def push(self): self.client.publish(self.topic, payload=json.dumps({"msg": "open_led"}, ensure_ascii=False), qos=0) self.client.publish(self.topic, payload=json.dumps({"msg": "push_stream"}, ensure_ascii=False), qos=0) def close(self): self.client.publish(self.topic, payload=json.dumps({"msg": "close_stream"}, ensure_ascii=False), qos=0) self.client.publish(self.topic, payload=json.dumps({"msg": "close_led"}, ensure_ascii=False), qos=0) def start(self): self.client.connect(self.broker, self.port) @app.post("/push_stream") def push_stream(username, device): MQTT = MQTTClient(broker, port, device, username, username) try: MQTT.start() MQTT.push() except Exception as e: # print(e) pass @app.post("/close_stream") def close_stream(username, device): try: MQTT = MQTTClient(broker, port, device, username, username) MQTT.start() MQTT.close() except Exception as e: # print(e) pass if __name__ == '__main__': broker = 'mqtt.lihaink.cn' port = 1883 uvicorn.run(app, host="127.0.0.1", port=8000)