终极指南:使用Python脚本完全控制TP-Link智能插座
【免费下载链接】tplink-smartplugTP-Link WiFi SmartPlug Client and Wireshark Dissector项目地址: https://gitcode.com/gh_mirrors/tp/tplink-smartplug
想要通过编程方式控制你的TP-Link智能插座吗?厌倦了每次都要打开手机App来操作设备?本文将为你展示如何使用开源项目gh_mirrors/tp/tplink-smartplug提供的Python工具,实现TP-Link智能插座的自动化控制。无论你是想创建定时任务、集成到智能家居系统,还是进行协议分析,这篇文章都将为你提供完整的技术方案。
🔍 理解TP-Link智能插座通信机制
TP-Link智能插座(如HS-100和HS-110)使用一种专有的智能家居协议进行通信。这个协议运行在TCP端口9999上,并采用简单的XOR自动密钥加密机制。虽然这种加密不提供真正的安全性,但它确实为设备间通信增加了一层基本的数据保护。
核心通信原理
智能插座通过JSON格式的命令进行控制,例如获取设备信息的命令为:
{"system":{"get_sysinfo":{}}}项目中的tplink_smartplug.py文件实现了完整的客户端功能,包括数据加密解密和网络通信。加密算法非常简单但有效:
def encrypt(string): key = 171 result = pack(">I", len(string)) for i in string: a = key ^ ord(i) key = a result += bytes([a]) return result这种XOR加密使用171作为初始密钥,每个字符与前一个加密结果进行XOR运算,形成链式加密效果。
🚀 快速开始:安装与基本使用
获取项目代码
首先克隆项目到本地:
git clone https://gitcode.com/gh_mirrors/tp/tplink-smartplug cd tplink-smartplug基本设备控制
项目提供了预定义的命令集,让你可以轻松控制智能插座:
# 获取设备信息 python tplink_smartplug.py -t 192.168.0.100 -c info # 打开插座 python tplink_smartplug.py -t 192.168.0.100 -c on # 关闭插座 python tplink_smartplug.py -t 192.168.0.100 -c off # 获取实时能耗数据(仅HS-110支持) python tplink_smartplug.py -t 192.168.0.100 -c energy可用命令速查表
| 命令 | 功能描述 | 适用场景 |
|---|---|---|
info | 获取设备基本信息 | 设备识别与状态检查 |
on/off | 开关插座 | 远程控制电器 |
energy | 查看实时能耗 | 电量监控与分析 |
time | 获取设备时间 | 时间同步检查 |
schedule | 查看定时规则 | 定时任务管理 |
countdown | 查看倒计时规则 | 延时控制 |
antitheft | 查看防盗规则 | 安防模式设置 |
reboot | 重启设备 | 故障排除 |
ledon/ledoff | 控制LED指示灯 | 夜间模式设置 |
📊 高级功能:深入设备控制
自定义JSON命令
除了预定义命令,你还可以发送自定义的JSON命令来访问更多设备功能:
# 设置设备别名 python tplink_smartplug.py -t 192.168.0.100 -j '{"system":{"set_dev_alias":{"alias":"客厅电灯"}}}' # 获取设备位置信息 python tplink_smartplug.py -t 192.168.0.100 -j '{"system":{"get_dev_location":{}}}' # 扫描Wi-Fi网络 python tplink_smartplug.py -t 192.168.0.100 -c wlanscan能耗监控与分析
对于HS-110型号,你可以获取详细的能耗数据:
import subprocess import json def get_energy_data(ip): """获取智能插座的能耗数据""" result = subprocess.run( ["python", "tplink_smartplug.py", "-t", ip, "-c", "energy", "-q"], capture_output=True, text=True ) return json.loads(result.stdout) # 解析能耗数据 energy_data = get_energy_data("192.168.0.100") print(f"当前功率: {energy_data['emeter']['get_realtime']['power_mw']/1000}W") print(f"电压: {energy_data['emeter']['get_realtime']['voltage_mv']/1000}V") print(f"电流: {energy_data['emeter']['get_realtime']['current_ma']/1000}A")🔧 实战应用:创建智能家居自动化系统
场景1:定时开关控制
创建一个Python脚本,实现根据时间自动控制设备:
import schedule import time import subprocess class SmartPlugController: def __init__(self, ip_address): self.ip = ip_address def turn_on(self): """打开插座""" subprocess.run(["python", "tplink_smartplug.py", "-t", self.ip, "-c", "on", "-q"]) print(f"[{time.strftime('%H:%M:%S')}] 插座已打开") def turn_off(self): """关闭插座""" subprocess.run(["python", "tplink_smartplug.py", "-t", self.ip, "-c", "off", "-q"]) print(f"[{time.strftime('%H:%M:%S')}] 插座已关闭") def get_status(self): """获取设备状态""" result = subprocess.run( ["python", "tplink_smartplug.py", "-t", self.ip, "-c", "info", "-q"], capture_output=True, text=True ) return result.stdout # 创建控制器实例 plug = SmartPlugController("192.168.0.100") # 设置定时任务 schedule.every().day.at("07:00").do(plug.turn_on) # 早上7点打开 schedule.every().day.at("23:00").do(plug.turn_off) # 晚上11点关闭 schedule.every().hour.do(lambda: print(f"设备状态: {plug.get_status()}")) # 运行调度器 while True: schedule.run_pending() time.sleep(1)场景2:基于条件的智能控制
结合传感器数据实现智能控制:
import requests import json from datetime import datetime class SmartPlugAutomation: def __init__(self, plug_ip): self.plug_ip = plug_ip self.weather_api = "https://api.openweathermap.org/data/2.5/weather" def should_turn_on_lights(self): """判断是否需要开灯""" now = datetime.now() # 检查时间(天黑后) if now.hour < 18 and now.hour > 6: return False # 检查天气API(示例) # 实际应用中需要替换为真实的天气API调用 # response = requests.get(f"{self.weather_api}?q=your_city&appid=your_api_key") # weather_data = response.json() # 简化逻辑:根据时间判断 return now.hour >= 18 or now.hour <= 6 def control_based_on_conditions(self): """基于条件控制插座""" if self.should_turn_on_lights(): subprocess.run(["python", "tplink_smartplug.py", "-t", self.plug_ip, "-c", "on", "-q"]) print("条件满足:已打开插座") else: subprocess.run(["python", "tplink_smartplug.py", "-t", self.plug_ip, "-c", "off", "-q"]) print("条件不满足:已关闭插座")🔬 协议分析与调试工具
Wireshark协议解析器
项目还提供了一个Wireshark解析器,可以帮助你深入分析TP-Link智能插座的通信协议:
使用Wireshark捕获并解析TP-Link智能插座通信包,显示设备状态查询命令及响应数据
要使用Wireshark解析器,只需将tplink-smarthome.lua文件复制到Wireshark插件目录:
- Windows:
%APPDATA%\Wireshark\plugins\ - Linux/MacOS:
$HOME/.wireshark/plugins
这个解析器可以自动解密TP-Link智能家居协议的数据包,让你能够直观地查看设备与服务器之间的通信内容。
协议分析实战
通过Wireshark分析,我们可以看到TP-Link设备通信的几个关键特点:
- 通信端口: TCP 9999
- 数据格式: JSON结构
- 加密方式: XOR自动密钥加密
- 云服务: 连接
devs.tplinkcloud.com服务器
📋 完整命令参考
项目中的tplink-smarthome-commands.txt文件包含了完整的命令列表,涵盖了设备控制的各个方面:
系统命令
- 获取系统信息、重启设备、恢复出厂设置
- 设置设备别名、MAC地址、设备ID
- 控制LED指示灯、设置设备位置
网络命令
- 扫描Wi-Fi网络
- 连接到指定Wi-Fi网络
云服务命令
- 获取云连接信息
- 绑定/解绑云账户
- 设置云服务器地址
能耗统计命令(HS-110)
- 获取实时电压、电流、功率数据
- 获取每日/每月用电统计
- 清除能耗统计数据
定时与规则命令
- 创建、编辑、删除定时规则
- 设置倒计时规则
- 配置防盗模式(离家模式)
💡 高级应用场景
集成到Home Assistant
你可以将TP-Link智能插座集成到Home Assistant中,实现更复杂的自动化场景:
# configuration.yaml switch: - platform: command_line switches: living_room_lamp: command_on: "python /path/to/tplink_smartplug.py -t 192.168.0.100 -c on" command_off: "python /path/to/tplink_smartplug.py -t 192.0.100 -c off" command_state: "python /path/to/tplink_smartplug.py -t 192.168.0.100 -c info" value_template: '{{ value_json.system.get_sysinfo.relay_state == 1 }}'能耗监控与报告
创建定期的能耗报告系统:
import csv from datetime import datetime, timedelta class EnergyMonitor: def __init__(self, plug_ip, csv_file="energy_log.csv"): self.plug_ip = plug_ip self.csv_file = csv_file def log_energy_data(self): """记录能耗数据到CSV文件""" data = self.get_energy_data() timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open(self.csv_file, 'a', newline='') as file: writer = csv.writer(file) writer.writerow([ timestamp, data['power_mw']/1000, data['voltage_mv']/1000, data['current_ma']/1000, data['total_wh']/1000 ]) print(f"已记录能耗数据: {timestamp}") def generate_daily_report(self): """生成每日用电报告""" # 实现报告生成逻辑 pass设备批量管理
如果你有多个TP-Link智能插座,可以创建批量管理工具:
class MultiPlugManager: def __init__(self): self.plugs = { "living_room": "192.168.0.100", "bedroom": "192.168.0.101", "kitchen": "192.168.0.102" } def turn_all_on(self): """打开所有插座""" for name, ip in self.plugs.items(): subprocess.run(["python", "tplink_smartplug.py", "-t", ip, "-c", "on", "-q"]) print(f"{name}插座已打开") def turn_all_off(self): """关闭所有插座""" for name, ip in self.plugs.items(): subprocess.run(["python", "tplink_smartplug.py", "-t", ip, "-c", "off", "-q"]) print(f"{name}插座已关闭") def get_all_status(self): """获取所有插座状态""" status = {} for name, ip in self.plugs.items(): result = subprocess.run( ["python", "tplink_smartplug.py", "-t", ip, "-c", "info", "-q"], capture_output=True, text=True ) status[name] = json.loads(result.stdout) return status🛠️ 故障排除与优化建议
常见问题解决
连接超时
- 检查设备IP地址是否正确
- 确保设备与计算机在同一网络
- 验证防火墙设置是否允许端口9999通信
命令无响应
- 确认设备电源正常
- 尝试重启智能插座
- 检查网络连接稳定性
能耗数据不准确
- 仅HS-110支持能耗监控功能
- 确保设备固件为最新版本
- 校准电压和电流增益设置
性能优化建议
连接池管理
- 对于频繁操作,维护TCP连接池
- 减少连接建立和断开的开销
异步操作
- 使用异步IO处理多个设备
- 避免阻塞主线程
错误重试机制
- 实现指数退避重试策略
- 添加连接健康检查
🎯 总结与下一步
通过本文的介绍,你已经掌握了使用Python控制TP-Link智能插座的核心技术。从基本的开关控制到复杂的自动化系统,这个开源项目为你提供了完整的工具链。
关键收获
- 简单易用: 通过预定义命令快速上手
- 功能全面: 支持设备所有功能,包括能耗监控
- 协议透明: 开放的协议实现,便于理解和扩展
- 集成友好: 可轻松集成到现有智能家居系统
扩展方向
- 开发图形界面: 基于现有功能开发用户友好的GUI应用
- 创建REST API: 将控制功能封装为Web服务
- 移动应用集成: 开发手机App进行远程控制
- 机器学习应用: 基于能耗数据训练用电模式识别模型
无论你是智能家居爱好者、物联网开发者,还是只是想自动化家中电器,这个TP-Link智能插座Python控制工具都能为你提供强大的技术支持。现在就开始你的智能家居自动化之旅吧!
【免费下载链接】tplink-smartplugTP-Link WiFi SmartPlug Client and Wireshark Dissector项目地址: https://gitcode.com/gh_mirrors/tp/tplink-smartplug
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考