SIM7600 MQTT TCP UDP 等常用网络功能测试

EMQX MQTT 测试

from flask import Flask, render_template_string, request, jsonify

import paho.mqtt.client as mqtt

import threading

import time

app = Flask(name)

mqtt_client = None

mqtt_connected = False

recv_messages = \[\]

recv_lock = threading.Lock()

HTML = """
MQTT Web Tool

MQTT Web Client

Broker Port ClientID Topic

Connect

Subscribe
Payload Publish
"""

def on_connect(client, userdata, flags, reason_code, properties=None):

global mqtt_connected

if reason_code == 0:

mqtt_connected = True

with recv_lock:

recv_messages.append("INFO MQTT connected")

else:

mqtt_connected = False

with recv_lock:

recv_messages.append(f"ERROR MQTT connect failed, code={reason_code}")

def on_disconnect(client, userdata, disconnect_flags, reason_code, properties=None):

global mqtt_connected

mqtt_connected = False

with recv_lock:

recv_messages.append(f"INFO MQTT disconnected, code={reason_code}")

def on_message(client, userdata, msg):

payload = msg.payload.decode(errors="ignore")

with recv_lock:

recv_messages.append(f"RECV {msg.topic} : {payload}")

@app.route("/")

def index():

return render_template_string(HTML)

@app.route("/connect", methods="POST")

def connect():

global mqtt_client, mqtt_connected

data = request.get_json(silent=True) or {}

复制代码
host = data.get("host", "").strip()
port = data.get("port", 1883)
clientid = data.get("clientid", "").strip()

if not host:
    return jsonify({"msg": "Host is empty"}), 400
if not clientid:
    return jsonify({"msg": "ClientID is empty"}), 400

try:
    port = int(port)
except Exception:
    return jsonify({"msg": "Port invalid"}), 400

try:
    if mqtt_client is not None:
        try:
            mqtt_client.loop_stop()
            mqtt_client.disconnect()
        except Exception:
            pass

    mqtt_connected = False

    mqtt_client = mqtt.Client(
        callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
        client_id=clientid
    )
    mqtt_client.on_connect = on_connect
    mqtt_client.on_disconnect = on_disconnect
    mqtt_client.on_message = on_message

    mqtt_client.connect(host, port, 60)
    mqtt_client.loop_start()

    # 等待最多3秒确认连接结果
    for _ in range(30):
        if mqtt_connected:
            return jsonify({"msg": f"Connected to {host}:{port}"})
        time.sleep(0.1)

    return jsonify({"msg": "Connect request sent, but not confirmed yet"}), 500

except Exception as e:
    mqtt_client = None
    mqtt_connected = False
    return jsonify({"msg": f"Connect failed: {str(e)}"}), 500

@app.route("/subscribe", methods="POST")

def subscribe():

global mqtt_client, mqtt_connected

data = request.get_json(silent=True) or {}

topic = data.get("topic", "").strip()

复制代码
if not topic:
    return jsonify({"msg": "Topic is empty"}), 400

if mqtt_client is None or not mqtt_connected:
    return jsonify({"msg": "MQTT not connected"}), 400

try:
    mqtt_client.subscribe(topic)
    return jsonify({"msg": f"Subscribed {topic}"})
except Exception as e:
    return jsonify({"msg": f"Subscribe failed: {str(e)}"}), 500

@app.route("/publish", methods="POST")

def publish():

global mqtt_client, mqtt_connected

data = request.get_json(silent=True) or {}

topic = data.get("topic", "").strip()

payload = data.get("payload", "")

复制代码
if not topic:
    return jsonify({"msg": "Topic is empty"}), 400

if mqtt_client is None or not mqtt_connected:
    return jsonify({"msg": "MQTT not connected"}), 400

try:
    info = mqtt_client.publish(topic, payload)
    if info.rc == mqtt.MQTT_ERR_SUCCESS:
        return jsonify({"msg": f"Published: {payload}"})
    else:
        return jsonify({"msg": f"Publish failed, rc={info.rc}"}), 500
except Exception as e:
    return jsonify({"msg": f"Publish failed: {str(e)}"}), 500

@app.route("/recv")

def recv():

global recv_messages

with recv_lock:

msgs = recv_messages:

recv_messages = \[\]

return jsonify(msgs)

if name == "main ":

print("Web MQTT Tool running")

print("Open browser: http://树莓派IP:5000")

app.run(host="0.0.0.0", port=5000, debug=False)

相关推荐
2401_894915532 小时前
Geo 优化源码部署实战:环境配置、参数调优完整指南
运维·服务器·数据库·tcp/ip·安全
肠畔码农2 小时前
Redis 主从复制内核深潜:从物理模型到全量增量同步的本质
网络·redis·php
CDN3603 小时前
360CDN发布HTTP/3(QUIC)弱网加速方案:实测首屏提速40%,彻底终结移动端接口超时与频繁断连
网络·网络协议·http
随风而飘1864 小时前
安立(Anritsu)MT8820C无线综合测试仪(手机综测仪)
网络·功能测试·测试工具·5g·智能手机
SWAGGY..4 小时前
【C++ 初阶】:(12)深入理解C++ stack:容器适配器、底层容器与算法实战
网络·网络协议·rpc
嵌入式阿蔡4 小时前
项目实战 02:智能家居环境网关——ESP32 做 BLE 中心 + 本地联动
网络·单片机·嵌入式硬件·esp32·智能家居·嵌入式实时数据库
Doraemomo4 小时前
Linux编程-socket网络编程之TCP
linux·网络·tcp/ip
猫咪宝妖5 小时前
信息安全工程师-网络信息安全
网络
Brilliantwxx5 小时前
【Linux】 进程(3)深度解析:从查看进程到进程状态
linux·服务器·网络·c++
我星期八休息5 小时前
Linux—五种IO模型与非阻塞IO
linux·运维·服务器·网络·数据库·网络协议