TP-Link智能插座终极指南:Python自动化控制完整实战
TP-Link智能插座终极指南Python自动化控制完整实战【免费下载链接】tplink-smartplugTP-Link WiFi SmartPlug Client and Wireshark Dissector项目地址: https://gitcode.com/gh_mirrors/tp/tplink-smartplugTP-Link智能插座如HS-100和HS-110是智能家居领域的热门设备通过Python脚本可以实现灵活的设备控制和自动化管理。本文将深入解析开源项目tplink-smartplug的核心功能提供从基础控制到高级应用的完整解决方案帮助开发者快速上手TP-Link智能插座的自动化开发。 项目核心功能解析快速获取项目代码git clone https://gitcode.com/gh_mirrors/tp/tplink-smartplug cd tplink-smartplug核心控制脚本tplink_smartplug.py项目的主控制脚本tplink_smartplug.py提供了完整的TP-Link智能插座控制功能支持HS-100和HS-110型号。该脚本实现了TP-Link智能家居协议的核心通信机制。预定义控制命令脚本内置了丰富的控制命令开发者无需手动构造复杂的JSON数据# 预定义的智能插座命令 commands { info: {system:{get_sysinfo:{}}}, # 获取设备信息 on: {system:{set_relay_state:{state:1}}}, # 打开插座 off: {system:{set_relay_state:{state:0}}}, # 关闭插座 ledoff: {system:{set_led_off:{off:1}}}, # 关闭LED指示灯 ledon: {system:{set_led_off:{off:0}}}, # 开启LED指示灯 cloudinfo: {cnCloud:{get_info:{}}}, # 获取云连接信息 wlanscan: {netif:{get_scaninfo:{refresh:0}}}, # 扫描WiFi网络 time: {time:{get_time:{}}}, # 获取设备时间 schedule: {schedule:{get_rules:{}}}, # 获取定时规则 countdown: {count_down:{get_rules:{}}}, # 获取倒计时规则 antitheft: {anti_theft:{get_rules:{}}}, # 获取防盗规则 reboot: {system:{reboot:{delay:1}}}, # 重启设备 reset: {system:{reset:{delay:1}}}, # 恢复出厂设置 energy: {emeter:{get_realtime:{}}} # 获取能耗数据HS-110 }通信协议加密解密TP-Link设备使用自定义的XOR自动密钥加密算法脚本通过以下函数实现数据加解密def encrypt(string): 加密函数使用XOR自动密钥算法 key 171 result pack(I, len(string)) for i in string: a key ^ ord(i) key a result bytes([a]) return result def decrypt(string): 解密函数与加密算法对称 key 171 result for i in string: a key ^ i key i result chr(a) return resultWireshark协议解析器项目还提供了Wireshark dissector插件tplink-smarthome.lua可以解析TP-Link智能家居协议的通信数据包。这对于调试和协议分析非常有价值。 基础控制实战命令行控制示例通过简单的命令行参数即可控制智能插座# 获取设备信息 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 # 重启设备 python tplink_smartplug.py -t 192.168.0.100 -c rebootPython API调用示例除了命令行工具您也可以直接在Python脚本中调用控制功能import subprocess import json def control_plug(ip, command, quietFalse): 控制智能插座的通用函数 cmd [python, tplink_smartplug.py, -t, ip, -c, command] if quiet: cmd.append(-q) result subprocess.run(cmd, capture_outputTrue, textTrue) if not quiet: print(f发送命令: {command}) print(f设备响应: {result.stdout}) return json.loads(result.stdout) if quiet else result.stdout # 使用示例 device_ip 192.168.0.100 response control_plug(device_ip, info, quietTrue) print(f设备信息: {response}) TP-Link智能插座通信协议分析TP-Link智能插座使用基于JSON的自定义协议通过TCP端口9999进行通信。协议采用简单的XOR加密提供基本的数据保护。通过Wireshark dissector插件我们可以深入分析通信过程。上图展示了Wireshark抓包工具对TP-Link智能插座通信协议的分析结果。图中可以看到协议栈结构从802.11无线帧到TCP/IP协议栈再到TP-Link自定义协议JSON数据格式通信数据采用JSON格式包含设备信息查询、控制命令等加密机制协议使用XOR自动密钥加密密钥初始值为171协议通信流程客户端连接到设备的TCP端口9999发送JSON格式的命令数据经过XOR加密设备接收命令并执行相应操作设备返回JSON格式的响应同样经过XOR加密客户端解密并解析响应数据 高级自动化应用定时控制脚本创建自动化控制脚本实现基于时间的设备控制import schedule import time from datetime import datetime import subprocess import json class SmartPlugScheduler: def __init__(self, ip_address): self.ip ip_address self.schedule_tasks [] def turn_on(self): 打开插座 result subprocess.run( [python, tplink_smartplug.py, -t, self.ip, -c, on, -q], capture_outputTrue, textTrue ) print(f[{datetime.now()}] 插座已打开) return result.stdout def turn_off(self): 关闭插座 result subprocess.run( [python, tplink_smartplug.py, -t, self.ip, -c, off, -q], capture_outputTrue, textTrue ) print(f[{datetime.now()}] 插座已关闭) return result.stdout def get_energy_data(self): 获取能耗数据仅HS-110 result subprocess.run( [python, tplink_smartplug.py, -t, self.ip, -c, energy, -q], capture_outputTrue, textTrue ) return json.loads(result.stdout) def schedule_daily_on(self, hour, minute0): 每天定时打开 schedule.every().day.at(f{hour:02d}:{minute:02d}).do(self.turn_on) self.schedule_tasks.append(f每天 {hour:02d}:{minute:02d} 打开) def schedule_daily_off(self, hour, minute0): 每天定时关闭 schedule.every().day.at(f{hour:02d}:{minute:02d}).do(self.turn_off) self.schedule_tasks.append(f每天 {hour:02d}:{minute:02d} 关闭) def run_scheduler(self): 运行调度器 print(f已设置的任务: {self.schedule_tasks}) while True: schedule.run_pending() time.sleep(60) # 每分钟检查一次 # 使用示例 scheduler SmartPlugScheduler(192.168.0.100) scheduler.schedule_daily_on(8, 0) # 每天早上8点打开 scheduler.schedule_daily_off(23, 0) # 每天晚上11点关闭 scheduler.run_scheduler()能耗监控系统对于HS-110型号可以创建能耗监控系统import time import json import csv from datetime import datetime class EnergyMonitor: def __init__(self, ip_address, interval300): self.ip ip_address self.interval interval # 监控间隔秒 self.data_file energy_data.csv def monitor_energy(self, duration_hours24): 监控能耗数据 end_time time.time() (duration_hours * 3600) # 创建CSV文件并写入表头 with open(self.data_file, w, newline) as csvfile: writer csv.writer(csvfile) writer.writerow([timestamp, voltage_mv, current_ma, power_mw, total_wh, err_code]) print(f开始监控能耗数据将持续{duration_hours}小时...) while time.time() end_time: try: # 获取能耗数据 result subprocess.run( [python, tplink_smartplug.py, -t, self.ip, -c, energy, -q], capture_outputTrue, textTrue ) energy_data json.loads(result.stdout) emeter_data energy_data.get(emeter, {}).get(get_realtime, {}) # 保存数据 with open(self.data_file, a, newline) as csvfile: writer csv.writer(csvfile) writer.writerow([ datetime.now().isoformat(), emeter_data.get(voltage_mv, 0), emeter_data.get(current_ma, 0), emeter_data.get(power_mw, 0), emeter_data.get(total_wh, 0), emeter_data.get(err_code, 0) ]) print(f[{datetime.now()}] 能耗数据已记录) except Exception as e: print(f获取能耗数据失败: {e}) time.sleep(self.interval) print(f监控完成数据已保存到 {self.data_file}) 协议扩展与自定义命令自定义JSON命令除了预定义命令您还可以直接发送自定义的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_icon:{}}} # 设置设备位置 python tplink_smartplug.py -t 192.168.0.100 -j {system:{set_dev_location:{longitude:116.4074,latitude:39.9042}}}完整的命令参考项目提供了完整的命令参考文件tplink-smarthome-commands.txt包含以下类别命令类别主要功能示例命令系统命令设备基本信息、重启、重置{system:{get_sysinfo:null}}电源控制开关控制、LED控制{system:{set_relay_state:{state:1}}}云服务云连接状态、服务器信息{cnCloud:{get_info:{}}}网络配置WiFi扫描、网络设置{netif:{get_scaninfo:{refresh:0}}}时间管理设备时间、时区设置{time:{get_time:{}}}定时任务定时规则管理{schedule:{get_rules:{}}}能耗监控实时能耗数据HS-110{emeter:{get_realtime:{}}}️ TDDP协议客户端项目还包含TP-Link设备调试协议TDDP客户端tddp-client.py支持更底层的设备通信# 使用TDDP协议查询设备信息 python tddp-client/tddp_client.py -t 192.168.0.100 -c 0A # 使用自定义用户名密码 python tddp-client/tddp_client.py -t 192.168.0.100 -u admin -p password -c 0ETDDP协议运行在UDP端口1040响应发送到UDP端口61000。该协议使用DES加密密钥基于用户名和密码的MD5哈希值。 实际应用场景智能家居集成将TP-Link智能插座集成到智能家居系统中# Home Assistant集成示例 import homeassistant.remote as remote class TPLinkSmartPlugHA: def __init__(self, hass_url, api_password, plug_ip): self.api remote.API(hass_url, api_password) self.plug_ip plug_ip def turn_on_via_ha(self, entity_id): 通过Home Assistant控制插座 remote.call_service(self.api, switch, turn_on, {entity_id: entity_id}) def create_automation(self, trigger, action): 创建自动化规则 automation_config { alias: TP-Link智能插座自动化, trigger: trigger, action: action } remote.set_state(self.api, automation.tplink_plug, stateon, attributesautomation_config)能耗分析与优化分析能耗数据优化用电习惯import pandas as pd import matplotlib.pyplot as plt def analyze_energy_data(csv_file): 分析能耗数据并生成报告 df pd.read_csv(csv_file) # 计算统计数据 avg_power df[power_mw].mean() / 1000 # 转换为瓦特 total_energy df[total_wh].iloc[-1] - df[total_wh].iloc[0] print(f平均功率: {avg_power:.2f}W) print(f总能耗: {total_energy:.2f}Wh) # 生成可视化图表 plt.figure(figsize(12, 6)) plt.plot(pd.to_datetime(df[timestamp]), df[power_mw] / 1000) plt.xlabel(时间) plt.ylabel(功率 (W)) plt.title(TP-Link智能插座功率曲线) plt.grid(True) plt.savefig(power_consumption.png) plt.show() 安全注意事项网络隔离建议将智能插座放置在独立的网络段中防火墙配置限制对端口9999的访问固件更新定期检查并更新设备固件密码安全修改默认的管理密码协议加密了解XOR加密的局限性不应用于高安全场景 性能优化建议连接池管理对于频繁操作实现连接池减少连接开销异步操作使用异步IO提高并发性能缓存机制缓存设备信息减少重复查询错误重试实现智能重试机制处理网络波动日志记录详细记录操作日志便于问题排查 总结TP-Link智能插座Python控制项目为开发者提供了完整的自动化解决方案。通过本文介绍的Python脚本和协议分析工具您可以快速实现设备控制使用预定义命令或自定义JSON深入分析通信协议借助Wireshark dissector理解底层机制构建自动化系统创建定时任务、能耗监控等高级应用集成智能家居平台与Home Assistant等系统无缝对接无论是家庭自动化、能耗管理还是IoT开发这个项目都提供了强大的基础工具。立即开始您的TP-Link智能插座自动化之旅解锁智能家居的无限可能【免费下载链接】tplink-smartplugTP-Link WiFi SmartPlug Client and Wireshark Dissector项目地址: https://gitcode.com/gh_mirrors/tp/tplink-smartplug创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考