从零开始的TP-Link智能插座自动化:Python脚本编写实例

【免费下载链接】tplink-smartplug TP-Link WiFi SmartPlug Client and Wireshark Dissector 【免费下载链接】tplink-smartplug 项目地址: https://gitcode.com/gh_mirrors/tp/tplink-smartplug

TP-Link智能插座是一款经济实用的智能家居设备,通过Python脚本可以轻松实现远程控制和自动化管理。本文将介绍如何使用开源项目gh_mirrors/tp/tplink-smartplug提供的工具,快速上手智能插座的自动化控制,无需深入了解底层通信协议。

📋 准备工作:环境与工具

在开始编写自动化脚本前,需要准备以下环境和工具:

  • Python 3.x环境
  • TP-Link智能插座(如HS-100或HS-110)
  • 项目核心文件:tplink_smartplug.py

快速获取项目代码

git clone https://gitcode.com/gh_mirrors/tp/tplink-smartplug
cd tplink-smartplug

🔑 核心功能解析

项目中的tplink_smartplug.py提供了完整的智能插座控制功能,主要包括:

1. 预定义控制命令

脚本内置了常用操作命令,无需手动编写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灯
    'reboot'   : '{"system":{"reboot":{"delay":1}}}',  # 重启设备
    'energy'   : '{"emeter":{"get_realtime":{}}}'  # 获取能耗数据(HS-110适用)
}

2. 通信协议加密解密

TP-Link设备使用自定义加密协议,脚本通过以下函数实现数据加解密:

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

def decrypt(string):
    key = 171
    result = ""
    for i in string:
        a = key ^ i
        key = i
        result += chr(a)
    return result

🚀 实战:编写自动化脚本

基础控制示例:一键开关插座

通过命令行直接控制插座状态:

# 打开插座
python tplink_smartplug.py -t 192.168.0.100 -c on

# 关闭插座
python tplink_smartplug.py -t 192.168.0.100 -c off

# 获取设备信息
python tplink_smartplug.py -t 192.168.0.100 -c info

高级应用:定时开关脚本

创建auto_switch.py实现定时控制:

import subprocess
import time
from datetime import datetime

def control_plug(ip, command):
    """控制智能插座的通用函数"""
    result = subprocess.run(
        ["python", "tplink_smartplug.py", "-t", ip, "-c", command, "-q"],
        capture_output=True, text=True
    )
    return result.stdout

# 配置设备IP和时间计划
PLUG_IP = "192.168.0.100"
ON_HOUR = 8   # 早上8点打开
OFF_HOUR = 23 # 晚上11点关闭

while True:
    now = datetime.now()
    # 每天指定时间执行操作
    if now.hour == ON_HOUR and now.minute == 0:
        control_plug(PLUG_IP, "on")
        time.sleep(60)  # 避免重复执行
    elif now.hour == OFF_HOUR and now.minute == 0:
        control_plug(PLUG_IP, "off")
        time.sleep(60)
    time.sleep(30)  # 每30秒检查一次

🔍 协议分析与调试

项目提供的Wireshark dissector可以帮助分析设备通信:

TP-Link智能插座通信协议分析 使用Wireshark捕获并解析TP-Link智能插座通信包,显示设备状态查询命令及响应数据

通过分析通信包,我们可以看到设备使用JSON格式进行数据交换,所有数据经过XOR加密保护。这一机制在tplink_smartplug.pyencryptdecrypt函数中实现。

📝 常用命令参考

完整命令列表可查看项目文件tplink-smarthome-commands.txt,以下是常用命令速查:

命令 功能描述
info 获取设备基本信息
on/off 开关控制
energy 查看实时能耗(仅HS-110)
time 获取设备当前时间
schedule 查看定时任务
reboot 重启设备

💡 自动化扩展建议

  1. 整合到智能家居系统:通过MQTT协议将控制脚本接入Home Assistant
  2. 能耗监控:定期记录能耗数据,生成用电报告
  3. 异常检测:当设备功率异常时发送通知
  4. 场景联动:结合光照传感器实现天黑自动开灯

通过本文介绍的方法,即使是Python新手也能快速实现TP-Link智能插座的自动化控制。项目提供的工具简化了复杂的通信协议处理,让我们可以专注于创意应用的开发。

【免费下载链接】tplink-smartplug TP-Link WiFi SmartPlug Client and Wireshark Dissector 【免费下载链接】tplink-smartplug 项目地址: https://gitcode.com/gh_mirrors/tp/tplink-smartplug

更多推荐