Skip to content

Commit

Permalink
Minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Paolo97Gll committed Aug 24, 2023
1 parent ca46ce1 commit d414596
Showing 1 changed file with 23 additions and 27 deletions.
50 changes: 23 additions & 27 deletions tplink_smartplug.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

logging.basicConfig(level=logging.INFO, format="[%(asctime)s] (%(levelname)s) %(module)s - %(funcName)s: %(message)s")

version = 0.4
version = 0.4,1

# Check if hostname is valid
def validHostname(hostname):
Expand All @@ -45,13 +45,10 @@ def validPort(port):
port = int(port)
except ValueError:
parser.error("Invalid port number.")

if ((port <= 1024) or (port > 65535)):
parser.error("Invalid port number.")

return port


# Predefined Smart Plug Commands
# For a full list of commands, consult tplink_commands.txt
commands = {'info' : '{"system":{"get_sysinfo":{}}}',
Expand Down Expand Up @@ -91,7 +88,6 @@ def decrypt(string):
result += chr(a)
return result


# Parse commandline arguments
parser = argparse.ArgumentParser(description=f"TP-Link Wi-Fi Smart Plug Client v{version}")
parser.add_argument("-t", "--target", metavar="<hostname>", required=True,
Expand All @@ -111,7 +107,6 @@ def decrypt(string):
help="Constantly update the time if needed")
args = parser.parse_args()


# Set target IP, port and command to send
ip = args.target
port = args.port
Expand All @@ -120,7 +115,6 @@ def decrypt(string):
else:
cmd = commands[args.command]


# Send command and receive reply
def send_command(args, ip, port, cmd):
try:
Expand All @@ -131,41 +125,43 @@ def send_command(args, ip, port, cmd):
sock_tcp.send(encrypt(cmd))
data = sock_tcp.recv(2048)
sock_tcp.close()

decrypted = decrypt(data[4:])
return decrypted

except socket.error:
logging.error(f"Could not connect to host {ip}:{port}")
return None

def update_time():
try:
rsp = send_command(args, ip, port, commands["time"])
if rsp:
rsp = json.loads(rsp)["time"]["get_time"]
time = datetime.now()
time_remote = datetime(rsp["year"], rsp["month"], rsp["mday"], rsp["hour"], rsp["min"], rsp["sec"])
if abs((time_remote - time).total_seconds()) > 60:
cmd = json.dumps({"time":{"set_timezone":{"year":time.year,"month":time.month,"mday":time.day,"hour":time.hour,"min":time.minute,"sec":time.second,"index":41}}})
decrypted = send_command(args, ip, port, cmd)
logging.info(f"Old time: {time_remote}")
logging.info(f"New time: {time}")
logging.info(decrypted)
else:
logging.info("Time ok, bypass")
else:
pass
except Exception as e:
logging.exception(e)

# Normal command
if not args.keep_time_updated:
decrypted = send_command(args, ip, port, cmd)
if args.quiet:
logging.info(decrypted)
else:
logging.info("Sent: ", cmd)
logging.info("Received: ", decrypted)
logging.info(f"Sent: {cmd}")
logging.info(f"Received: {decrypted}")

# Time updater
else:
while True:
try:
rsp = send_command(args, ip, port, commands["time"])
if rsp:
rsp = json.loads(rsp)["time"]["get_time"]
time = datetime.now()
time_remote = datetime(rsp["year"], rsp["month"], rsp["mday"], rsp["hour"], rsp["min"], rsp["sec"])
if abs((time_remote - time).total_seconds()) > 60:
cmd = json.dumps({"time":{"set_timezone":{"year":time.year,"month":time.month,"mday":time.day,"hour":time.hour,"min":time.minute,"sec":time.second,"index":41}}})
decrypted = send_command(args, ip, port, cmd)
logging.info(decrypted)
else:
logging.info("Time ok, bypass")
else:
pass
except Exception as e:
logging.exception(e)
update_time()
sleep(5)

0 comments on commit d414596

Please sign in to comment.