# ukgw_mqtt_client **Repository Path**: ukiot/ukgw_mqtt_client ## Basic Information - **Project Name**: ukgw_mqtt_client - **Description**: MQTT 网关客户端:实现login logout control report config update - **Primary Language**: Python - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-04-17 - **Last Updated**: 2025-04-18 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # MQTT设备网关 一个模块化、可扩展的MQTT设备客户端网关,用于物联网设备与MQTT服务器的通信。 ## 功能特点 - **模块化设计**:核心功能被拆分为独立模块,便于扩展和维护 - **完整功能集**:支持设备登录/登出、数据上报、远程控制、配置管理和固件更新 - **可扩展架构**:基于标准接口,可以轻松添加新功能 - **事件驱动**:基于MQTT的发布/订阅机制,支持异步操作 - **错误处理**:内置错误处理和重试机制 ## 项目结构 ``` . ├── mqtt_gateway.py # 核心网关类 ├── modules/ # 功能模块目录 │ ├── __init__.py # 模块包初始化 │ ├── base_module.py # 基础模块接口 │ ├── auth_module.py # 认证模块(登录/登出) │ ├── report_module.py # 数据上报模块 │ ├── control_module.py # 设备控制模块 │ ├── config_module.py # 配置管理模块 │ └── update_module.py # 固件更新模块 ├── example.py # 示例程序 └── README.md # 项目说明 ``` ## 安装要求 - Python 3.6+ - paho-mqtt 库 ## 安装方法 1. 克隆或下载本项目 2. 安装依赖: ```bash pip install paho-mqtt ``` ## 快速开始 1. 确保已安装所有依赖 2. 运行示例程序: ```bash python example.py ``` 示例程序将连接到本地MQTT服务器(默认localhost:1883),并演示各个模块的功能。 ## 使用方法 ### 创建网关实例 ```python from mqtt_gateway import MQTTGateway # 网关配置 config = { 'device_id': 'device123', 'host': 'localhost', 'port': 1883, 'username': 'user', 'password': 'password' } # 创建网关实例 gateway = MQTTGateway(config) ``` ### 添加功能模块 ```python from modules.auth_module import AuthModule from modules.report_module import ReportModule # 创建并注册认证模块 auth_module = AuthModule(gateway, {'auto_login': True}) gateway.register_module('auth', auth_module) # 创建并注册数据上报模块 report_module = ReportModule(gateway, {'report_interval': 60}) gateway.register_module('report', report_module) ``` ### 启动网关 ```python if gateway.start(): print("网关已启动") # 主循环 try: while True: time.sleep(1) except KeyboardInterrupt: pass finally: gateway.stop() else: print("网关启动失败") ``` ## 自定义模块 可以通过继承 `BaseModule` 类来创建自定义模块: ```python from modules.base_module import BaseModule class MyCustomModule(BaseModule): def __init__(self, gateway, module_config=None): super().__init__(gateway, module_config) def get_subscriptions(self): return { f'device/{self.device_id}/custom': self._handle_custom_message } def _handle_custom_message(self, topic, payload): # 处理自定义消息 pass ``` ## 配置说明 网关配置示例: ```json { "device_id": "device123", "client_id": "gateway-device123", "host": "localhost", "port": 1883, "username": "user", "password": "password", "keepalive": 60, "use_tls": false, "modules": { "auth": { "auto_login": true, "heartbeat_interval": 30 }, "report": { "auto_report": true, "report_interval": 60 }, "config": { "config_file": "device_config.json" }, "update": { "auto_update": false, "current_version": "1.0.0" } } } ``` ## 许可证 MIT