# pythonproject01 **Repository Path**: sakura-matou/pythonproject01 ## Basic Information - **Project Name**: pythonproject01 - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-06-09 - **Last Updated**: 2026-06-09 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # PythonProject2 这个项目把以下实验内容串成了一套完整链路: 1. TCP 客户端每秒发送一个随机数 2. TCP 服务端接收数据并动态显示最近 20 个点 3. 服务端把数据写入 MySQL 4. 服务端把数据发布到 MQTT 5. MQTT 订阅端把时间戳和数值保存到文本文件 6. FastAPI 提供按时间段查询和统计分析接口 7. Streamlit 页面同时调用 REST API 和 MQTT 8. Streamlit 的实时曲线通过 MQTT WebSocket 在新消息到达时立即更新 ## 目录说明 - `client.py`: TCP 客户端 - `server.py`: TCP 服务端 + MySQL 入库 + MQTT 发布 + 动态曲线 - `data_service.py`: MySQL 访问和统计分析公共层 - `mqtt_publisher.py`: MQTT 发布工具 - `mqtt_receiver.py`: MQTT 订阅端,保存到 `received_data.txt` - `web_api.py`: FastAPI 查询服务 - `streamlit_dashboard.py`: Streamlit 前端页面 - `start_all.ps1`: 一键启动脚本 - `schema.sql`: 数据库建表脚本 - `requirements.txt`: Python 依赖 ## 默认配置 - TCP 服务端: `127.0.0.1:8888` - FastAPI: `http://127.0.0.1:8000` - MQTT Broker: `127.0.0.1:1883` - MQTT Topic: `tcp/data` - MQTT WebSocket: `ws://127.0.0.1:8083/mqtt` - MySQL 地址: `jdbc:mysql://localhost:3306` - MySQL 数据库: `python01` - MySQL 数据表: `tcp_random_data` 如果需要修改,可以通过环境变量覆盖: - `TCP_HOST` - `TCP_PORT` - `MQTT_BROKER` - `MQTT_PORT` - `MQTT_TOPIC` - `MQTT_WS_URL` - `MYSQL_HOST` - `MYSQL_PORT` - `MYSQL_USER` - `MYSQL_PASSWORD` - `MYSQL_DB` - `MYSQL_TABLE` ## 安装依赖 ```powershell pip install -r requirements.txt ``` ## 启动顺序 1. 启动 MySQL 2. 启动 EMQX 3. 启动 TCP 服务端 4. 启动 MQTT 接收端 5. 启动 FastAPI 6. 启动 Streamlit 7. 启动 TCP 客户端 ## 启动命令 ### 一键启动 ```powershell .\start_all.ps1 ``` 可选参数: ```powershell .\start_all.ps1 -SkipClient .\start_all.ps1 -SkipReceiver .\start_all.ps1 -HeadlessStreamlit ``` ### 1. TCP 服务端 ```powershell python server.py ``` ### 2. MQTT 接收端 ```powershell python mqtt_receiver.py ``` ### 3. FastAPI ```powershell uvicorn web_api:app --host 127.0.0.1 --port 8000 ``` ### 4. Streamlit ```powershell streamlit run streamlit_dashboard.py ``` ### 5. TCP 客户端 ```powershell python client.py ``` ## EMQX 说明 Streamlit 实时图表使用的是 MQTT WebSocket,而不是定时刷新页面。 因此要确保 EMQX 已开启 WebSocket 监听,通常地址是: ```text ws://127.0.0.1:8083/mqtt ``` ## 时间段查询 FastAPI 提供以下核心接口: - `GET /api/data/query` - `GET /api/data/recent` - `GET /api/stats/summary` - `GET /api/stats/distribution` - `GET /api/stats/timeseries` 例如查询某个时间段的数据: ```text http://127.0.0.1:8000/api/data/query?start_time=2026-06-05 09:00:00&end_time=2026-06-05 10:00:00 ```