3 """Wrapper functions for dealing with TPLink devices. Based on code
4 written by Lubomir Stroetmann and Copyright 2016 softScheck GmbH which
5 was covered by the Apache 2.0 license:
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
11 http://www.apache.org/licenses/LICENSE-2.0
13 Modifications by Scott Gasch Copyright 2020-2022 also released under
14 the Apache 2.0 license as required by the license (see above).
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
30 from struct import pack
31 from typing import Dict, Optional
34 from decorator_utils import timeout
36 logger = logging.getLogger(__name__)
39 @timeout(10.0, use_signals=False, error_message="Timed out waiting for tplink.py")
40 def tplink_command(command: str) -> bool:
41 result = os.system(command)
42 signal = result & 0xFF
44 msg = f'{command} died with signal {signal}'
46 logging_utils.hlog(msg)
49 exit_value = result >> 8
51 msg = f'{command} failed, exited {exit_value}'
53 logging_utils.hlog(msg)
55 logger.debug('%s succeeded.', command)
59 @timeout(10.0, use_signals=False, error_message="Timed out waiting for tplink.py")
60 def tplink_get_info(cmd: str) -> Optional[Dict]:
61 logger.debug('Getting tplink device status via "%s"', cmd)
63 out = subprocess.getoutput(cmd)
64 logger.debug('RAW OUT> %s', out)
65 out = re.sub("Sent:.*\n", "", out)
66 out = re.sub("Received: *", "", out)
67 info = json.loads(out)["system"]["get_sysinfo"]
68 logger.debug("%s", json.dumps(info, indent=4, sort_keys=True))
70 except Exception as e:
72 print(out, file=sys.stderr)
76 def encrypt(string: str) -> bytes:
77 """Encryption and Decryption of TP-Link Smart Home Protocol.
79 XOR Autokey Cipher with starting key = 171
81 >>> " ".join(hex(b).replace('0x', '') for b in encrypt('{"system":{"get_sysinfo":{}}}'))
82 '0 0 0 1d d0 f2 81 f8 8b ff 9a f7 d5 ef 94 b6 d1 b4 c0 9f ec 95 e6 8f e1 87 e8 ca f0 8b f6 8b f6'
86 result = pack(">I", len(string))
94 def decrypt(string: bytes) -> str:
95 """Opposite of encrypt (above).
97 >>> b = encrypt('hi, mom')
98 >>> s = decrypt(b[4:])
112 if __name__ == '__main__':