2016-11-21 22:18:12 +00:00
|
|
|
# pyHS100
|
|
|
|
# Python Library supporting TP-Link Smart Plugs/Switches (HS100/HS110/Hs200)
|
|
|
|
#
|
|
|
|
# The communication protocol was reverse engineered by Lubomir Stroetmann and
|
|
|
|
# Tobias Esser in 'Reverse Engineering the TP-Link HS110'
|
|
|
|
# https://www.softscheck.com/en/reverse-engineering-tp-link-hs110/
|
|
|
|
#
|
|
|
|
# This library reuses codes and concepts of the TP-Link WiFi SmartPlug Client
|
|
|
|
# at https://github.com/softScheck/tplink-smartplug, developed by Lubomir
|
|
|
|
# Stroetmann which is licensed under the Apache License, Version 2.0.
|
|
|
|
#
|
|
|
|
# You may obtain a copy of the license at
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
import datetime
|
|
|
|
import json
|
2016-07-09 12:36:33 +00:00
|
|
|
import logging
|
|
|
|
import socket
|
2016-10-15 08:18:31 +00:00
|
|
|
import sys
|
2016-07-09 11:34:27 +00:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2016-11-21 23:39:17 +00:00
|
|
|
# possible device features
|
|
|
|
FEATURE_ENERGY_METER = 'ENE'
|
|
|
|
FEATURE_TIMER = 'TIM'
|
|
|
|
|
|
|
|
ALL_FEATURES = (FEATURE_ENERGY_METER, FEATURE_TIMER)
|
|
|
|
|
2016-07-09 12:36:33 +00:00
|
|
|
|
2016-07-09 11:34:27 +00:00
|
|
|
class SmartPlug(object):
|
2016-11-21 22:18:12 +00:00
|
|
|
"""Representation of a TP-Link Smart Switch.
|
2016-07-09 12:36:33 +00:00
|
|
|
|
2016-07-09 11:34:27 +00:00
|
|
|
Usage example when used as library:
|
|
|
|
p = SmartPlug("192.168.1.105")
|
2016-11-21 23:39:17 +00:00
|
|
|
# print the devices alias
|
|
|
|
print(p.alias)
|
2016-07-09 11:34:27 +00:00
|
|
|
# change state of plug
|
|
|
|
p.state = "OFF"
|
|
|
|
p.state = "ON"
|
|
|
|
# query and print current state of plug
|
|
|
|
print(p.state)
|
|
|
|
Note:
|
|
|
|
The library references the same structure as defined for the D-Link Switch
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, ip):
|
|
|
|
"""Create a new SmartPlug instance identified by the IP."""
|
|
|
|
self.ip = ip
|
2016-11-21 23:39:17 +00:00
|
|
|
self.alias, self.model, self.features = self.identify()
|
2016-07-09 11:34:27 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def state(self):
|
|
|
|
"""Get the device state (i.e. ON or OFF)."""
|
2016-11-21 23:39:17 +00:00
|
|
|
response = self.get_sysinfo()
|
|
|
|
relay_state = response['relay_state']
|
2016-10-19 07:53:21 +00:00
|
|
|
|
|
|
|
if relay_state is None:
|
2016-07-09 11:34:27 +00:00
|
|
|
return 'unknown'
|
2016-10-19 07:53:21 +00:00
|
|
|
elif relay_state == 0:
|
2016-07-09 11:34:27 +00:00
|
|
|
return "OFF"
|
2016-10-19 07:53:21 +00:00
|
|
|
elif relay_state == 1:
|
2016-07-09 11:34:27 +00:00
|
|
|
return "ON"
|
|
|
|
else:
|
2016-10-19 07:53:21 +00:00
|
|
|
_LOGGER.warning("Unknown state %s returned" % str(relay_state))
|
2016-07-09 11:34:27 +00:00
|
|
|
return 'unknown'
|
|
|
|
|
|
|
|
@state.setter
|
|
|
|
def state(self, value):
|
|
|
|
"""Set device state.
|
|
|
|
:type value: str
|
|
|
|
:param value: Future state (either ON or OFF)
|
|
|
|
"""
|
|
|
|
if value.upper() == 'ON':
|
2016-10-18 07:59:30 +00:00
|
|
|
self.turn_on()
|
2016-07-09 11:34:27 +00:00
|
|
|
|
|
|
|
elif value.upper() == 'OFF':
|
2016-10-18 07:59:30 +00:00
|
|
|
self.turn_off()
|
2016-07-09 11:34:27 +00:00
|
|
|
|
|
|
|
else:
|
|
|
|
raise TypeError("State %s is not valid." % str(value))
|
|
|
|
|
2016-11-21 23:39:17 +00:00
|
|
|
def get_sysinfo(self):
|
2016-10-18 07:59:30 +00:00
|
|
|
"""Interrogate the switch"""
|
2016-11-21 22:18:12 +00:00
|
|
|
return TPLinkSmartHomeProtocol.query(
|
2016-11-21 23:39:17 +00:00
|
|
|
host=self.ip, request='{"system":{"get_sysinfo":{}}}'
|
|
|
|
)['system']['get_sysinfo']
|
2016-10-13 15:31:34 +00:00
|
|
|
|
|
|
|
def turn_on(self):
|
2016-10-18 07:59:30 +00:00
|
|
|
"""Turns the switch on
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
Return values:
|
|
|
|
True on success
|
|
|
|
False on failure
|
|
|
|
"""
|
2016-11-21 22:18:12 +00:00
|
|
|
response = TPLinkSmartHomeProtocol.query(
|
|
|
|
host=self.ip, request='{"system":{"set_relay_state":{"state":1}}}')
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
if response["system"]["set_relay_state"]["err_code"] == 0:
|
|
|
|
return True
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
|
|
|
def turn_off(self):
|
2016-10-18 07:59:30 +00:00
|
|
|
"""Turns the switch off
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
Return values:
|
|
|
|
True on success
|
|
|
|
False on failure
|
|
|
|
"""
|
2016-11-21 22:18:12 +00:00
|
|
|
response = TPLinkSmartHomeProtocol.query(
|
|
|
|
host=self.ip, request='{"system":{"set_relay_state":{"state":0}}}')
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
if response["system"]["set_relay_state"]["err_code"] == 0:
|
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 23:39:17 +00:00
|
|
|
@property
|
|
|
|
def has_emeter(self):
|
|
|
|
return FEATURE_ENERGY_METER in self.features
|
|
|
|
|
2016-10-13 15:31:34 +00:00
|
|
|
def get_emeter_realtime(self):
|
2016-10-18 07:59:30 +00:00
|
|
|
"""Gets the current energy readings from the switch
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
Return values:
|
|
|
|
False if command is not successful or the switch doesn't support energy metering
|
|
|
|
Dict with the current readings
|
|
|
|
"""
|
2016-11-21 23:39:17 +00:00
|
|
|
if not self.has_emeter:
|
2016-10-18 07:59:30 +00:00
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
response = TPLinkSmartHomeProtocol.query(
|
|
|
|
host=self.ip, request='{"emeter":{"get_realtime":{}}}')
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
if response["emeter"]["get_realtime"]["err_code"] != 0:
|
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
response["emeter"]["get_realtime"].pop('err_code', None)
|
|
|
|
return response["emeter"]["get_realtime"]
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
def get_emeter_daily(self, year=datetime.datetime.now().year, month=datetime.datetime.now().month):
|
|
|
|
"""Gets daily statistics for a given month.
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
Arguments:
|
|
|
|
year (optional): The year for which to retrieve statistics, defaults to current year
|
|
|
|
month (optional): The mont for which to retrieve statistics, defaults to current month
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
Return values:
|
|
|
|
False if command is not successful or the switch doesn't support energy metering
|
|
|
|
Dict where the keys represent the days, and the values are the aggregated statistics
|
|
|
|
"""
|
2016-11-21 23:39:17 +00:00
|
|
|
if not self.has_emeter:
|
2016-10-18 07:59:30 +00:00
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
response = TPLinkSmartHomeProtocol.query(
|
|
|
|
host=self.ip, request='{"emeter":{"get_daystat":{"month":' + str(month) + ',"year":' + str(year) + '}}}')
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
if response["emeter"]["get_daystat"]["err_code"] != 0:
|
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
data = dict()
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
for i, j in enumerate(response["emeter"]["get_daystat"]["day_list"]):
|
|
|
|
if j["energy"] > 0:
|
|
|
|
data[j["day"]] = j["energy"]
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
return data
|
|
|
|
|
|
|
|
def get_emeter_monthly(self, year=datetime.datetime.now().year):
|
|
|
|
"""Gets monthly statistics for a given year.
|
2016-10-13 15:31:34 +00:00
|
|
|
|
|
|
|
Arguments:
|
|
|
|
year (optional): The year for which to retrieve statistics, defaults to current year
|
|
|
|
|
|
|
|
Return values:
|
|
|
|
False if command is not successful or the switch doesn't support energy metering
|
|
|
|
Dict - the keys represent the months, the values are the aggregated statistics
|
2016-10-18 07:59:30 +00:00
|
|
|
"""
|
2016-11-21 23:39:17 +00:00
|
|
|
if not self.has_emeter:
|
2016-10-18 07:59:30 +00:00
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
response = TPLinkSmartHomeProtocol.query(
|
|
|
|
host=self.ip, request='{"emeter":{"get_monthstat":{"year":' + str(year) + '}}}')
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
if response["emeter"]["get_monthstat"]["err_code"] != 0:
|
|
|
|
return False
|
|
|
|
|
|
|
|
data = dict()
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
for i, j in enumerate(response["emeter"]["get_monthstat"]["month_list"]):
|
|
|
|
if j["energy"] > 0:
|
|
|
|
data[j["month"]] = j["energy"]
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
return data
|
2016-10-13 15:31:34 +00:00
|
|
|
|
|
|
|
def erase_emeter_stats(self):
|
2016-10-18 07:59:30 +00:00
|
|
|
"""Erases all statistics.
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
Return values:
|
|
|
|
True: Success
|
|
|
|
False: Failure or not supported by switch
|
|
|
|
"""
|
2016-11-21 23:39:17 +00:00
|
|
|
if not self.has_emeter:
|
2016-10-18 07:59:30 +00:00
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
response = TPLinkSmartHomeProtocol.query(
|
|
|
|
host=self.ip, request='{"emeter":{"erase_emeter_stat":null}}')
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
if response["emeter"]["erase_emeter_stat"]["err_code"] != 0:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
2016-10-13 15:31:34 +00:00
|
|
|
|
|
|
|
def current_consumption(self):
|
2016-10-18 07:59:30 +00:00
|
|
|
"""Get the current power consumption in Watt."""
|
2016-11-21 23:39:17 +00:00
|
|
|
if not self.has_emeter:
|
2016-10-19 07:28:48 +00:00
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
response = self.get_emeter_realtime()
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-10-18 07:59:30 +00:00
|
|
|
return response["power"]
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 23:39:17 +00:00
|
|
|
def identify(self):
|
|
|
|
"""
|
|
|
|
Query device information to identify model and featureset
|
|
|
|
|
|
|
|
:return: str model, list of supported features
|
|
|
|
"""
|
|
|
|
sys_info = self.get_sysinfo()
|
|
|
|
|
|
|
|
alias = sys_info['alias']
|
|
|
|
model = sys_info["model"]
|
|
|
|
features = sys_info['feature'].split(':')
|
|
|
|
|
|
|
|
for feature in features:
|
|
|
|
if feature not in ALL_FEATURES:
|
|
|
|
_LOGGER.warn('Unknown feature %s on device %s.', feature, model)
|
|
|
|
|
|
|
|
return alias, model, features
|
2016-11-21 22:18:12 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TPLinkSmartHomeProtocol:
|
|
|
|
"""
|
|
|
|
Implementation of the TP-Link Smart Home Protocol
|
|
|
|
|
|
|
|
Encryption/Decryption methods based on the works of
|
|
|
|
Lubomir Stroetmann and Tobias Esser
|
|
|
|
|
|
|
|
https://www.softscheck.com/en/reverse-engineering-tp-link-hs110/
|
|
|
|
https://github.com/softScheck/tplink-smartplug/
|
|
|
|
|
|
|
|
which are licensed under the Apache License, Version 2.0
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
"""
|
|
|
|
IV = 171
|
2016-10-17 12:17:28 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
@staticmethod
|
|
|
|
def query(host, request, port=9999):
|
2016-10-18 07:59:30 +00:00
|
|
|
"""
|
2016-11-21 22:18:12 +00:00
|
|
|
Request information from a TP-Link SmartHome Device and return the
|
|
|
|
response.
|
|
|
|
|
|
|
|
:param host: ip address of the device
|
|
|
|
:param port: port on the device (default: 9999)
|
|
|
|
:param request: command to send to the device (can be either dict or
|
|
|
|
json string)
|
|
|
|
:return:
|
2016-10-18 07:59:30 +00:00
|
|
|
"""
|
2016-11-21 22:18:12 +00:00
|
|
|
if isinstance(request, dict):
|
|
|
|
request = json.dumps(request)
|
2016-10-15 08:18:31 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
sock.connect((host, port))
|
|
|
|
sock.send(TPLinkSmartHomeProtocol.encrypt(request))
|
|
|
|
buffer = sock.recv(4096)[4:]
|
|
|
|
sock.shutdown(socket.SHUT_RDWR)
|
|
|
|
sock.close()
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
response = TPLinkSmartHomeProtocol.decrypt(buffer)
|
|
|
|
return json.loads(response)
|
2016-10-17 12:17:28 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
@staticmethod
|
|
|
|
def encrypt(request):
|
2016-10-18 07:59:30 +00:00
|
|
|
"""
|
2016-11-21 22:18:12 +00:00
|
|
|
Encrypt a request for a TP-Link Smart Home Device.
|
|
|
|
|
|
|
|
:param request: plaintext request data
|
|
|
|
:return: ciphertext request
|
2016-10-18 07:59:30 +00:00
|
|
|
"""
|
2016-11-21 22:18:12 +00:00
|
|
|
key = TPLinkSmartHomeProtocol.IV
|
|
|
|
buffer = ['\0\0\0\0']
|
2016-10-15 08:18:31 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
for char in request:
|
|
|
|
cipher = key ^ ord(char)
|
|
|
|
key = cipher
|
|
|
|
buffer.append(chr(cipher))
|
2016-10-15 08:18:31 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
ciphertext = ''.join(buffer)
|
|
|
|
if sys.version_info.major > 2:
|
|
|
|
ciphertext = ciphertext.encode('latin-1')
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
return ciphertext
|
2016-10-18 07:59:30 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
@staticmethod
|
|
|
|
def decrypt(ciphertext):
|
|
|
|
"""
|
|
|
|
Decrypt a response of a TP-Link Smart Home Device.
|
2016-10-18 07:59:30 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
:param ciphertext: encrypted response data
|
|
|
|
:return: plaintext response
|
2016-10-18 07:59:30 +00:00
|
|
|
"""
|
2016-11-21 22:18:12 +00:00
|
|
|
key = TPLinkSmartHomeProtocol.IV
|
|
|
|
buffer = []
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
if sys.version_info.major > 2:
|
|
|
|
ciphertext = ciphertext.decode('latin-1')
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
for char in ciphertext:
|
|
|
|
plain = key ^ ord(char)
|
|
|
|
key = ord(char)
|
|
|
|
buffer.append(chr(plain))
|
|
|
|
|
|
|
|
plaintext = ''.join(buffer)
|
|
|
|
|
|
|
|
return plaintext
|