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)

相关推荐
小张同学a.42 分钟前
LAMP架构2
linux·运维·网络·架构·负载均衡
9624561 小时前
跨域与私有网络访问限制排查实录
运维·服务器·网络
发量惊人的中年网工1 小时前
SD-WAN如何赋能工业物联网?打造工厂网络远程连接和数据传输新方案
运维·网络·分布式·物联网
Chengbei111 小时前
云存储桶漏洞检测工具OSS-2.0更新,全类型文件解析,存储桶遍历 + 敏感排查一站式完成渗透取证
网络·安全·web安全·网络安全·xss
乐维_lwops2 小时前
乐维社区“专家坐诊”第403期问答
运维·网络·监控系统·答疑·lerwee运维智能体
2401_873479402 小时前
IPv6支持不足怎么办?用双栈兼容IP离线库实现平滑过渡
数据库·网络协议·tcp/ip·ip
小王C语言2 小时前
虚拟机开机过程中关机,再次开机没有分配 IP
linux·网络·tcp/ip
零零信安2 小时前
暗网监测技术实践(一):威胁源采集与反爬对抗——基于《暗网情报技术能力框架》的双生态视角
网络·数据泄露·零零信安
翼龙云_cloud3 小时前
阿里云国际站代理商:ECS弹性伸缩 自动应对流量高峰
运维·网络·数据库·阿里云·架构
ZJH__GO3 小时前
网络编程v4--群聊和私聊的实现
运维·服务器·网络