Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Complete rewrite of the scanner, now allows force-scanning of IP ranges #252

Merged
merged 1 commit into from
Jan 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 27 additions & 8 deletions tinytuya/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
Run TinyTuya Setup Wizard:
python -m tinytuya wizard
This network scan will run if calling this module via command line:
python -m tinytuya <max_retry>
python -m tinytuya <max_time>

"""

Expand All @@ -19,15 +19,20 @@
from . import wizard
from . import scanner

retries = tinytuya.MAXCOUNT
retries = 0
state = 0
color = True
retriesprovided = False
force = False
force_list = []
last_force = False
broadcast_listen = True
assume_yes = False

for i in sys.argv:
if i==sys.argv[0]:
continue
this_force = False
if i.lower() == "wizard":
state = 1
elif i.lower() == "scan":
Expand All @@ -36,25 +41,38 @@
color = False
elif i.lower() == "-force":
force = True
this_force = True
elif i.lower() == "-no-broadcasts":
broadcast_listen = False
elif i.lower() == "snapshot":
state = 2
elif i.lower() == "devices":
state = 3
elif i.lower() == "json":
state = 4
elif i.lower() == "-yes":
assume_yes = True
elif last_force and len(i) > 6:
this_force = True
force_list.append( i )
else:
try:
retries = int(i)
retriesprovided = True
except:
state = 10

last_force = this_force

if force and len(force_list) > 0:
force = force_list

# State 0 = Run Network Scan
if state == 0:
if retriesprovided:
scanner.scan(maxretry=retries, color=color, forcescan=force)
scanner.scan(scantime=retries, color=color, forcescan=force, discover=broadcast_listen, assume_yes=assume_yes)
else:
scanner.scan(color=color, forcescan=force)
scanner.scan(color=color, forcescan=force, discover=broadcast_listen, assume_yes=assume_yes)

# State 1 = Run Setup Wizard
if state == 1:
Expand All @@ -70,7 +88,7 @@
# State 3 = Scan All Devices
if state == 3:
if retriesprovided:
scanner.alldevices(color=color, retries=retries)
scanner.alldevices(color=color, scantime=retries)
else:
scanner.alldevices(color=color)

Expand All @@ -82,16 +100,17 @@
if state == 10:
print("TinyTuya [%s]\n" % (tinytuya.version))
print("Usage:\n")
print(" python -m tinytuya [command] [<max_retry>] [-nocolor] [-h]")
print(" python -m tinytuya <command> [<max_time>] [-nocolor] [-force [192.168.0.0/24 192.168.1.0/24 ...]] [-h]")
print("")
print(" wizard Launch Setup Wizard to get Tuya Local KEYs.")
print(" scan Scan local network for Tuya devices.")
print(" devices Scan all devices listed in devices.json file.")
print(" snapshot Scan devices listed in snapshot.json file.")
print(" json Scan devices listed in snapshot.json file [JSON].")
print(" <max_retry> Maximum number of retries to find Tuya devices [Default=15]")
print(" <max_time> Maximum time to find Tuya devices [Default=%s]" % tinytuya.SCANTIME)
print(" -nocolor Disable color text output.")
print(" -force Force network scan for device IP addresses.")
print(" -force Force network scan for device IP addresses. Auto-detects network range if none provided.")
print(" -no-broadcasts Ignore broadcast packets when force scanning.")
print(" -h Show usage.")
print("")

Expand Down
31 changes: 24 additions & 7 deletions tinytuya/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
SCANTIME = 18 # How many seconds to wait before stopping device discovery
UDPPORT = 6666 # Tuya 3.1 UDP Port
UDPPORTS = 6667 # Tuya 3.3 encrypted UDP Port
UDPPORTAPP = 7000 # Tuya app encrypted UDP Port
TCPPORT = 6668 # Tuya TCP Local Port
TIMEOUT = 3.0 # Seconds to wait for a broadcast
TCPTIMEOUT = 0.4 # Seconds to wait for socket open for scanning
Expand Down Expand Up @@ -154,10 +155,15 @@
MESSAGE_RETCODE_FMT = ">I" # retcode for received messages
MESSAGE_END_FMT = ">2I" # 2*uint32: crc, suffix
MESSAGE_END_FMT_HMAC = ">32sI" # 32s:hmac, uint32:suffix
PREFIX_VALUE = 0x000055AA
PREFIX_BIN = b"\x00\x00U\xaa"
SUFFIX_VALUE = 0x0000AA55
SUFFIX_BIN = b"\x00\x00\xaaU"
PREFIX_VALUE = PREFIX_55AA_VALUE = 0x000055AA
PREFIX_BIN = PREFIX_55AA_BIN = b"\x00\x00U\xaa"
SUFFIX_VALUE = SUFFIX_55AA_VALUE = 0x0000AA55
SUFFIX_BIN = SUFFIX_55AA_BIN = b"\x00\x00\xaaU"
PREFIX_6699_VALUE = 0x00006699
PREFIX_6699_BIN = b"\x00\x00\x66\x99"
SUFFIX_6699_VALUE = 0x00009966
SUFFIX_6699_BIN = b"\x00\x00\x99\x66"

NO_PROTOCOL_HEADER_CMDS = [DP_QUERY, DP_QUERY_NEW, UPDATEDPS, HEART_BEAT, SESS_KEY_NEG_START, SESS_KEY_NEG_RESP, SESS_KEY_NEG_FINISH ]

# Python 2 Support
Expand Down Expand Up @@ -445,7 +451,6 @@ def find_device(dev_id=None, address=None):
gwId = version = ""
result = data
try:
result = data[20:-8]
try:
result = decrypt_udp(result)
except:
Expand Down Expand Up @@ -1556,15 +1561,27 @@ def encrypt(msg, key):
def decrypt(msg, key):
return unpad(AES.new(key, AES.MODE_ECB).decrypt(msg)).decode()

def decrypt_gcm(msg, key):
nonce = msg[:12]
return AES.new(key, AES.MODE_GCM, nonce=nonce).decrypt(msg[12:]).decode()

# UDP packet payload decryption - credit to tuya-convert
udpkey = md5(b"yGAdlopoPVldABfn").digest()


def decrypt_udp(msg):
if msg[:4] == PREFIX_55AA_BIN:
return decrypt(msg[20:-8], udpkey)
if msg[:4] == PREFIX_6699_BIN:
dec = decrypt_gcm(msg[18:-20], udpkey)
# strip return code if present
if dec[:4] == (chr(0) * 4):
dec = dec[4:]
# app sometimes has extra bytes at the end
while dec[-1] == chr(0):
dec = dec[:-1]
return dec
return decrypt(msg, udpkey)


# Return positive number or zero
def floor(x):
if x > 0:
Expand Down
Loading