2016-11-22 01:31:25 +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-07-09 12:36:33 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
class SmartPlug:
|
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)
|
2016-11-22 01:31:25 +00:00
|
|
|
|
2016-07-09 11:34:27 +00:00
|
|
|
Note:
|
|
|
|
The library references the same structure as defined for the D-Link Switch
|
|
|
|
"""
|
2016-12-04 22:00:56 +00:00
|
|
|
# switch states
|
|
|
|
SWITCH_STATE_ON = 'ON'
|
|
|
|
SWITCH_STATE_OFF = 'OFF'
|
|
|
|
SWITCH_STATE_UNKNOWN = 'UNKNOWN'
|
|
|
|
|
|
|
|
# possible device features
|
|
|
|
FEATURE_ENERGY_METER = 'ENE'
|
|
|
|
FEATURE_TIMER = 'TIM'
|
|
|
|
|
|
|
|
ALL_FEATURES = (FEATURE_ENERGY_METER, FEATURE_TIMER)
|
2016-07-09 11:34:27 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
def __init__(self, ip_address):
|
|
|
|
"""
|
|
|
|
Create a new SmartPlug instance, identified through its IP address.
|
|
|
|
|
|
|
|
:param ip_address: ip address on which the device listens
|
|
|
|
"""
|
|
|
|
socket.inet_pton(socket.AF_INET, ip_address)
|
|
|
|
self.ip_address = ip_address
|
|
|
|
|
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):
|
2016-11-22 01:31:25 +00:00
|
|
|
"""
|
|
|
|
Retrieve the switch state
|
|
|
|
|
|
|
|
:returns: one of
|
|
|
|
SWITCH_STATE_ON
|
|
|
|
SWITCH_STATE_OFF
|
|
|
|
SWITCH_STATE_UNKNOWN
|
|
|
|
"""
|
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
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
if relay_state == 0:
|
2016-12-04 22:00:56 +00:00
|
|
|
return SmartPlug.SWITCH_STATE_OFF
|
2016-10-19 07:53:21 +00:00
|
|
|
elif relay_state == 1:
|
2016-12-04 22:00:56 +00:00
|
|
|
return SmartPlug.SWITCH_STATE_ON
|
2016-07-09 11:34:27 +00:00
|
|
|
else:
|
2016-11-22 01:31:25 +00:00
|
|
|
_LOGGER.warning("Unknown state %s returned.", relay_state)
|
2016-12-04 22:00:56 +00:00
|
|
|
return SmartPlug.SWITCH_STATE_UNKNOWN
|
2016-07-09 11:34:27 +00:00
|
|
|
|
|
|
|
@state.setter
|
|
|
|
def state(self, value):
|
|
|
|
"""
|
2016-11-22 01:31:25 +00:00
|
|
|
Set the new switch state
|
2016-07-09 11:34:27 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
:param value: one of
|
|
|
|
SWITCH_STATE_ON
|
|
|
|
SWITCH_STATE_OFF
|
|
|
|
:return: True if new state was successfully set
|
|
|
|
False if an error occured
|
|
|
|
"""
|
2016-12-04 22:00:56 +00:00
|
|
|
if value.upper() == SmartPlug.SWITCH_STATE_ON:
|
2016-11-22 01:31:25 +00:00
|
|
|
self.turn_on()
|
2016-12-04 22:00:56 +00:00
|
|
|
elif value.upper() == SmartPlug.SWITCH_STATE_OFF:
|
2016-10-18 07:59:30 +00:00
|
|
|
self.turn_off()
|
2016-07-09 11:34:27 +00:00
|
|
|
else:
|
2016-11-22 01:31:25 +00:00
|
|
|
raise ValueError("State %s is not valid.", value)
|
2016-07-09 11:34:27 +00:00
|
|
|
|
2016-11-21 23:39:17 +00:00
|
|
|
def get_sysinfo(self):
|
2016-11-22 01:31:25 +00:00
|
|
|
"""
|
|
|
|
Retrieve system information.
|
|
|
|
|
|
|
|
:return: dict sysinfo
|
|
|
|
"""
|
|
|
|
response = TPLinkSmartHomeProtocol.query(
|
|
|
|
host=self.ip_address,
|
|
|
|
request={'system': {'get_sysinfo': {}}}
|
2016-11-21 23:39:17 +00:00
|
|
|
)['system']['get_sysinfo']
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
if response['err_code'] != 0:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return response
|
|
|
|
|
2016-10-13 15:31:34 +00:00
|
|
|
def turn_on(self):
|
2016-11-22 01:31:25 +00:00
|
|
|
"""
|
|
|
|
Turn the switch on.
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
:return: True on success
|
|
|
|
:raises ProtocolError when device responds with err_code != 0
|
2016-10-18 07:59:30 +00:00
|
|
|
"""
|
2016-11-21 22:18:12 +00:00
|
|
|
response = TPLinkSmartHomeProtocol.query(
|
2016-11-22 01:31:25 +00:00
|
|
|
host=self.ip_address,
|
|
|
|
request={'system': {'set_relay_state': {'state': 1}}}
|
|
|
|
)['system']['set_relay_state']
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
if response['err_code'] != 0:
|
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
return True
|
2016-10-13 15:31:34 +00:00
|
|
|
|
|
|
|
def turn_off(self):
|
2016-11-22 01:31:25 +00:00
|
|
|
"""
|
|
|
|
Turn the switch off.
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
:return: True on success
|
|
|
|
False on error
|
2016-10-18 07:59:30 +00:00
|
|
|
"""
|
2016-11-21 22:18:12 +00:00
|
|
|
response = TPLinkSmartHomeProtocol.query(
|
2016-11-22 01:31:25 +00:00
|
|
|
host=self.ip_address,
|
|
|
|
request={'system': {'set_relay_state': {'state': 0}}}
|
|
|
|
)['system']['set_relay_state']
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
if response['err_code'] != 0:
|
|
|
|
return False
|
2016-10-18 07:59:30 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
return True
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-21 23:39:17 +00:00
|
|
|
@property
|
|
|
|
def has_emeter(self):
|
2016-11-22 01:31:25 +00:00
|
|
|
"""
|
|
|
|
Checks feature list for energey meter support.
|
|
|
|
|
|
|
|
:return: True if energey meter is available
|
|
|
|
False if energymeter is missing
|
|
|
|
"""
|
2016-12-04 22:00:56 +00:00
|
|
|
return SmartPlug.FEATURE_ENERGY_METER in self.features
|
2016-11-21 23:39:17 +00:00
|
|
|
|
2016-10-13 15:31:34 +00:00
|
|
|
def get_emeter_realtime(self):
|
2016-11-22 01:31:25 +00:00
|
|
|
"""
|
|
|
|
Retrive current energy readings from device.
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
:returns: dict with current readings
|
|
|
|
False if device has no energy meter or error occured
|
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(
|
2016-11-22 01:31:25 +00:00
|
|
|
host=self.ip_address, request={'emeter': {'get_realtime': {}}}
|
|
|
|
)['emeter']['get_realtime']
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
if response['err_code'] != 0:
|
2016-10-18 07:59:30 +00:00
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
del response['err_code']
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
return response
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
def get_emeter_daily(self, year=None, month=None):
|
|
|
|
"""
|
|
|
|
Retrieve daily statistics for a given month
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
:param year: year for which to retrieve statistics (default: this year)
|
|
|
|
:param month: month for which to retrieve statistcs (default: this
|
|
|
|
month)
|
|
|
|
:return: dict: mapping of day of month to value
|
|
|
|
False if device has no energy meter or error occured
|
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-22 01:31:25 +00:00
|
|
|
if year is None:
|
|
|
|
year = datetime.datetime.now().year
|
|
|
|
if month is None:
|
|
|
|
month = datetime.datetime.now().month
|
|
|
|
|
2016-11-21 22:18:12 +00:00
|
|
|
response = TPLinkSmartHomeProtocol.query(
|
2016-11-22 01:31:25 +00:00
|
|
|
host=self.ip_address,
|
|
|
|
request={'emeter': {'get_daystat': {'month': str(month),
|
|
|
|
'year': str(year)}}}
|
|
|
|
)['emeter']['get_daystat']
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
if response['err_code'] != 0:
|
2016-10-18 07:59:30 +00:00
|
|
|
return False
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
return {entry['day']: entry['energy']
|
|
|
|
for entry in response['day_list']}
|
2016-10-18 07:59:30 +00:00
|
|
|
|
|
|
|
def get_emeter_monthly(self, year=datetime.datetime.now().year):
|
2016-11-22 01:31:25 +00:00
|
|
|
"""
|
|
|
|
Retrieve monthly statistics for a given year.
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
:param year: year for which to retrieve statistics (default: this year)
|
|
|
|
:return: dict: mapping of month to value
|
|
|
|
False if device has no energy meter or error occured
|
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(
|
2016-11-22 01:31:25 +00:00
|
|
|
host=self.ip_address,
|
|
|
|
request={'emeter': {'get_monthstat': {'year': str(year)}}}
|
|
|
|
)['emeter']['get_monthstat']
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
if response['err_code'] != 0:
|
2016-10-18 07:59:30 +00:00
|
|
|
return False
|
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
return {entry['month']: entry['energy']
|
|
|
|
for entry in response['month_list']}
|
2016-10-13 15:31:34 +00:00
|
|
|
|
|
|
|
def erase_emeter_stats(self):
|
2016-11-22 01:31:25 +00:00
|
|
|
"""
|
|
|
|
Erase energy meter statistics
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
:return: True if statistics were deleted
|
|
|
|
False if device has no energy meter or error occured
|
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(
|
2016-11-22 01:31:25 +00:00
|
|
|
host=self.ip_address,
|
|
|
|
request={'emeter': {'erase_emeter_stat': None}}
|
|
|
|
)['emeter']['erase_emeter_stat']
|
2016-10-13 15:31:34 +00:00
|
|
|
|
2016-11-22 01:31:25 +00:00
|
|
|
return response['err_code'] == 0
|
2016-10-13 15:31:34 +00:00
|
|
|
|
|
|
|
def current_consumption(self):
|
2016-11-22 01:31:25 +00:00
|
|
|
"""
|
|
|
|
Get the current power consumption in Watt.
|
|
|
|
|
|
|
|
:return: the current power consumption in Watt.
|
|
|
|
False if device has no energy meter of error occured.
|
|
|
|
"""
|
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-11-22 01:31:25 +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']
|
2016-11-22 01:31:25 +00:00
|
|
|
model = sys_info['model']
|
2016-11-21 23:39:17 +00:00
|
|
|
features = sys_info['feature'].split(':')
|
|
|
|
|
|
|
|
for feature in features:
|
2016-12-04 22:00:56 +00:00
|
|
|
if feature not in SmartPlug.ALL_FEATURES:
|
2016-11-22 01:31:25 +00:00
|
|
|
_LOGGER.warning("Unknown feature %s on device %s.",
|
|
|
|
feature, model)
|
2016-11-21 23:39:17 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
"""
|
2016-11-22 01:31:25 +00:00
|
|
|
initialization_vector = 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-22 01:31:25 +00:00
|
|
|
key = TPLinkSmartHomeProtocol.initialization_vector
|
2016-11-21 22:18:12 +00:00
|
|
|
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-22 01:31:25 +00:00
|
|
|
key = TPLinkSmartHomeProtocol.initialization_vector
|
2016-11-21 22:18:12 +00:00
|
|
|
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
|