This commit is contained in:
xyj 2023-12-28 09:37:37 +08:00
parent 4e5be6bd2e
commit a0e4dcac5b
1 changed files with 11 additions and 18 deletions

29
test.py
View File

@ -7,11 +7,7 @@ import paho.mqtt.client as mqtt
app = FastAPI()
broker = 'mqtt.lihaink.cn'
port = 1883
subscribe_topic = 'info_dev_4'
username = 'lihai_lot_land_1'
password = 'lihai_lot_land_1'
class MQTTClient:
@ -24,26 +20,22 @@ class MQTTClient:
# 千万不要指定client_id 不然死翘翘
self.client = mqtt.Client()
self.client.username_pw_set(self.username, self.password)
self.client.on_connect = self.on_connect
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
self.client.subscribe(self.topic)
def push(self):
self.client.publish("lihai_lot_walnutpi_dev_4", payload=json.dumps({"msg": "push_stream"}, ensure_ascii=False),
self.client.publish(self.topic, payload=json.dumps({"msg": "push_stream"}, ensure_ascii=False),
qos=0)
def close(self):
self.client.publish("lihai_lot_walnutpi_dev_4", payload=json.dumps({"msg": "close_stream"}, ensure_ascii=False),
self.client.publish(self.topic, payload=json.dumps({"msg": "close_stream"}, ensure_ascii=False),
qos=0)
def start(self):
self.client.connect(self.broker, self.port)
@app.get("/push_stream")
def push_stream():
@app.post("/push_stream")
def push_stream(username, device):
MQTT = MQTTClient(broker, port, device, username, username)
try:
MQTT.start()
MQTT.push()
@ -52,9 +44,10 @@ def push_stream():
pass
@app.get("/close_stream")
def close_stream():
@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:
@ -63,6 +56,6 @@ def close_stream():
if __name__ == '__main__':
MQTT = MQTTClient(broker, port, subscribe_topic, username, password)
broker = 'mqtt.lihaink.cn'
port = 1883
uvicorn.run(app, host="127.0.0.1", port=8000)