index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
729,310 | tinytuya.BulbDevice | __init__ | null | def __init__(self, *args, **kwargs):
# set the default version to None so we do not immediately connect and call status()
if 'version' not in kwargs or not kwargs['version']:
kwargs['version'] = None
super(BulbDevice, self).__init__(*args, **kwargs)
| (self, *args, **kwargs) |
729,311 | tinytuya.core | __repr__ | null | def __repr__(self):
# FIXME can do better than this
if self.parent:
parent = self.parent.id
else:
parent = None
return ("%s( %r, address=%r, local_key=%r, dev_type=%r, connection_timeout=%r, version=%r, persist=%r, cid=%r, parent=%r, children=%r )" %
(self.__class__.__name__, self.id, self.address, self.real_local_key.decode(), self.dev_type, self.connection_timeout, self.version, self.socketPersistent, self.cid, parent, self.children))
| (self) |
729,312 | tinytuya.core | _check_socket_close | null | def _check_socket_close(self, force=False):
if (force or not self.socketPersistent) and self.socket:
self.socket.close()
self.socket = None
| (self, force=False) |
729,313 | tinytuya.core | _decode_payload | null | def _decode_payload(self, payload):
log.debug("decode payload=%r", payload)
cipher = AESCipher(self.local_key)
if self.version == 3.4:
# 3.4 devices encrypt the version header in addition to the payload
try:
log.debug("decrypting=%r", payload)
payload = cipher.decrypt(payload, False, decode_text=False)
except:
log.debug("incomplete payload=%r (len:%d)", payload, len(payload), exc_info=True)
return error_json(ERR_PAYLOAD)
log.debug("decrypted 3.x payload=%r", payload)
log.debug("payload type = %s", type(payload))
if payload.startswith(PROTOCOL_VERSION_BYTES_31):
# Received an encrypted payload
# Remove version header
payload = payload[len(PROTOCOL_VERSION_BYTES_31) :]
# Decrypt payload
# Remove 16-bytes of MD5 hexdigest of payload
payload = cipher.decrypt(payload[16:])
elif self.version >= 3.2: # 3.2 or 3.3 or 3.4 or 3.5
# Trim header for non-default device type
if payload.startswith( self.version_bytes ):
payload = payload[len(self.version_header) :]
log.debug("removing 3.x=%r", payload)
elif self.dev_type == "device22" and (len(payload) & 0x0F) != 0:
payload = payload[len(self.version_header) :]
log.debug("removing device22 3.x header=%r", payload)
if self.version < 3.4:
try:
log.debug("decrypting=%r", payload)
payload = cipher.decrypt(payload, False)
except:
log.debug("incomplete payload=%r (len:%d)", payload, len(payload), exc_info=True)
return error_json(ERR_PAYLOAD)
log.debug("decrypted 3.x payload=%r", payload)
# Try to detect if device22 found
log.debug("payload type = %s", type(payload))
if not isinstance(payload, str):
try:
payload = payload.decode()
except:
log.debug("payload was not string type and decoding failed")
return error_json(ERR_JSON, payload)
if not self.disabledetect and "data unvalid" in payload:
self.dev_type = "device22"
# set at least one DPS
self.dps_to_request = {"1": None}
log.debug(
"'data unvalid' error detected: switching to dev_type %r",
self.dev_type,
)
return None
elif not payload.startswith(b"{"):
log.debug("Unexpected payload=%r", payload)
return error_json(ERR_PAYLOAD, payload)
if not isinstance(payload, str):
payload = payload.decode()
log.debug("decoded results=%r", payload)
try:
json_payload = json.loads(payload)
except:
json_payload = error_json(ERR_JSON, payload)
# v3.4 stuffs it into {"data":{"dps":{"1":true}}, ...}
if "dps" not in json_payload and "data" in json_payload and "dps" in json_payload['data']:
json_payload['dps'] = json_payload['data']['dps']
return json_payload
| (self, payload) |
729,314 | tinytuya.core | _encode_message | null | def _encode_message( self, msg ):
# make sure to use the parent's self.seqno and session key
if self.parent:
return self.parent._encode_message( msg )
hmac_key = None
iv = None
payload = msg.payload
self.cipher = AESCipher(self.local_key)
if self.version >= 3.4:
hmac_key = self.local_key
if msg.cmd not in NO_PROTOCOL_HEADER_CMDS:
# add the 3.x header
payload = self.version_header + payload
log.debug('final payload: %r', payload)
if self.version >= 3.5:
iv = True
# seqno cmd retcode payload crc crc_good, prefix, iv
msg = TuyaMessage(self.seqno, msg.cmd, None, payload, 0, True, PREFIX_6699_VALUE, True)
self.seqno += 1 # increase message sequence number
data = pack_message(msg,hmac_key=self.local_key)
log.debug("payload encrypted=%r",binascii.hexlify(data))
return data
payload = self.cipher.encrypt(payload, False)
elif self.version >= 3.2:
# expect to connect and then disconnect to set new
payload = self.cipher.encrypt(payload, False)
if msg.cmd not in NO_PROTOCOL_HEADER_CMDS:
# add the 3.x header
payload = self.version_header + payload
elif msg.cmd == CONTROL:
# need to encrypt
payload = self.cipher.encrypt(payload)
preMd5String = (
b"data="
+ payload
+ b"||lpv="
+ PROTOCOL_VERSION_BYTES_31
+ b"||"
+ self.local_key
)
m = md5()
m.update(preMd5String)
hexdigest = m.hexdigest()
# some tuya libraries strip 8: to :24
payload = (
PROTOCOL_VERSION_BYTES_31
+ hexdigest[8:][:16].encode("latin1")
+ payload
)
self.cipher = None
msg = TuyaMessage(self.seqno, msg.cmd, 0, payload, 0, True, PREFIX_55AA_VALUE, False)
self.seqno += 1 # increase message sequence number
buffer = pack_message(msg,hmac_key=hmac_key)
log.debug("payload encrypted=%r",binascii.hexlify(buffer))
return buffer
| (self, msg) |
729,315 | tinytuya.core | _get_socket | null | def _get_socket(self, renew):
if renew and self.socket is not None:
# self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
self.socket = None
if self.socket is None:
# Set up Socket
retries = 0
err = ERR_OFFLINE
while retries < self.socketRetryLimit:
if self.auto_ip and not self.address:
bcast_data = find_device(self.id)
if bcast_data['ip'] is None:
log.debug("Unable to find device on network (specify IP address)")
return ERR_OFFLINE
self.address = bcast_data['ip']
new_version = float(bcast_data['version'])
if new_version != self.version:
# this may trigger a network call which will call _get_socket() again
#self.set_version(new_version)
self.version = new_version
self.version_str = "v" + str(version)
self.version_bytes = str(version).encode('latin1')
self.version_header = self.version_bytes + PROTOCOL_3x_HEADER
self.payload_dict = None
if not self.address:
log.debug("No address for device!")
return ERR_OFFLINE
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if self.socketNODELAY:
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.socket.settimeout(self.connection_timeout)
try:
retries = retries + 1
self.socket.connect((self.address, self.port))
if self.version >= 3.4:
# restart session key negotiation
if self._negotiate_session_key():
return True
else:
if self.socket:
self.socket.close()
self.socket = None
return ERR_KEY_OR_VER
else:
return True
except socket.timeout as e:
# unable to open socket
log.debug(
"socket unable to connect (timeout) - retry %d/%d",
retries, self.socketRetryLimit
)
err = ERR_OFFLINE
except Exception as e:
# unable to open socket
log.debug(
"socket unable to connect (exception) - retry %d/%d",
retries, self.socketRetryLimit, exc_info=True
)
err = ERR_CONNECT
if self.socket:
self.socket.close()
self.socket = None
if retries < self.socketRetryLimit:
time.sleep(self.socketRetryDelay)
if self.auto_ip:
self.address = None
# unable to get connection
return err
# existing socket active
return True
| (self, renew) |
729,316 | tinytuya.BulbDevice | _hexvalue_to_hsv |
Converts the hexvalue used by Tuya for colour representation into
an HSV value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
| @staticmethod
def _hexvalue_to_hsv(hexvalue, bulb="A"):
"""
Converts the hexvalue used by Tuya for colour representation into
an HSV value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
"""
if bulb == "A":
h = int(hexvalue[7:10], 16) / 360.0
s = int(hexvalue[10:12], 16) / 255.0
v = int(hexvalue[12:14], 16) / 255.0
if bulb == "B":
# hexvalue is in hsv
h = int(hexvalue[0:4], 16) / 360.0
s = int(hexvalue[4:8], 16) / 1000.0
v = int(hexvalue[8:12], 16) / 1000.0
return (h, s, v)
| (hexvalue, bulb='A') |
729,317 | tinytuya.BulbDevice | _hexvalue_to_rgb |
Converts the hexvalue used by Tuya for colour representation into
an RGB value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
| @staticmethod
def _hexvalue_to_rgb(hexvalue, bulb="A"):
"""
Converts the hexvalue used by Tuya for colour representation into
an RGB value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
"""
if bulb == "A":
r = int(hexvalue[0:2], 16)
g = int(hexvalue[2:4], 16)
b = int(hexvalue[4:6], 16)
if bulb == "B":
# hexvalue is in hsv
h = float(int(hexvalue[0:4], 16) / 360.0)
s = float(int(hexvalue[4:8], 16) / 1000.0)
v = float(int(hexvalue[8:12], 16) / 1000.0)
rgb = colorsys.hsv_to_rgb(h, s, v)
r = int(rgb[0] * 255)
g = int(rgb[1] * 255)
b = int(rgb[2] * 255)
return (r, g, b)
| (hexvalue, bulb='A') |
729,318 | tinytuya.core | _negotiate_session_key | null | def _negotiate_session_key(self):
rkey = self._send_receive_quick( self._negotiate_session_key_generate_step_1(), 2 )
step3 = self._negotiate_session_key_generate_step_3( rkey )
if not step3:
return False
self._send_receive_quick( step3, None )
self._negotiate_session_key_generate_finalize()
return True
| (self) |
729,319 | tinytuya.core | _negotiate_session_key_generate_finalize | null | def _negotiate_session_key_generate_finalize( self ):
if IS_PY2:
k = [ chr(ord(a)^ord(b)) for (a,b) in zip(self.local_nonce,self.remote_nonce) ]
self.local_key = ''.join(k)
else:
self.local_key = bytes( [ a^b for (a,b) in zip(self.local_nonce,self.remote_nonce) ] )
log.debug("Session nonce XOR'd: %r", self.local_key)
cipher = AESCipher(self.real_local_key)
if self.version == 3.4:
self.local_key = cipher.encrypt( self.local_key, False, pad=False )
else:
iv = self.local_nonce[:12]
log.debug("Session IV: %r", iv)
self.local_key = cipher.encrypt( self.local_key, use_base64=False, pad=False, iv=iv )[12:28]
log.debug("Session key negotiate success! session key: %r", self.local_key)
return True
| (self) |
729,320 | tinytuya.core | _negotiate_session_key_generate_step_1 | null | def _negotiate_session_key_generate_step_1( self ):
self.local_nonce = b'0123456789abcdef' # not-so-random random key
self.remote_nonce = b''
self.local_key = self.real_local_key
return MessagePayload(SESS_KEY_NEG_START, self.local_nonce)
| (self) |
729,321 | tinytuya.core | _negotiate_session_key_generate_step_3 | null | def _negotiate_session_key_generate_step_3( self, rkey ):
if not rkey or type(rkey) != TuyaMessage or len(rkey.payload) < 48:
# error
log.debug("session key negotiation failed on step 1")
return False
if rkey.cmd != SESS_KEY_NEG_RESP:
log.debug("session key negotiation step 2 returned wrong command: %d", rkey.cmd)
return False
payload = rkey.payload
if self.version == 3.4:
try:
log.debug("decrypting=%r", payload)
cipher = AESCipher(self.real_local_key)
payload = cipher.decrypt(payload, False, decode_text=False)
except:
log.debug("session key step 2 decrypt failed, payload=%r (len:%d)", payload, len(payload), exc_info=True)
return False
log.debug("decrypted session key negotiation step 2 payload=%r", payload)
log.debug("payload type = %s len = %d", type(payload), len(payload))
if len(payload) < 48:
log.debug("session key negotiation step 2 failed, too short response")
return False
self.remote_nonce = payload[:16]
hmac_check = hmac.new(self.local_key, self.local_nonce, sha256).digest()
if hmac_check != payload[16:48]:
log.debug("session key negotiation step 2 failed HMAC check! wanted=%r but got=%r", binascii.hexlify(hmac_check), binascii.hexlify(payload[16:48]))
return False
log.debug("session local nonce: %r remote nonce: %r", self.local_nonce, self.remote_nonce)
rkey_hmac = hmac.new(self.local_key, self.remote_nonce, sha256).digest()
return MessagePayload(SESS_KEY_NEG_FINISH, rkey_hmac)
| (self, rkey) |
729,322 | tinytuya.core | _process_message | null | def _process_message( self, msg, dev_type=None, from_child=None, minresponse=28, decode_response=True ):
# null packet, nothing to decode
if not msg or len(msg.payload) == 0:
log.debug("raw unpacked message = %r", msg)
# legacy/default mode avoids persisting socket across commands
self._check_socket_close()
return None
# option - decode Message with hard coded offsets
# result = self._decode_payload(data[20:-8])
# Unpack Message into TuyaMessage format
# and return payload decrypted
try:
# Data available: seqno cmd retcode payload crc
log.debug("raw unpacked message = %r", msg)
result = self._decode_payload(msg.payload)
if result is None:
log.debug("_decode_payload() failed!")
except:
log.debug("error unpacking or decoding tuya JSON payload", exc_info=True)
result = error_json(ERR_PAYLOAD)
# Did we detect a device22 device? Return ERR_DEVTYPE error.
if dev_type and dev_type != self.dev_type:
log.debug(
"Device22 detected and updated (%s -> %s) - Update payload and try again",
dev_type,
self.dev_type,
)
result = error_json(ERR_DEVTYPE)
found_child = False
if self.children:
found_cid = None
if result and 'cid' in result:
found_cid = result['cid']
elif result and 'data' in result and type(result['data']) == dict and 'cid' in result['data']:
found_cid = result['data']['cid']
if found_cid:
for c in self.children:
if self.children[c].cid == found_cid:
result['device'] = found_child = self.children[c]
break
if from_child and from_child is not True and from_child != found_child:
# async update from different CID, try again
log.debug( 'Recieved async update for wrong CID %s while looking for CID %s, trying again', found_cid, from_child.cid )
if self.socketPersistent:
# if persistent, save response until the next receive() call
# otherwise, trash it
if found_child:
result = found_child._process_response(result)
else:
result = self._process_response(result)
self.received_wrong_cid_queue.append( (found_child, result) )
# events should not be coming in so fast that we will never timeout a read, so don't worry about loops
return self._send_receive( None, minresponse, True, decode_response, from_child=from_child)
# legacy/default mode avoids persisting socket across commands
self._check_socket_close()
if found_child:
return found_child._process_response(result)
return self._process_response(result)
| (self, msg, dev_type=None, from_child=None, minresponse=28, decode_response=True) |
729,323 | tinytuya.core | _process_response |
Override this function in a sub-class if you want to do some processing on the received data
| def _process_response(self, response): # pylint: disable=R0201
"""
Override this function in a sub-class if you want to do some processing on the received data
"""
return response
| (self, response) |
729,324 | tinytuya.core | _receive | null | def _receive(self):
# make sure to use the parent's self.seqno and session key
if self.parent:
return self.parent._receive()
# message consists of header + retcode + [data] + crc (4 or 32) + footer
min_len_55AA = struct.calcsize(MESSAGE_HEADER_FMT_55AA) + 4 + 4 + len(SUFFIX_BIN)
# message consists of header + iv + retcode + [data] + crc (16) + footer
min_len_6699 = struct.calcsize(MESSAGE_HEADER_FMT_6699) + 12 + 4 + 16 + len(SUFFIX_BIN)
min_len = min_len_55AA if min_len_55AA < min_len_6699 else min_len_6699
prefix_len = len( PREFIX_55AA_BIN )
data = self._recv_all( min_len )
# search for the prefix. if not found, delete everything except
# the last (prefix_len - 1) bytes and recv more to replace it
prefix_offset_55AA = data.find( PREFIX_55AA_BIN )
prefix_offset_6699 = data.find( PREFIX_6699_BIN )
while prefix_offset_55AA != 0 and prefix_offset_6699 != 0:
log.debug('Message prefix not at the beginning of the received data!')
log.debug('Offset 55AA: %d, 6699: %d, Received data: %r', prefix_offset_55AA, prefix_offset_6699, data)
if prefix_offset_55AA < 0 and prefix_offset_6699 < 0:
data = data[1-prefix_len:]
else:
prefix_offset = prefix_offset_6699 if prefix_offset_55AA < 0 else prefix_offset_55AA
data = data[prefix_offset:]
data += self._recv_all( min_len - len(data) )
prefix_offset_55AA = data.find( PREFIX_55AA_BIN )
prefix_offset_6699 = data.find( PREFIX_6699_BIN )
header = parse_header(data)
remaining = header.total_length - len(data)
if remaining > 0:
data += self._recv_all( remaining )
log.debug("received data=%r", binascii.hexlify(data))
hmac_key = self.local_key if self.version >= 3.4 else None
no_retcode = False #None if self.version >= 3.5 else False
return unpack_message(data, header=header, hmac_key=hmac_key, no_retcode=no_retcode)
| (self) |
729,325 | tinytuya.core | _recv_all | null | def _recv_all(self, length):
tries = 2
data = b''
while length > 0:
newdata = self.socket.recv(length)
if not newdata or len(newdata) == 0:
log.debug("_recv_all(): no data? %r", newdata)
# connection closed?
tries -= 1
if tries == 0:
raise DecodeError('No data received - connection closed?')
if self.sendWait is not None:
time.sleep(self.sendWait)
continue
data += newdata
length -= len(newdata)
tries = 2
return data
| (self, length) |
729,326 | tinytuya.core | _register_child | null | def _register_child(self, child):
if child.id in self.children and child != self.children[child.id]:
log.debug('Replacing existing child %r!', child.id)
self.children[child.id] = child
# disable device22 detection as some gateways return "json obj data unvalid" when the gateway is polled without a cid
self.disabledetect = True
self.payload_dict = None
| (self, child) |
729,327 | tinytuya.BulbDevice | _rgb_to_hexvalue |
Convert an RGB value to the hex representation expected by Tuya Bulb.
Index (DPS_INDEX_COLOUR) is assumed to be in the format:
(Type A) Index: 5 in hex format: rrggbb0hhhssvv
(Type B) Index: 24 in hex format: hhhhssssvvvv
While r, g and b are just hexadecimal values of the corresponding
Red, Green and Blue values, the h, s and v values (which are values
between 0 and 1) are scaled:
Type A: 360 (h) and 255 (s and v)
Type B: 360 (h) and 1000 (s and v)
Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255.
| @staticmethod
def _rgb_to_hexvalue(r, g, b, bulb="A"):
"""
Convert an RGB value to the hex representation expected by Tuya Bulb.
Index (DPS_INDEX_COLOUR) is assumed to be in the format:
(Type A) Index: 5 in hex format: rrggbb0hhhssvv
(Type B) Index: 24 in hex format: hhhhssssvvvv
While r, g and b are just hexadecimal values of the corresponding
Red, Green and Blue values, the h, s and v values (which are values
between 0 and 1) are scaled:
Type A: 360 (h) and 255 (s and v)
Type B: 360 (h) and 1000 (s and v)
Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255.
"""
rgb = [r, g, b]
hsv = colorsys.rgb_to_hsv(rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0)
# Bulb Type A
if bulb == "A":
# h:0-360,s:0-255,v:0-255|hsv|
hexvalue = ""
for value in rgb:
temp = str(hex(int(value))).replace("0x", "")
if len(temp) == 1:
temp = "0" + temp
hexvalue = hexvalue + temp
hsvarray = [int(hsv[0] * 360), int(hsv[1] * 255), int(hsv[2] * 255)]
hexvalue_hsv = ""
for value in hsvarray:
temp = str(hex(int(value))).replace("0x", "")
if len(temp) == 1:
temp = "0" + temp
hexvalue_hsv = hexvalue_hsv + temp
if len(hexvalue_hsv) == 7:
hexvalue = hexvalue + "0" + hexvalue_hsv
else:
hexvalue = hexvalue + "00" + hexvalue_hsv
# Bulb Type B
if bulb == "B":
# h:0-360,s:0-1000,v:0-1000|hsv|
hexvalue = ""
hsvarray = [int(hsv[0] * 360), int(hsv[1] * 1000), int(hsv[2] * 1000)]
for value in hsvarray:
temp = str(hex(int(value))).replace("0x", "")
while len(temp) < 4:
temp = "0" + temp
hexvalue = hexvalue + temp
return hexvalue
| (r, g, b, bulb='A') |
729,328 | tinytuya.core | _send_receive |
Send single buffer `payload` and receive a single buffer.
Args:
payload(bytes): Data to send. Set to 'None' to receive only.
minresponse(int): Minimum response size expected (default=28 bytes)
getresponse(bool): If True, wait for and return response.
| def _send_receive(self, payload, minresponse=28, getresponse=True, decode_response=True, from_child=None):
"""
Send single buffer `payload` and receive a single buffer.
Args:
payload(bytes): Data to send. Set to 'None' to receive only.
minresponse(int): Minimum response size expected (default=28 bytes)
getresponse(bool): If True, wait for and return response.
"""
if self.parent:
return self.parent._send_receive(payload, minresponse, getresponse, decode_response, from_child=self)
if (not payload) and getresponse and self.received_wrong_cid_queue:
if (not self.children) or (not from_child):
r = self.received_wrong_cid_queue[0]
self.received_wrong_cid_queue = self.received_wrong_cid_queue[1:]
return r
found_rq = False
for rq in self.received_wrong_cid_queue:
if rq[0] == from_child:
found_rq = rq
break
if found_rq:
self.received_wrong_cid_queue.remove(found_rq)
return found_rq[1]
success = False
partial_success = False
retries = 0
recv_retries = 0
#max_recv_retries = 0 if not self.retry else 2 if self.socketRetryLimit > 2 else self.socketRetryLimit
max_recv_retries = 0 if not self.retry else self.socketRetryLimit
dev_type = self.dev_type
do_send = True
msg = None
while not success:
# open up socket if device is available
sock_result = self._get_socket(False)
if sock_result is not True:
# unable to get a socket - device likely offline
self._check_socket_close(True)
return error_json( sock_result if sock_result else ERR_OFFLINE )
# send request to device
try:
if payload is not None and do_send:
log.debug("sending payload")
enc_payload = self._encode_message(payload) if type(payload) == MessagePayload else payload
self.socket.sendall(enc_payload)
if self.sendWait is not None:
time.sleep(self.sendWait) # give device time to respond
if getresponse:
do_send = False
rmsg = self._receive()
# device may send null ack (28 byte) response before a full response
# consider it an ACK and do not retry the send even if we do not get a full response
if rmsg:
payload = None
partial_success = True
msg = rmsg
if (not msg or len(msg.payload) == 0) and recv_retries <= max_recv_retries:
log.debug("received null payload (%r), fetch new one - retry %s / %s", msg, recv_retries, max_recv_retries)
recv_retries += 1
if recv_retries > max_recv_retries:
success = True
else:
success = True
log.debug("received message=%r", msg)
else:
# legacy/default mode avoids persisting socket across commands
self._check_socket_close()
return None
except (KeyboardInterrupt, SystemExit) as err:
log.debug("Keyboard Interrupt - Exiting")
raise
except socket.timeout as err:
# a socket timeout occurred
if payload is None:
# Receive only mode - return None
self._check_socket_close()
return None
do_send = True
retries += 1
# toss old socket and get new one
self._check_socket_close(True)
log.debug(
"Timeout in _send_receive() - retry %s / %s",
retries, self.socketRetryLimit
)
# if we exceed the limit of retries then lets get out of here
if retries > self.socketRetryLimit:
log.debug(
"Exceeded tinytuya retry limit (%s)",
self.socketRetryLimit
)
# timeout reached - return error
return error_json(ERR_KEY_OR_VER)
# wait a bit before retrying
time.sleep(0.1)
except DecodeError as err:
log.debug("Error decoding received data - read retry %s/%s", recv_retries, max_recv_retries, exc_info=True)
recv_retries += 1
if recv_retries > max_recv_retries:
# we recieved at least 1 valid message with a null payload, so the send was successful
if partial_success:
self._check_socket_close()
return None
# no valid messages received
self._check_socket_close(True)
return error_json(ERR_PAYLOAD)
except Exception as err:
# likely network or connection error
do_send = True
retries += 1
# toss old socket and get new one
self._check_socket_close(True)
log.debug(
"Network connection error in _send_receive() - retry %s/%s",
retries, self.socketRetryLimit, exc_info=True
)
# if we exceed the limit of retries then lets get out of here
if retries > self.socketRetryLimit:
log.debug(
"Exceeded tinytuya retry limit (%s)",
self.socketRetryLimit
)
log.debug("Unable to connect to device ")
# timeout reached - return error
return error_json(ERR_CONNECT)
# wait a bit before retrying
time.sleep(0.1)
# except
# while
# could be None or have a null payload
if not decode_response:
# legacy/default mode avoids persisting socket across commands
self._check_socket_close()
return msg
return self._process_message( msg, dev_type, from_child, minresponse, decode_response )
| (self, payload, minresponse=28, getresponse=True, decode_response=True, from_child=None) |
729,329 | tinytuya.core | _send_receive_quick | null | def _send_receive_quick(self, payload, recv_retries, from_child=None): # pylint: disable=W0613
if self.parent:
return self.parent._send_receive_quick(payload, recv_retries, from_child=self)
log.debug("sending payload quick")
if self._get_socket(False) is not True:
return None
enc_payload = self._encode_message(payload) if type(payload) == MessagePayload else payload
try:
self.socket.sendall(enc_payload)
except:
self._check_socket_close(True)
return None
if not recv_retries:
return True
while recv_retries:
try:
msg = self._receive()
except:
msg = None
if msg and len(msg.payload) != 0:
return msg
recv_retries -= 1
if recv_retries == 0:
log.debug("received null payload (%r) but out of recv retries, giving up", msg)
else:
log.debug("received null payload (%r), fetch new one - %s retries remaining", msg, recv_retries)
return False
| (self, payload, recv_retries, from_child=None) |
729,330 | tinytuya.core | add_dps_to_request | Add a datapoint (DP) to be included in requests. | def add_dps_to_request(self, dp_indicies):
"""Add a datapoint (DP) to be included in requests."""
if isinstance(dp_indicies, int):
self.dps_to_request[str(dp_indicies)] = None
else:
self.dps_to_request.update({str(index): None for index in dp_indicies})
| (self, dp_indicies) |
729,331 | tinytuya.BulbDevice | brightness | Return brightness value | def brightness(self):
"""Return brightness value"""
return self.status()[self.DPS][self.DPS_INDEX_BRIGHTNESS[self.bulb_type]]
| (self) |
729,332 | tinytuya.core | close | null | def close(self):
self.__del__()
| (self) |
729,333 | tinytuya.BulbDevice | colour_hsv | Return colour as HSV value | def colour_hsv(self):
"""Return colour as HSV value"""
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR[self.bulb_type]]
return BulbDevice._hexvalue_to_hsv(hexvalue, self.bulb_type)
| (self) |
729,334 | tinytuya.BulbDevice | colour_rgb | Return colour as RGB value | def colour_rgb(self):
"""Return colour as RGB value"""
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR[self.bulb_type]]
return BulbDevice._hexvalue_to_rgb(hexvalue, self.bulb_type)
| (self) |
729,335 | tinytuya.BulbDevice | colourtemp | Return colour temperature | def colourtemp(self):
"""Return colour temperature"""
return self.status()[self.DPS][self.DPS_INDEX_COLOURTEMP[self.bulb_type]]
| (self) |
729,336 | tinytuya.core | detect_available_dps | Return which datapoints are supported by the device. | def detect_available_dps(self):
"""Return which datapoints are supported by the device."""
# device22 devices need a sort of bruteforce querying in order to detect the
# list of available dps experience shows that the dps available are usually
# in the ranges [1-25] and [100-110] need to split the bruteforcing in
# different steps due to request payload limitation (max. length = 255)
self.dps_cache = {}
ranges = [(2, 11), (11, 21), (21, 31), (100, 111)]
for dps_range in ranges:
# dps 1 must always be sent, otherwise it might fail in case no dps is found
# in the requested range
self.dps_to_request = {"1": None}
self.add_dps_to_request(range(*dps_range))
try:
data = self.status()
except Exception as ex:
log.exception("Failed to get status: %s", ex)
raise
if data is not None and "dps" in data:
for k in data["dps"]:
self.dps_cache[k] = None
if self.dev_type == "default":
self.dps_to_request = self.dps_cache
return self.dps_cache
log.debug("Detected dps: %s", self.dps_cache)
self.dps_to_request = self.dps_cache
return self.dps_cache
| (self) |
729,337 | tinytuya.core | find |
Mainly here for backwards compatibility.
Calling tinytuya.find_device() directly is recommended.
Parameters:
did = The specific Device ID you are looking for (returns only IP and Version)
Response:
(ip, version)
| @staticmethod
def find(did):
"""
Mainly here for backwards compatibility.
Calling tinytuya.find_device() directly is recommended.
Parameters:
did = The specific Device ID you are looking for (returns only IP and Version)
Response:
(ip, version)
"""
bcast_data = find_device(dev_id=did)
return (bcast_data['ip'], bcast_data['version'])
| (did) |
729,338 | tinytuya.core | generate_payload |
Generate the payload to send.
Args:
command(str): The type of command.
This is one of the entries from payload_dict
data(dict, optional): The data to send.
This is what will be passed via the 'dps' entry
gwId(str, optional): Will be used for gwId
devId(str, optional): Will be used for devId
uid(str, optional): Will be used for uid
| def generate_payload(self, command, data=None, gwId=None, devId=None, uid=None, rawData=None, reqType=None):
"""
Generate the payload to send.
Args:
command(str): The type of command.
This is one of the entries from payload_dict
data(dict, optional): The data to send.
This is what will be passed via the 'dps' entry
gwId(str, optional): Will be used for gwId
devId(str, optional): Will be used for devId
uid(str, optional): Will be used for uid
"""
# dicts will get referenced instead of copied if we don't do this
def _deepcopy(dict1):
result = {}
for k in dict1:
if isinstance( dict1[k], dict ):
result[k] = _deepcopy( dict1[k] )
else:
result[k] = dict1[k]
return result
# dict2 will be merged into dict1
# as dict2 is payload_dict['...'] we only need to worry about copying 2 levels deep,
# the command id and "command"/"command_override" keys: i.e. dict2[CMD_ID]["command"]
def _merge_payload_dicts(dict1, dict2):
for cmd in dict2:
if cmd not in dict1:
# make a deep copy so we don't get a reference
dict1[cmd] = _deepcopy( dict2[cmd] )
else:
for var in dict2[cmd]:
if not isinstance( dict2[cmd][var], dict ):
# not a dict, safe to copy
dict1[cmd][var] = dict2[cmd][var]
else:
# make a deep copy so we don't get a reference
dict1[cmd][var] = _deepcopy( dict2[cmd][var] )
# start merging down to the final payload dict
# later merges overwrite earlier merges
# "default" - ("gateway" if gateway) - ("zigbee" if sub-device) - [version string] - ('gateway_'+[version string] if gateway) -
# 'zigbee_'+[version string] if sub-device - [dev_type if not "default"]
if not self.payload_dict or self.last_dev_type != self.dev_type:
self.payload_dict = {}
_merge_payload_dicts( self.payload_dict, payload_dict['default'] )
if self.children:
_merge_payload_dicts( self.payload_dict, payload_dict['gateway'] )
if self.cid:
_merge_payload_dicts( self.payload_dict, payload_dict['zigbee'] )
if self.version_str in payload_dict:
_merge_payload_dicts( self.payload_dict, payload_dict[self.version_str] )
if self.children and ('gateway_'+self.version_str) in payload_dict:
_merge_payload_dicts( self.payload_dict, payload_dict['gateway_'+self.version_str] )
if self.cid and ('zigbee_'+self.version_str) in payload_dict:
_merge_payload_dicts( self.payload_dict, payload_dict['zigbee_'+self.version_str] )
if self.dev_type != 'default':
_merge_payload_dicts( self.payload_dict, payload_dict[self.dev_type] )
log.debug( 'final payload_dict for %r (%r/%r): %r', self.id, self.version_str, self.dev_type, self.payload_dict )
# save it so we don't have to calculate this again unless something changes
self.last_dev_type = self.dev_type
json_data = command_override = None
if command in self.payload_dict:
if 'command' in self.payload_dict[command]:
json_data = self.payload_dict[command]['command']
if 'command_override' in self.payload_dict[command]:
command_override = self.payload_dict[command]['command_override']
if command_override is None:
command_override = command
if json_data is None:
# I have yet to see a device complain about included but unneeded attribs, but they *will*
# complain about missing attribs, so just include them all unless otherwise specified
json_data = {"gwId": "", "devId": "", "uid": "", "t": ""}
# make sure we don't modify payload_dict
json_data = json_data.copy()
if "gwId" in json_data:
if gwId is not None:
json_data["gwId"] = gwId
elif self.parent:
json_data["gwId"] = self.parent.id
else:
json_data["gwId"] = self.id
if "devId" in json_data:
if devId is not None:
json_data["devId"] = devId
else:
json_data["devId"] = self.id
if "uid" in json_data:
if uid is not None:
json_data["uid"] = uid
else:
json_data["uid"] = self.id
if self.cid:
json_data["cid"] = self.cid
if "data" in json_data:
json_data["data"]["cid"] = self.cid
json_data["data"]["ctype"] = 0
#elif "cid" in json_data:
# del json_data['cid']
if "t" in json_data:
if json_data['t'] == "int":
json_data["t"] = int(time.time())
else:
json_data["t"] = str(int(time.time()))
if rawData is not None and "data" in json_data:
json_data["data"] = rawData
elif data is not None:
if "dpId" in json_data:
json_data["dpId"] = data
elif "data" in json_data:
json_data["data"]["dps"] = data
else:
json_data["dps"] = data
elif self.dev_type == "device22" and command == DP_QUERY:
json_data["dps"] = self.dps_to_request
if reqType and "reqType" in json_data:
json_data["reqType"] = reqType
# Create byte buffer from hex data
if json_data == "":
payload = ""
else:
payload = json.dumps(json_data)
# if spaces are not removed device does not respond!
payload = payload.replace(" ", "")
payload = payload.encode("utf-8")
log.debug("building command %s payload=%r", command, payload)
# create Tuya message packet
return MessagePayload(command_override, payload)
| (self, command, data=None, gwId=None, devId=None, uid=None, rawData=None, reqType=None) |
729,339 | tinytuya.core | heartbeat |
Send a keep-alive HEART_BEAT command to keep the TCP connection open.
Devices only send an empty-payload response, so no need to wait for it.
Args:
nowait(bool): True to send without waiting for response.
| def heartbeat(self, nowait=True):
"""
Send a keep-alive HEART_BEAT command to keep the TCP connection open.
Devices only send an empty-payload response, so no need to wait for it.
Args:
nowait(bool): True to send without waiting for response.
"""
# open device, send request, then close connection
payload = self.generate_payload(HEART_BEAT)
data = self._send_receive(payload, 0, getresponse=(not nowait))
log.debug("heartbeat received data=%r", data)
return data
| (self, nowait=True) |
729,340 | tinytuya.core | product |
Request AP_CONFIG Product Info from device. [BETA]
| def product(self):
"""
Request AP_CONFIG Product Info from device. [BETA]
"""
# open device, send request, then close connection
payload = self.generate_payload(AP_CONFIG)
data = self._send_receive(payload, 0)
log.debug("product received data=%r", data)
return data
| (self) |
729,341 | tinytuya.core | receive |
Poll device to read any payload in the buffer. Timeout results in None returned.
| def receive(self):
"""
Poll device to read any payload in the buffer. Timeout results in None returned.
"""
return self._send_receive(None)
| (self) |
729,342 | tinytuya.core | send |
Send single buffer `payload`.
Args:
payload(bytes): Data to send.
| def send(self, payload):
"""
Send single buffer `payload`.
Args:
payload(bytes): Data to send.
"""
return self._send_receive(payload, 0, getresponse=False)
| (self, payload) |
729,343 | tinytuya.BulbDevice | set_brightness |
Set the brightness value of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255).
nowait(bool): True to send without waiting for response.
| def set_brightness(self, brightness, nowait=False):
"""
Set the brightness value of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255).
nowait(bool): True to send without waiting for response.
"""
if self.bulb_type == "A" and not 25 <= brightness <= 255:
return error_json(
ERR_RANGE,
"set_brightness: The brightness needs to be between 25 and 255.",
)
if self.bulb_type == "B" and not 10 <= brightness <= 1000:
return error_json(
ERR_RANGE,
"set_brightness: The brightness needs to be between 10 and 1000.",
)
# Determine which mode bulb is in and adjust accordingly
state = self.state()
data = None
if "mode" in state:
if state["mode"] == "white":
# for white mode use DPS for brightness
if not self.has_brightness:
log.debug("set_brightness: Device does not appear to support brightness.")
# return error_json(ERR_FUNCTION, "set_brightness: Device does not support brightness.")
payload = self.generate_payload(
CONTROL, {self.DPS_INDEX_BRIGHTNESS[self.bulb_type]: brightness}
)
data = self._send_receive(payload, getresponse=(not nowait))
if state["mode"] == "colour":
# for colour mode use hsv to increase brightness
if self.bulb_type == "A":
value = brightness / 255.0
else:
value = brightness / 1000.0
(h, s, v) = self.colour_hsv()
data = self.set_hsv(h, s, value, nowait=nowait)
if data is not None or nowait is True:
return data
else:
return error_json(ERR_STATE, "set_brightness: Unknown bulb state.")
| (self, brightness, nowait=False) |
729,344 | tinytuya.BulbDevice | set_brightness_percentage |
Set the brightness value of an rgb bulb.
Args:
brightness(int): Value for the brightness in percent (0-100)
nowait(bool): True to send without waiting for response.
| def set_brightness_percentage(self, brightness=100, nowait=False):
"""
Set the brightness value of an rgb bulb.
Args:
brightness(int): Value for the brightness in percent (0-100)
nowait(bool): True to send without waiting for response.
"""
if not 0 <= brightness <= 100:
return error_json(
ERR_RANGE,
"set_brightness_percentage: Brightness percentage needs to be between 0 and 100.",
)
b = int(25 + (255 - 25) * brightness / 100)
if self.bulb_type == "B":
b = int(10 + (1000 - 10) * brightness / 100)
data = self.set_brightness(b, nowait=nowait)
return data
| (self, brightness=100, nowait=False) |
729,345 | tinytuya.BulbDevice | set_bulb_type | null | def set_bulb_type(self, type):
self.bulb_type = type
| (self, type) |
729,346 | tinytuya.BulbDevice | set_colour |
Set colour of an rgb bulb.
Args:
r(int): Value for the colour Red as int from 0-255.
g(int): Value for the colour Green as int from 0-255.
b(int): Value for the colour Blue as int from 0-255.
nowait(bool): True to send without waiting for response.
| def set_colour(self, r, g, b, nowait=False):
"""
Set colour of an rgb bulb.
Args:
r(int): Value for the colour Red as int from 0-255.
g(int): Value for the colour Green as int from 0-255.
b(int): Value for the colour Blue as int from 0-255.
nowait(bool): True to send without waiting for response.
"""
if not self.has_colour:
log.debug("set_colour: Device does not appear to support color.")
# return error_json(ERR_FUNCTION, "set_colour: Device does not support color.")
if not 0 <= r <= 255:
return error_json(
ERR_RANGE,
"set_colour: The value for red needs to be between 0 and 255.",
)
if not 0 <= g <= 255:
return error_json(
ERR_RANGE,
"set_colour: The value for green needs to be between 0 and 255.",
)
if not 0 <= b <= 255:
return error_json(
ERR_RANGE,
"set_colour: The value for blue needs to be between 0 and 255.",
)
hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b, self.bulb_type)
payload = self.generate_payload(
CONTROL,
{
self.DPS_INDEX_MODE[self.bulb_type]: self.DPS_MODE_COLOUR,
self.DPS_INDEX_COLOUR[self.bulb_type]: hexvalue,
},
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
| (self, r, g, b, nowait=False) |
729,347 | tinytuya.BulbDevice | set_colourtemp |
Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature (0-255).
nowait(bool): True to send without waiting for response.
| def set_colourtemp(self, colourtemp, nowait=False):
"""
Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature (0-255).
nowait(bool): True to send without waiting for response.
"""
if not self.has_colourtemp:
log.debug("set_colourtemp: Device does not appear to support colortemp.")
# return error_json(ERR_FUNCTION, "set_colourtemp: Device does not support colortemp.")
if self.bulb_type == "A" and not 0 <= colourtemp <= 255:
return error_json(
ERR_RANGE,
"set_colourtemp: The colour temperature needs to be between 0 and 255.",
)
if self.bulb_type == "B" and not 0 <= colourtemp <= 1000:
return error_json(
ERR_RANGE,
"set_colourtemp: The colour temperature needs to be between 0 and 1000.",
)
payload = self.generate_payload(
CONTROL, {self.DPS_INDEX_COLOURTEMP[self.bulb_type]: colourtemp}
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
| (self, colourtemp, nowait=False) |
729,348 | tinytuya.BulbDevice | set_colourtemp_percentage |
Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature in percentage (0-100).
nowait(bool): True to send without waiting for response.
| def set_colourtemp_percentage(self, colourtemp=100, nowait=False):
"""
Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature in percentage (0-100).
nowait(bool): True to send without waiting for response.
"""
if not 0 <= colourtemp <= 100:
return error_json(
ERR_RANGE,
"set_colourtemp_percentage: Colourtemp percentage needs to be between 0 and 100.",
)
c = int(255 * colourtemp / 100)
if self.bulb_type == "B":
c = int(1000 * colourtemp / 100)
data = self.set_colourtemp(c, nowait=nowait)
return data
| (self, colourtemp=100, nowait=False) |
729,349 | tinytuya.core | set_dpsUsed | null | def set_dpsUsed(self, dps_to_request):
self.dps_to_request = dps_to_request
| (self, dps_to_request) |
729,350 | tinytuya.BulbDevice | set_hsv |
Set colour of an rgb bulb using h, s, v.
Args:
h(float): colour Hue as float from 0-1
s(float): colour Saturation as float from 0-1
v(float): colour Value as float from 0-1
nowait(bool): True to send without waiting for response.
| def set_hsv(self, h, s, v, nowait=False):
"""
Set colour of an rgb bulb using h, s, v.
Args:
h(float): colour Hue as float from 0-1
s(float): colour Saturation as float from 0-1
v(float): colour Value as float from 0-1
nowait(bool): True to send without waiting for response.
"""
if not self.has_colour:
log.debug("set_hsv: Device does not appear to support color.")
# return error_json(ERR_FUNCTION, "set_hsv: Device does not support color.")
if not 0 <= h <= 1.0:
return error_json(
ERR_RANGE, "set_hsv: The value for Hue needs to be between 0 and 1."
)
if not 0 <= s <= 1.0:
return error_json(
ERR_RANGE,
"set_hsv: The value for Saturation needs to be between 0 and 1.",
)
if not 0 <= v <= 1.0:
return error_json(
ERR_RANGE,
"set_hsv: The value for Value needs to be between 0 and 1.",
)
(r, g, b) = colorsys.hsv_to_rgb(h, s, v)
hexvalue = BulbDevice._rgb_to_hexvalue(
r * 255.0, g * 255.0, b * 255.0, self.bulb_type
)
payload = self.generate_payload(
CONTROL,
{
self.DPS_INDEX_MODE[self.bulb_type]: self.DPS_MODE_COLOUR,
self.DPS_INDEX_COLOUR[self.bulb_type]: hexvalue,
},
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
| (self, h, s, v, nowait=False) |
729,351 | tinytuya.BulbDevice | set_mode |
Set bulb mode
Args:
mode(string): white,colour,scene,music
nowait(bool): True to send without waiting for response.
| def set_mode(self, mode="white", nowait=False):
"""
Set bulb mode
Args:
mode(string): white,colour,scene,music
nowait(bool): True to send without waiting for response.
"""
payload = self.generate_payload(
CONTROL, {self.DPS_INDEX_MODE[self.bulb_type]: mode}
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
| (self, mode='white', nowait=False) |
729,352 | tinytuya.core | set_multiple_values |
Set multiple indexes at the same time
Args:
data(dict): array of index/value pairs to set
nowait(bool): True to send without waiting for response.
| def set_multiple_values(self, data, nowait=False):
"""
Set multiple indexes at the same time
Args:
data(dict): array of index/value pairs to set
nowait(bool): True to send without waiting for response.
"""
out = {}
for i in data:
out[str(i)] = data[i]
payload = self.generate_payload(CONTROL, out)
return self._send_receive(payload, getresponse=(not nowait))
| (self, data, nowait=False) |
729,353 | tinytuya.core | set_retry | null | def set_retry(self, retry):
self.retry = retry
| (self, retry) |
729,354 | tinytuya.BulbDevice | set_scene |
Set to scene mode
Args:
scene(int): Value for the scene as int from 1-4.
nowait(bool): True to send without waiting for response.
| def set_scene(self, scene, nowait=False):
"""
Set to scene mode
Args:
scene(int): Value for the scene as int from 1-4.
nowait(bool): True to send without waiting for response.
"""
if not 1 <= scene <= 4:
return error_json(
ERR_RANGE, "set_scene: The value for scene needs to be between 1 and 4."
)
if scene == 1:
s = self.DPS_MODE_SCENE_1
elif scene == 2:
s = self.DPS_MODE_SCENE_2
elif scene == 3:
s = self.DPS_MODE_SCENE_3
else:
s = self.DPS_MODE_SCENE_4
payload = self.generate_payload(
CONTROL, {self.DPS_INDEX_MODE[self.bulb_type]: s}
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
| (self, scene, nowait=False) |
729,355 | tinytuya.core | set_sendWait | null | def set_sendWait(self, s):
self.sendWait = s
| (self, s) |
729,356 | tinytuya.core | set_socketNODELAY | null | def set_socketNODELAY(self, nodelay):
self.socketNODELAY = nodelay
if self.socket:
if nodelay:
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
else:
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 0)
| (self, nodelay) |
729,357 | tinytuya.core | set_socketPersistent | null | def set_socketPersistent(self, persist):
self.socketPersistent = persist
if self.socket and not persist:
self.socket.close()
self.socket = None
| (self, persist) |
729,358 | tinytuya.core | set_socketRetryDelay | null | def set_socketRetryDelay(self, delay):
self.socketRetryDelay = delay
| (self, delay) |
729,359 | tinytuya.core | set_socketRetryLimit | null | def set_socketRetryLimit(self, limit):
self.socketRetryLimit = limit
| (self, limit) |
729,360 | tinytuya.core | set_socketTimeout | null | def set_socketTimeout(self, s):
self.connection_timeout = s
if self.socket:
self.socket.settimeout(s)
| (self, s) |
729,361 | tinytuya.core | set_status |
Set status of the device to 'on' or 'off'.
Args:
on(bool): True for 'on', False for 'off'.
switch(int): The switch to set
nowait(bool): True to send without waiting for response.
| def set_status(self, on, switch=1, nowait=False):
"""
Set status of the device to 'on' or 'off'.
Args:
on(bool): True for 'on', False for 'off'.
switch(int): The switch to set
nowait(bool): True to send without waiting for response.
"""
# open device, send request, then close connection
if isinstance(switch, int):
switch = str(switch) # index and payload is a string
payload = self.generate_payload(CONTROL, {switch: on})
data = self._send_receive(payload, getresponse=(not nowait))
log.debug("set_status received data=%r", data)
return data
| (self, on, switch=1, nowait=False) |
729,362 | tinytuya.core | set_timer |
Set a timer.
Args:
num_secs(int): Number of seconds
dps_id(int): DPS Index for Timer
nowait(bool): True to send without waiting for response.
| def set_timer(self, num_secs, dps_id=0, nowait=False):
"""
Set a timer.
Args:
num_secs(int): Number of seconds
dps_id(int): DPS Index for Timer
nowait(bool): True to send without waiting for response.
"""
# Query status, pick last device id as that is probably the timer
if dps_id == 0:
status = self.status()
if "dps" in status:
devices = status["dps"]
devices_numbers = list(devices.keys())
devices_numbers.sort()
dps_id = devices_numbers[-1]
else:
log.debug("set_timer received error=%r", status)
return status
payload = self.generate_payload(CONTROL, {dps_id: num_secs})
data = self._send_receive(payload, getresponse=(not nowait))
log.debug("set_timer received data=%r", data)
return data
| (self, num_secs, dps_id=0, nowait=False) |
729,363 | tinytuya.core | set_value |
Set int value of any index.
Args:
index(int): index to set
value(int): new value for the index
nowait(bool): True to send without waiting for response.
| def set_value(self, index, value, nowait=False):
"""
Set int value of any index.
Args:
index(int): index to set
value(int): new value for the index
nowait(bool): True to send without waiting for response.
"""
# open device, send request, then close connection
if isinstance(index, int):
index = str(index) # index and payload is a string
payload = self.generate_payload(CONTROL, {index: value})
data = self._send_receive(payload, getresponse=(not nowait))
return data
| (self, index, value, nowait=False) |
729,364 | tinytuya.BulbDevice | set_version |
Set the Tuya device version 3.1 or 3.3 for BulbDevice
Attempt to determine BulbDevice Type: A or B based on:
Type A has keys 1-5 (default)
Type B has keys 20-29
Type C is Feit type bulbs from costco
| def set_version(self, version): # pylint: disable=W0621
"""
Set the Tuya device version 3.1 or 3.3 for BulbDevice
Attempt to determine BulbDevice Type: A or B based on:
Type A has keys 1-5 (default)
Type B has keys 20-29
Type C is Feit type bulbs from costco
"""
super(BulbDevice, self).set_version(version)
# Try to determine type of BulbDevice Type based on DPS indexes
status = self.status()
if status is not None:
if "dps" in status:
if "1" not in status["dps"]:
self.bulb_type = "B"
if self.DPS_INDEX_BRIGHTNESS[self.bulb_type] in status["dps"]:
self.has_brightness = True
if self.DPS_INDEX_COLOURTEMP[self.bulb_type] in status["dps"]:
self.has_colourtemp = True
if self.DPS_INDEX_COLOUR[self.bulb_type] in status["dps"]:
self.has_colour = True
else:
self.bulb_type = "B"
else:
# response has no dps
self.bulb_type = "B"
log.debug("bulb type set to %s", self.bulb_type)
| (self, version) |
729,365 | tinytuya.BulbDevice | set_white |
Set white coloured theme of an rgb bulb.
Args:
brightness(int): Value for the brightness (A:25-255 or B:10-1000)
colourtemp(int): Value for the colour temperature (A:0-255, B:0-1000).
nowait(bool): True to send without waiting for response.
Default: Max Brightness and Min Colourtemp
| def set_white(self, brightness=-1, colourtemp=-1, nowait=False):
"""
Set white coloured theme of an rgb bulb.
Args:
brightness(int): Value for the brightness (A:25-255 or B:10-1000)
colourtemp(int): Value for the colour temperature (A:0-255, B:0-1000).
nowait(bool): True to send without waiting for response.
Default: Max Brightness and Min Colourtemp
"""
# Brightness (default Max)
if brightness < 0:
brightness = 255
if self.bulb_type == "B":
brightness = 1000
if self.bulb_type == "A" and not 25 <= brightness <= 255:
return error_json(
ERR_RANGE, "set_white: The brightness needs to be between 25 and 255."
)
if self.bulb_type == "B" and not 10 <= brightness <= 1000:
return error_json(
ERR_RANGE, "set_white: The brightness needs to be between 10 and 1000."
)
# Colourtemp (default Min)
if colourtemp < 0:
colourtemp = 0
if self.bulb_type == "A" and not 0 <= colourtemp <= 255:
return error_json(
ERR_RANGE,
"set_white: The colour temperature needs to be between 0 and 255.",
)
if self.bulb_type == "B" and not 0 <= colourtemp <= 1000:
return error_json(
ERR_RANGE,
"set_white: The colour temperature needs to be between 0 and 1000.",
)
payload = self.generate_payload(
CONTROL,
{
self.DPS_INDEX_MODE[self.bulb_type]: self.DPS_MODE_WHITE,
self.DPS_INDEX_BRIGHTNESS[self.bulb_type]: brightness,
self.DPS_INDEX_COLOURTEMP[self.bulb_type]: colourtemp,
},
)
data = self._send_receive(payload, getresponse=(not nowait))
return data
| (self, brightness=-1, colourtemp=-1, nowait=False) |
729,366 | tinytuya.BulbDevice | set_white_percentage |
Set white coloured theme of an rgb bulb.
Args:
brightness(int): Value for the brightness in percent (0-100)
colourtemp(int): Value for the colour temperature in percent (0-100)
nowait(bool): True to send without waiting for response.
| def set_white_percentage(self, brightness=100, colourtemp=0, nowait=False):
"""
Set white coloured theme of an rgb bulb.
Args:
brightness(int): Value for the brightness in percent (0-100)
colourtemp(int): Value for the colour temperature in percent (0-100)
nowait(bool): True to send without waiting for response.
"""
# Brightness
if not 0 <= brightness <= 100:
return error_json(
ERR_RANGE,
"set_white_percentage: Brightness percentage needs to be between 0 and 100.",
)
b = int(25 + (255 - 25) * brightness / 100)
if self.bulb_type == "B":
b = int(10 + (1000 - 10) * brightness / 100)
# Colourtemp
if not 0 <= colourtemp <= 100:
return error_json(
ERR_RANGE,
"set_white_percentage: Colourtemp percentage needs to be between 0 and 100.",
)
c = int(255 * colourtemp / 100)
if self.bulb_type == "B":
c = int(1000 * colourtemp / 100)
data = self.set_white(b, c, nowait=nowait)
return data
| (self, brightness=100, colourtemp=0, nowait=False) |
729,367 | tinytuya.BulbDevice | state | Return state of Bulb | def state(self):
"""Return state of Bulb"""
status = self.status()
state = {}
if not status:
return error_json(ERR_JSON, "state: empty response")
if "Error" in status.keys():
return error_json(ERR_JSON, status["Error"])
if self.DPS not in status.keys():
return error_json(ERR_JSON, "state: no data points")
for key in status[self.DPS].keys():
if key in self.DPS_2_STATE:
state[self.DPS_2_STATE[key]] = status[self.DPS][key]
return state
| (self) |
729,368 | tinytuya.core | status | Return device status. | def status(self, nowait=False):
"""Return device status."""
query_type = DP_QUERY
log.debug("status() entry (dev_type is %s)", self.dev_type)
payload = self.generate_payload(query_type)
data = self._send_receive(payload, 0, getresponse=(not nowait))
log.debug("status() received data=%r", data)
# Error handling
if (not nowait) and data and "Err" in data:
if data["Err"] == str(ERR_DEVTYPE):
# Device22 detected and change - resend with new payload
log.debug("status() rebuilding payload for device22")
payload = self.generate_payload(query_type)
data = self._send_receive(payload)
elif data["Err"] == str(ERR_PAYLOAD):
log.debug("Status request returned an error, is version %r and local key %r correct?", self.version, self.local_key)
return data
| (self, nowait=False) |
729,369 | tinytuya.core | subdev_query | Query for a list of sub-devices and their status | def subdev_query( self, nowait=False ):
"""Query for a list of sub-devices and their status"""
# final payload should look like: {"data":{"cids":[]},"reqType":"subdev_online_stat_query"}
payload = self.generate_payload(LAN_EXT_STREAM, rawData={"cids":[]}, reqType='subdev_online_stat_query')
return self._send_receive(payload, 0, getresponse=(not nowait))
| (self, nowait=False) |
729,370 | tinytuya.BulbDevice | turn_off | Turn the device on | def turn_off(self, switch=0, nowait=False):
"""Turn the device on"""
if switch == 0:
switch = self.DPS_INDEX_ON[self.bulb_type]
self.set_status(False, switch, nowait=nowait)
| (self, switch=0, nowait=False) |
729,371 | tinytuya.BulbDevice | turn_on | Turn the device on | def turn_on(self, switch=0, nowait=False):
"""Turn the device on"""
if switch == 0:
switch = self.DPS_INDEX_ON[self.bulb_type]
self.set_status(True, switch, nowait=nowait)
| (self, switch=0, nowait=False) |
729,372 | tinytuya.core | updatedps |
Request device to update index.
Args:
index(array): list of dps to update (ex. [4, 5, 6, 18, 19, 20])
nowait(bool): True to send without waiting for response.
| def updatedps(self, index=None, nowait=False):
"""
Request device to update index.
Args:
index(array): list of dps to update (ex. [4, 5, 6, 18, 19, 20])
nowait(bool): True to send without waiting for response.
"""
if index is None:
index = [1]
log.debug("updatedps() entry (dev_type is %s)", self.dev_type)
# open device, send request, then close connection
payload = self.generate_payload(UPDATEDPS, index)
data = self._send_receive(payload, 0, getresponse=(not nowait))
log.debug("updatedps received data=%r", data)
return data
| (self, index=None, nowait=False) |
729,373 | tinytuya.Cloud | Cloud | null | class Cloud(object):
def __init__(self, apiRegion=None, apiKey=None, apiSecret=None, apiDeviceID=None, new_sign_algorithm=True, initial_token=None, **extrakw):
"""
Tuya Cloud IoT Platform Access
Args:
initial_token: The auth token from a previous run. It will be refreshed if it has expired
Playload Construction - Header Data:
Parameter Type Required Description
client_id String Yes client_id
signature String Yes HMAC-SHA256 Signature (see below)
sign_method String Yes Message-Digest Algorithm of the signature: HMAC-SHA256.
t Long Yes 13-bit standard timestamp (now in milliseconds).
lang String No Language. It is zh by default in China and en in other areas.
access_token String * Required for service management calls
Signature Details:
* OAuth Token Request: signature = HMAC-SHA256(KEY + t, SECRET).toUpperCase()
* Service Management: signature = HMAC-SHA256(KEY + access_token + t, SECRET).toUpperCase()
URIs:
* Get Token = https://openapi.tuyaus.com/v1.0/token?grant_type=1
* Get UserID = https://openapi.tuyaus.com/v1.0/devices/{DeviceID}
* Get Devices = https://openapi.tuyaus.com/v1.0/users/{UserID}/devices
REFERENCE:
* https://images.tuyacn.com/smart/docs/python_iot_code_sample.py
* https://iot.tuya.com/cloud/products/detail
"""
# Class Variables
self.CONFIGFILE = 'tinytuya.json'
self.apiRegion = apiRegion
self.apiKey = apiKey
self.apiSecret = apiSecret
self.apiDeviceID = apiDeviceID
self.urlhost = ''
self.uid = None # Tuya Cloud User ID
self.token = initial_token
self.error = None
self.new_sign_algorithm = new_sign_algorithm
self.server_time_offset = 0
self.use_old_device_list = True
self.mappings = None
if (not apiKey) or (not apiSecret):
try:
# Load defaults from config file if available
config = {}
with open(self.CONFIGFILE) as f:
config = json.load(f)
self.apiRegion = config['apiRegion']
self.apiKey = config['apiKey']
self.apiSecret = config['apiSecret']
if 'apiDeviceID' in config:
self.apiDeviceID = config['apiDeviceID']
except:
self.error = error_json(
ERR_CLOUDKEY,
"Tuya Cloud Key and Secret required",
)
#return self.error
raise TypeError('Tuya Cloud Key and Secret required') # pylint: disable=W0707
self.setregion(apiRegion)
if not self.token:
# Attempt to connect to cloud and get token
self._gettoken()
def setregion(self, apiRegion=None):
# Set hostname based on apiRegion
if apiRegion is None:
apiRegion = self.apiRegion
self.apiRegion = apiRegion.lower()
self.urlhost = "openapi.tuyacn.com" # China Data Center
if self.apiRegion == "us":
self.urlhost = "openapi.tuyaus.com" # Western America Data Center
if self.apiRegion == "us-e":
self.urlhost = "openapi-ueaz.tuyaus.com" # Eastern America Data Center
if self.apiRegion == "eu":
self.urlhost = "openapi.tuyaeu.com" # Central Europe Data Center
if self.apiRegion == "eu-w":
self.urlhost = "openapi-weaz.tuyaeu.com" # Western Europe Data Center
if self.apiRegion == "in":
self.urlhost = "openapi.tuyain.com" # India Datacenter
def _tuyaplatform(self, uri, action='GET', post=None, ver='v1.0', recursive=False, query=None, content_type=None):
"""
Handle GET and POST requests to Tuya Cloud
"""
# Build URL and Header
if ver:
url = "https://%s/%s/%s" % (self.urlhost, ver, uri)
elif uri[0] == '/':
url = "https://%s%s" % (self.urlhost, uri)
else:
url = "https://%s/%s" % (self.urlhost, uri)
headers = {}
body = {}
sign_url = url
if post is not None:
body = json.dumps(post)
if action not in ('GET', 'POST', 'PUT', 'DELETE'):
action = 'POST' if post else 'GET'
if action == 'POST' and content_type is None:
content_type = 'application/json'
if content_type:
headers['Content-type'] = content_type
if query:
# note: signature must be calculated before URL-encoding!
if type(query) == str:
# if it's a string then assume no url-encoding is needed
if query[0] == '?':
url += query
else:
url += '?' + query
sign_url = url
else:
# dicts are unsorted, however Tuya requires the keys to be in alphabetical order for signing
# as per https://developer.tuya.com/en/docs/iot/singnature?id=Ka43a5mtx1gsc
if type(query) == dict:
sorted_query = []
for k in sorted(query.keys()):
sorted_query.append( (k, query[k]) )
query = sorted_query
# calculate signature without url-encoding
sign_url += '?' + '&'.join( [str(x[0]) + '=' + str(x[1]) for x in query] )
req = requests.Request(action, url, params=query).prepare()
url = req.url
else:
req = requests.Request(action, url, params=query).prepare()
sign_url = url = req.url
now = int(time.time()*1000)
headers = dict(list(headers.items()) + [('Signature-Headers', ":".join(headers.keys()))]) if headers else {}
if self.token is None:
payload = self.apiKey + str(now)
headers['secret'] = self.apiSecret
else:
payload = self.apiKey + self.token + str(now)
# If running the post 6-30-2021 signing algorithm update the payload to include it's data
if self.new_sign_algorithm:
payload += ('%s\n' % action + # HTTPMethod
hashlib.sha256(bytes((body or "").encode('utf-8'))).hexdigest() + '\n' + # Content-SHA256
''.join(['%s:%s\n'%(key, headers[key]) # Headers
for key in headers.get("Signature-Headers", "").split(":")
if key in headers]) + '\n' +
'/' + sign_url.split('//', 1)[-1].split('/', 1)[-1])
# Sign Payload
signature = hmac.new(
self.apiSecret.encode('utf-8'),
msg=payload.encode('utf-8'),
digestmod=hashlib.sha256
).hexdigest().upper()
# Create Header Data
headers['client_id'] = self.apiKey
headers['sign'] = signature
headers['t'] = str(now)
headers['sign_method'] = 'HMAC-SHA256'
headers['mode'] = 'cors'
if self.token is not None:
headers['access_token'] = self.token
# Send Request to Cloud and Get Response
if action == 'GET':
response = requests.get(url, headers=headers)
log.debug(
"GET: URL=%s HEADERS=%s response code=%d text=%s token=%s", url, headers, response.status_code, response.text, self.token
)
else:
log.debug(
"POST: URL=%s HEADERS=%s DATA=%s", url, headers, body,
)
response = requests.post(url, headers=headers, data=body)
log.debug(
"POST RESPONSE: code=%d text=%s token=%s", response.status_code, response.text, self.token
)
# Check to see if token is expired
if "token invalid" in response.text:
if recursive is True:
log.debug("Failed 2nd attempt to renew token - Aborting")
return None
log.debug("Token Expired - Try to renew")
self._gettoken()
if not self.token:
log.debug("Failed to renew token")
return None
else:
return self._tuyaplatform(uri, action, post, ver, True)
try:
response_dict = json.loads(response.content.decode())
self.error = None
except:
try:
response_dict = json.loads(response.content)
except:
self.error = error_json(
ERR_CLOUDKEY,
"Cloud _tuyaplatform() invalid response: %r" % response.content,
)
return self.error
# Check to see if token is expired
return response_dict
def _gettoken(self):
# Get Oauth Token from tuyaPlatform
self.token = None
response_dict = self._tuyaplatform('token?grant_type=1')
if not response_dict or 'success' not in response_dict or not response_dict['success']:
self.error = error_json(
ERR_CLOUDTOKEN,
"Cloud _gettoken() failed: %r" % response_dict['msg'],
)
return self.error
if 't' in response_dict:
# round it to 2 minutes to try and factor out any processing delays
self.server_time_offset = round( ((response_dict['t'] / 1000.0) - time.time()) / 120 )
self.server_time_offset *= 120
log.debug("server_time_offset: %r", self.server_time_offset)
self.token = response_dict['result']['access_token']
return self.token
def _getuid(self, deviceid=None):
# Get user ID (UID) for deviceid
if not self.token:
return self.error
if not deviceid:
return error_json(
ERR_PARAMS,
"_getuid() requires deviceID parameter"
)
uri = 'devices/%s' % deviceid
response_dict = self._tuyaplatform(uri)
if not response_dict['success']:
if 'code' not in response_dict:
response_dict['code'] = -1
if 'msg' not in response_dict:
response_dict['msg'] = 'Unknown Error'
log.debug(
"Error from Tuya Cloud: %r", response_dict['msg'],
)
return error_json(
ERR_CLOUD,
"Error from Tuya Cloud: Code %r: %r" % (response_dict['code'], response_dict['msg'])
)
uid = response_dict['result']['uid']
return uid
def cloudrequest(self, url, action=None, post=None, query=None):
"""
Make a generic cloud request and return the results.
Args:
url: Required. The URL to fetch, i.e. "/v1.0/devices/0011223344556677/logs"
action: Optional. GET, POST, DELETE, or PUT. Defaults to GET, unless POST data is supplied.
post: Optional. POST body data. Will be fed into json.dumps() before posting.
query: Optional. A dict containing query string key/value pairs.
"""
if not self.token:
return self.error
if action is None:
action = 'POST' if post else 'GET'
return self._tuyaplatform(url, action=action, post=post, ver=None, query=query)
# merge device list 'result2' into 'result1'
# if result2 has a device which is not in result1 then it will be added
# if result2 has a key which does not exist or is empty in result1 then that key will be copied over
def _update_device_list( self, result1, result2 ):
for new_device in result2:
if 'id' not in new_device or not new_device['id']:
continue
found = False
for existing_device in result1:
if 'id' in existing_device and existing_device['id'] == new_device['id']:
found = True
for k in new_device:
if k not in existing_device or not existing_device[k]:
existing_device[k] = new_device[k]
if not found:
result1.append( new_device )
def _get_all_devices( self, uid=None, device_ids=None ):
fetches = 0
our_result = { 'result': [] }
last_row_key = None
has_more = True
total = 0
if uid:
# get device list for specified user id
query = {'page_size':'75', 'source_type': 'tuyaUser', 'source_id': uid}
# API docu: https://developer.tuya.com/en/docs/cloud/dc413408fe?id=Kc09y2ons2i3b
uri = '/v1.3/iot-03/devices'
if device_ids:
if isinstance( device_ids, tuple ) or isinstance( device_ids, list ):
query['device_ids'] = ','.join(device_ids)
else:
query['device_ids'] = device_ids
else:
# get all devices
query = {'size':'50'}
# API docu: https://developer.tuya.com/en/docs/cloud/fc19523d18?id=Kakr4p8nq5xsc
uri = '/v1.0/iot-01/associated-users/devices'
while has_more:
result = self.cloudrequest( uri, query=query )
fetches += 1
has_more = False
if type(result) == dict:
log.debug( 'Cloud response:' )
log.debug( json.dumps( result, indent=2 ) )
else:
log.debug( 'Cloud response: %r', result )
# format it the same as before, basically just moves result->devices into result
for i in result:
if i == 'result':
# by-user-id has the result in 'list' while all-devices has it in 'devices'
if 'list' in result[i] and 'devices' not in result[i]:
our_result[i] += result[i]['list']
elif 'devices' in result[i]:
our_result[i] += result[i]['devices']
if 'total' in result[i]: total = result[i]['total']
if 'last_row_key' in result[i]:
query['last_row_key'] = result[i]['last_row_key']
if 'has_more' in result[i]:
has_more = result[i]['has_more']
else:
our_result[i] = result[i]
our_result['fetches'] = fetches
our_result['total'] = total
return our_result
def getdevices(self, verbose=False, oldlist=[], include_map=False):
"""
Return dictionary of all devices.
If verbose is true, return full Tuya device
details.
"""
old_devices = {}
if oldlist:
for dev in oldlist:
dev_id = dev['id']
old_devices[dev_id] = dev
if self.apiDeviceID and self.use_old_device_list:
json_data = {}
uid_list = {}
# apiDeviceID can be a comma-separated list, so process them all
for dev_id in self.apiDeviceID.split(','):
dev_id = dev_id.strip()
if not dev_id:
continue
uid = self._getuid( dev_id )
if not uid:
# no user for this device?
continue
if isinstance( uid, dict ):
# it's an error_json dict
return uid
else:
uid_list[uid] = True
if not uid_list:
return error_json(
ERR_CLOUD,
"Unable to get uid for device list"
)
for uid in uid_list:
# Use UID to get list of all Devices for User
uri = 'users/%s/devices' % uid
json_run = self._tuyaplatform(uri)
# merge the dicts
for k in json_run:
if (k not in json_data) or (k != 'result'):
# replace if key is not 'result'
json_data[k] = json_run[k]
else:
# merge 'result' keys
json_data[k] += json_run[k]
else:
json_data = self._get_all_devices()
users = {}
# loop through all devices and build a list of user IDs
for dev in json_data['result']:
if 'uid' in dev:
users[dev['uid']] = True
if users:
# we have at least 1 user id, so fetch the device list again to make sure we have the local key
# this also gets us the gateway_id for child devices
for uid in users.keys():
json_data2 = self._get_all_devices( uid=uid )
self._update_device_list( json_data['result'], json_data2['result'] )
if verbose:
return json_data
elif not json_data or 'result' not in json_data:
return error_json(
ERR_CLOUD,
"Unable to get device list"
)
self.getdevices_raw = json_data
devs = json_data['result']
changed_devices = []
unchanged_devices = []
# check to see if anything has changed. if so, re-download factory-infos and DP mapping
for dev in devs:
dev_id = dev['id']
if dev_id not in old_devices:
# newly-added device
changed_devices.append( dev )
continue
old = old_devices[dev_id]
if 'key' not in old or old['key'] != dev['local_key']:
# local key changed
changed_devices.append( dev )
continue
if (('icon' not in old) and ('icon' in dev)) or (include_map and ('mapping' not in old or old['mapping'] is None)):
# icon or mapping added
changed_devices.append( dev )
continue
is_same = True
for k in DEVICEFILE_SAVE_VALUES:
if k in dev and k != 'icon' and k != 'last_ip' and (k not in old or old[k] != dev[k]):
is_same = False
break
if not is_same:
changed_devices.append( dev )
continue
unchanged_devices.append( old )
if include_map:
mappings = self.getmappings( changed_devices )
for productid in mappings:
for dev in changed_devices:
if 'product_id' in dev and dev['product_id'] == productid:
dev['mapping'] = mappings[productid]
# also set unchanged devices just in case the mapping changed
for dev in unchanged_devices:
if 'product_id' in dev and dev['product_id'] == productid:
dev['mapping'] = mappings[productid]
log.debug( 'changed: %d', len(changed_devices) )
log.debug( 'unchanged: %d', len(unchanged_devices) )
# Filter to only Name, ID and Key
return self.filter_devices( changed_devices ) + unchanged_devices
def _get_hw_addresses( self, maclist, devices ):
while devices:
# returns id, mac, uuid (and sn if available)
uri = 'devices/factory-infos?device_ids=%s' % (",".join(devices[:50]))
result = self._tuyaplatform(uri)
log.debug( json.dumps( result, indent=2 ) )
if 'result' in result:
for dev in result['result']:
if 'id' in dev:
dev_id = dev['id']
del dev['id']
maclist[dev_id] = dev
devices = devices[50:]
def filter_devices( self, devs, ip_list=None ):
json_mac_data = {}
# mutable json_mac_data will be modified
self._get_hw_addresses( json_mac_data, [i['id'] for i in devs] )
tuyadevices = []
icon_host = 'https://images.' + self.urlhost.split( '.', 1 )[1] + '/'
for i in devs:
dev_id = i['id']
item = {
'name': '' if 'name' not in i else i['name'].strip(),
'id': dev_id,
'key': '' if 'local_key' not in i else i['local_key'],
'mac': '' if 'mac' not in i else i['mac']
}
if dev_id in json_mac_data:
for k in ('mac','uuid','sn'):
if k in json_mac_data[dev_id]:
item[k] = json_mac_data[dev_id][k]
if ip_list and 'mac' in item and item['mac'] in ip_list:
item['ip'] = ip_list[item['mac']]
for k in DEVICEFILE_SAVE_VALUES:
if k in i:
if k == 'icon':
item[k] = icon_host + i[k]
else:
item[k] = i[k]
if 'gateway_id' in i:
k = 'gateway_id'
item[k] = i[k]
tuyadevices.append(item)
return tuyadevices
def _getdevice(self, param='status', deviceid=None):
if not self.token:
return self.error
if not deviceid:
return error_json(
ERR_PARAMS,
"Missing DeviceID Parameter"
)
uri = 'iot-03/devices/%s/%s' % (deviceid, param)
response_dict = self._tuyaplatform(uri)
if not response_dict['success']:
log.debug(
"Error from Tuya Cloud: %r", response_dict['msg'],
)
return response_dict
def getstatus(self, deviceid=None):
"""
Get the status of the device.
"""
return self._getdevice('status', deviceid)
def getfunctions(self, deviceid=None):
"""
Get the functions of the device.
"""
return self._getdevice('functions', deviceid)
def getproperties(self, deviceid=None):
"""
Get the properties of the device.
"""
return self._getdevice('specification', deviceid)
def getdps(self, deviceid=None):
"""
Get the specifications including DPS IDs of the device.
"""
if not self.token:
return self.error
if not deviceid:
return error_json(
ERR_PARAMS,
"Missing DeviceID Parameter"
)
uri = 'devices/%s/specifications' % (deviceid)
response_dict = self._tuyaplatform(uri, ver='v1.1')
if not response_dict['success']:
log.debug(
"Error from Tuya Cloud: %r", response_dict['msg'],
)
return response_dict
def sendcommand(self, deviceid=None, commands=None, uri='iot-03/devices/'):
"""
Send a command to the device
"""
if not self.token:
return self.error
if (not deviceid) or (not commands):
return error_json(
ERR_PARAMS,
"Missing DeviceID and/or Command Parameters"
)
uri += '%s/commands' % (deviceid)
response_dict = self._tuyaplatform(uri,action='POST',post=commands)
if not response_dict['success']:
log.debug(
"Error from Tuya Cloud: %r", response_dict['msg'],
)
return response_dict
def getconnectstatus(self, deviceid=None):
"""
Get the device Cloud connect status.
"""
if not self.token:
return self.error
if not deviceid:
return error_json(
ERR_PARAMS,
"Missing DeviceID Parameter"
)
uri = 'devices/%s' % (deviceid)
response_dict = self._tuyaplatform(uri, ver='v1.0')
if not response_dict['success']:
log.debug("Error from Tuya Cloud: %r", response_dict['msg'])
return(response_dict["result"]["online"])
def getdevicelog(self, deviceid=None, start=None, end=None, evtype=None, size=0, max_fetches=50, start_row_key=None, params=None):
"""
Get the logs for a device.
https://developer.tuya.com/en/docs/cloud/0a30fc557f?id=Ka7kjybdo0jse
Note: The cloud only returns logs for DPs in the "official" DPS list.
If the device specifications are wrong then not all logs will be returned!
This is a limitation of Tuya's servers and there is nothing we can do about it.
Args:
devid: Required. Device ID
start: Optional. Get logs starting from this time. Defaults to yesterday
end: Optional. Get logs until this time. Defaults to the current time
evtype: Optional. Limit to events of this type. 1 = Online, 7 = DP Reports. Defaults to all events.
size: Optional. Target number of log entries to return. Defaults to 0 (all, up to max_fetches*100).
Actual number of log entries returned will be between "0" and "size * 2 - 1"
max_fetches: Optional. Maximum number of queries to send to the server. Tuya's server has a hard limit
of 100 records per query, so the maximum number of logs returned is "max_fetches * 100"
start_row_key: Optional. The "next_row_key" from a previous run.
params: Optional. Additional values to include in the query string. Defaults to an empty dict.
Returns:
Response from server
"""
if not deviceid:
return error_json(
ERR_PARAMS,
"Missing DeviceID Parameter"
)
# server expects times as unixtime * 1000
if not end:
end = int((time.time() + self.server_time_offset) * 1000)
elif end < 0:
end = int(((time.time() + self.server_time_offset) + (end * 86400) ) * 1000)
else:
end = Cloud.format_timestamp( end )
if not start:
start = end - (86400*1000)
elif start < 0:
start = int(((time.time() + self.server_time_offset) + (start * 86400) ) * 1000)
else:
start = Cloud.format_timestamp( start )
if start > end:
tmp = start
start = end
end = tmp
if not evtype:
# get them all by default
# 1 = device online, 7 = DP report
evtype = '1,2,3,4,5,6,7,8,9,10'
elif type(evtype) == str:
pass
elif type(evtype) == bytes:
evtype = evtype.decode('utf8')
elif type(evtype) == int:
evtype = str(evtype)
elif type(evtype) == list or type(evtype) == tuple:
evtype = ','.join( [str(i) for i in evtype] )
else:
raise ValueError( "Unhandled 'evtype' type %s - %r" % (type(evtype), evtype) )
want_size = size
if not size:
size = 100
elif size > 100:
size = 100
#if (want_size / size) * 2 > max_fetches:
# max_fetches = round( (want_size / size) * 2 ) + 1
if not max_fetches or max_fetches < 1:
max_fetches = 50
params = {} if type(params) != dict else params.copy()
if 'start_time' not in params:
params['start_time'] = start
if 'end_time' not in params:
params['end_time'] = end
if 'type' not in params:
params['type'] = evtype
if 'size' not in params:
params['size'] = size
if 'query_type' not in params:
params['query_type'] = 1
if start_row_key:
params['start_row_key'] = start_row_key
ret = self.cloudrequest( '/v1.0/devices/%s/logs' % deviceid, query=params)
max_fetches -= 1
fetches = 1
if ret and 'result' in ret:
# ret['result'] is a dict so the 'result' below will be a reference, not a copy
result = ret['result']
again = True
next_row_key = ''
while (
again and max_fetches and
'logs' in result and
'has_next' in result and result['has_next'] and
(not want_size or len(result['logs']) < size) and
'next_row_key' in result and result['next_row_key'] and next_row_key != result['next_row_key']
):
again = False
max_fetches -= 1
fetches += 1
params['start_row_key'] = result['next_row_key']
next_row_key = result['next_row_key']
result['next_row_key'] = None
result['has_next'] = False
res = self.cloudrequest( '/v1.0/devices/%s/logs' % deviceid, query=params)
if res and 'result' in res:
result2 = res['result']
if 'logs' in result2:
result['logs'] += result2['logs']
again = True
if 'has_next' in result2:
result['has_next'] = result2['has_next']
if 'next_row_key' in result2:
result['next_row_key'] = result2['next_row_key']
else:
break
ret['fetches'] = fetches
return ret
@staticmethod
def format_timestamp( ts ):
# converts a 10-digit unix timestamp to the 13-digit stamp the servers expect
if type(ts) != int:
if len(str(int(ts))) == 10:
ts = int( ts * 1000 )
else:
ts = int( ts )
elif len(str(ts)) == 10:
ts *= 1000
return ts
@staticmethod
def _build_mapping( src, dst ):
# merge multiple DPS sets from result['status'] and result['functions'] into a single result
for mapp in src:
try:
code = mapp['code']
dp_id = code if 'dp_id' not in mapp else str(mapp['dp_id'])
if dp_id in dst:
continue
data = { 'code': code, 'type': mapp['type'] }
if mapp['type'].lower() == 'string':
values = mapp['values']
else:
try:
values = json.loads( mapp['values'] )
except:
values = mapp['values']
if values and type(values) == dict and 'unit' in values:
if values['unit']:
# normalize some unicode and temperature units
# not sure what a good replacement for '份' is (seen in a pet feeder)
values['unit'] = values['unit'].replace('℉','°F').replace('℃','°C').replace('f','°F').replace('c','°C').replace('秒','s')
# Tuya's 'JSON' mapping type is an ordered dict, but python's dict is not! so, save the raw value as well
if mapp['type'].lower() == 'json':
data['raw_values'] = mapp['values']
data['values'] = values
dst[dp_id] = data
except:
log.debug( 'Parse mapping item failed!', exc_info=True )
def getmapping( self, productid, deviceid=None ):
# return a mapping for the given product id, or download it from the cloud using a device id
# Return value: None on failure, or a dict on success (may be an empty dict if device does not have DPs)
if not self.mappings:
self.mappings = {} #load_mappings()
if productid in self.mappings:
# already have this product id, so just return it
return self.mappings[productid]
if deviceid:
# we do not have this product id yet, so download it via this device id
result = self.getdps(deviceid)
if result:
if 'result' in result:
result = result['result']
dps = {}
# merge result['status'] and result['functions'] into a single result
if 'status' in result:
self._build_mapping( result['status'], dps )
if 'functions' in result:
self._build_mapping( result['functions'], dps )
self.mappings[productid] = dps
log.debug( 'Downloaded mapping for device %r: %r', deviceid, dps)
elif ('code' in result and result['code'] == 2009) or ('msg' in result and result['msg'] == 'not support this device'):
# this device does not have any DPs!
self.mappings[productid] = {}
if productid in self.mappings:
# download success, so return it
return self.mappings[productid]
# no device id, or download failed
return None
def setmappings( self, mappings ):
# sets an initial mapping set so we do not need to download everything
if type(mappings) == dict:
self.mappings = mappings
def getmappings( self, devices ):
# get all mappings for all tuya devices
# returns a dict with product ids as keys
if not self.mappings:
self.mappings = {}
for dev in devices:
try:
devid = dev['id']
productid = dev['product_id']
except:
# we need both the device id and the product id to download mappings!
continue
if productid not in self.mappings:
self.getmapping( productid, devid )
return self.mappings
| (apiRegion=None, apiKey=None, apiSecret=None, apiDeviceID=None, new_sign_algorithm=True, initial_token=None, **extrakw) |
729,374 | tinytuya.Cloud | __init__ |
Tuya Cloud IoT Platform Access
Args:
initial_token: The auth token from a previous run. It will be refreshed if it has expired
Playload Construction - Header Data:
Parameter Type Required Description
client_id String Yes client_id
signature String Yes HMAC-SHA256 Signature (see below)
sign_method String Yes Message-Digest Algorithm of the signature: HMAC-SHA256.
t Long Yes 13-bit standard timestamp (now in milliseconds).
lang String No Language. It is zh by default in China and en in other areas.
access_token String * Required for service management calls
Signature Details:
* OAuth Token Request: signature = HMAC-SHA256(KEY + t, SECRET).toUpperCase()
* Service Management: signature = HMAC-SHA256(KEY + access_token + t, SECRET).toUpperCase()
URIs:
* Get Token = https://openapi.tuyaus.com/v1.0/token?grant_type=1
* Get UserID = https://openapi.tuyaus.com/v1.0/devices/{DeviceID}
* Get Devices = https://openapi.tuyaus.com/v1.0/users/{UserID}/devices
REFERENCE:
* https://images.tuyacn.com/smart/docs/python_iot_code_sample.py
* https://iot.tuya.com/cloud/products/detail
| def __init__(self, apiRegion=None, apiKey=None, apiSecret=None, apiDeviceID=None, new_sign_algorithm=True, initial_token=None, **extrakw):
"""
Tuya Cloud IoT Platform Access
Args:
initial_token: The auth token from a previous run. It will be refreshed if it has expired
Playload Construction - Header Data:
Parameter Type Required Description
client_id String Yes client_id
signature String Yes HMAC-SHA256 Signature (see below)
sign_method String Yes Message-Digest Algorithm of the signature: HMAC-SHA256.
t Long Yes 13-bit standard timestamp (now in milliseconds).
lang String No Language. It is zh by default in China and en in other areas.
access_token String * Required for service management calls
Signature Details:
* OAuth Token Request: signature = HMAC-SHA256(KEY + t, SECRET).toUpperCase()
* Service Management: signature = HMAC-SHA256(KEY + access_token + t, SECRET).toUpperCase()
URIs:
* Get Token = https://openapi.tuyaus.com/v1.0/token?grant_type=1
* Get UserID = https://openapi.tuyaus.com/v1.0/devices/{DeviceID}
* Get Devices = https://openapi.tuyaus.com/v1.0/users/{UserID}/devices
REFERENCE:
* https://images.tuyacn.com/smart/docs/python_iot_code_sample.py
* https://iot.tuya.com/cloud/products/detail
"""
# Class Variables
self.CONFIGFILE = 'tinytuya.json'
self.apiRegion = apiRegion
self.apiKey = apiKey
self.apiSecret = apiSecret
self.apiDeviceID = apiDeviceID
self.urlhost = ''
self.uid = None # Tuya Cloud User ID
self.token = initial_token
self.error = None
self.new_sign_algorithm = new_sign_algorithm
self.server_time_offset = 0
self.use_old_device_list = True
self.mappings = None
if (not apiKey) or (not apiSecret):
try:
# Load defaults from config file if available
config = {}
with open(self.CONFIGFILE) as f:
config = json.load(f)
self.apiRegion = config['apiRegion']
self.apiKey = config['apiKey']
self.apiSecret = config['apiSecret']
if 'apiDeviceID' in config:
self.apiDeviceID = config['apiDeviceID']
except:
self.error = error_json(
ERR_CLOUDKEY,
"Tuya Cloud Key and Secret required",
)
#return self.error
raise TypeError('Tuya Cloud Key and Secret required') # pylint: disable=W0707
self.setregion(apiRegion)
if not self.token:
# Attempt to connect to cloud and get token
self._gettoken()
| (self, apiRegion=None, apiKey=None, apiSecret=None, apiDeviceID=None, new_sign_algorithm=True, initial_token=None, **extrakw) |
729,375 | tinytuya.Cloud | _build_mapping | null | @staticmethod
def _build_mapping( src, dst ):
# merge multiple DPS sets from result['status'] and result['functions'] into a single result
for mapp in src:
try:
code = mapp['code']
dp_id = code if 'dp_id' not in mapp else str(mapp['dp_id'])
if dp_id in dst:
continue
data = { 'code': code, 'type': mapp['type'] }
if mapp['type'].lower() == 'string':
values = mapp['values']
else:
try:
values = json.loads( mapp['values'] )
except:
values = mapp['values']
if values and type(values) == dict and 'unit' in values:
if values['unit']:
# normalize some unicode and temperature units
# not sure what a good replacement for '份' is (seen in a pet feeder)
values['unit'] = values['unit'].replace('℉','°F').replace('℃','°C').replace('f','°F').replace('c','°C').replace('秒','s')
# Tuya's 'JSON' mapping type is an ordered dict, but python's dict is not! so, save the raw value as well
if mapp['type'].lower() == 'json':
data['raw_values'] = mapp['values']
data['values'] = values
dst[dp_id] = data
except:
log.debug( 'Parse mapping item failed!', exc_info=True )
| (src, dst) |
729,376 | tinytuya.Cloud | _get_all_devices | null | def _get_all_devices( self, uid=None, device_ids=None ):
fetches = 0
our_result = { 'result': [] }
last_row_key = None
has_more = True
total = 0
if uid:
# get device list for specified user id
query = {'page_size':'75', 'source_type': 'tuyaUser', 'source_id': uid}
# API docu: https://developer.tuya.com/en/docs/cloud/dc413408fe?id=Kc09y2ons2i3b
uri = '/v1.3/iot-03/devices'
if device_ids:
if isinstance( device_ids, tuple ) or isinstance( device_ids, list ):
query['device_ids'] = ','.join(device_ids)
else:
query['device_ids'] = device_ids
else:
# get all devices
query = {'size':'50'}
# API docu: https://developer.tuya.com/en/docs/cloud/fc19523d18?id=Kakr4p8nq5xsc
uri = '/v1.0/iot-01/associated-users/devices'
while has_more:
result = self.cloudrequest( uri, query=query )
fetches += 1
has_more = False
if type(result) == dict:
log.debug( 'Cloud response:' )
log.debug( json.dumps( result, indent=2 ) )
else:
log.debug( 'Cloud response: %r', result )
# format it the same as before, basically just moves result->devices into result
for i in result:
if i == 'result':
# by-user-id has the result in 'list' while all-devices has it in 'devices'
if 'list' in result[i] and 'devices' not in result[i]:
our_result[i] += result[i]['list']
elif 'devices' in result[i]:
our_result[i] += result[i]['devices']
if 'total' in result[i]: total = result[i]['total']
if 'last_row_key' in result[i]:
query['last_row_key'] = result[i]['last_row_key']
if 'has_more' in result[i]:
has_more = result[i]['has_more']
else:
our_result[i] = result[i]
our_result['fetches'] = fetches
our_result['total'] = total
return our_result
| (self, uid=None, device_ids=None) |
729,377 | tinytuya.Cloud | _get_hw_addresses | null | def _get_hw_addresses( self, maclist, devices ):
while devices:
# returns id, mac, uuid (and sn if available)
uri = 'devices/factory-infos?device_ids=%s' % (",".join(devices[:50]))
result = self._tuyaplatform(uri)
log.debug( json.dumps( result, indent=2 ) )
if 'result' in result:
for dev in result['result']:
if 'id' in dev:
dev_id = dev['id']
del dev['id']
maclist[dev_id] = dev
devices = devices[50:]
| (self, maclist, devices) |
729,378 | tinytuya.Cloud | _getdevice | null | def _getdevice(self, param='status', deviceid=None):
if not self.token:
return self.error
if not deviceid:
return error_json(
ERR_PARAMS,
"Missing DeviceID Parameter"
)
uri = 'iot-03/devices/%s/%s' % (deviceid, param)
response_dict = self._tuyaplatform(uri)
if not response_dict['success']:
log.debug(
"Error from Tuya Cloud: %r", response_dict['msg'],
)
return response_dict
| (self, param='status', deviceid=None) |
729,379 | tinytuya.Cloud | _gettoken | null | def _gettoken(self):
# Get Oauth Token from tuyaPlatform
self.token = None
response_dict = self._tuyaplatform('token?grant_type=1')
if not response_dict or 'success' not in response_dict or not response_dict['success']:
self.error = error_json(
ERR_CLOUDTOKEN,
"Cloud _gettoken() failed: %r" % response_dict['msg'],
)
return self.error
if 't' in response_dict:
# round it to 2 minutes to try and factor out any processing delays
self.server_time_offset = round( ((response_dict['t'] / 1000.0) - time.time()) / 120 )
self.server_time_offset *= 120
log.debug("server_time_offset: %r", self.server_time_offset)
self.token = response_dict['result']['access_token']
return self.token
| (self) |
729,380 | tinytuya.Cloud | _getuid | null | def _getuid(self, deviceid=None):
# Get user ID (UID) for deviceid
if not self.token:
return self.error
if not deviceid:
return error_json(
ERR_PARAMS,
"_getuid() requires deviceID parameter"
)
uri = 'devices/%s' % deviceid
response_dict = self._tuyaplatform(uri)
if not response_dict['success']:
if 'code' not in response_dict:
response_dict['code'] = -1
if 'msg' not in response_dict:
response_dict['msg'] = 'Unknown Error'
log.debug(
"Error from Tuya Cloud: %r", response_dict['msg'],
)
return error_json(
ERR_CLOUD,
"Error from Tuya Cloud: Code %r: %r" % (response_dict['code'], response_dict['msg'])
)
uid = response_dict['result']['uid']
return uid
| (self, deviceid=None) |
729,381 | tinytuya.Cloud | _tuyaplatform |
Handle GET and POST requests to Tuya Cloud
| def _tuyaplatform(self, uri, action='GET', post=None, ver='v1.0', recursive=False, query=None, content_type=None):
"""
Handle GET and POST requests to Tuya Cloud
"""
# Build URL and Header
if ver:
url = "https://%s/%s/%s" % (self.urlhost, ver, uri)
elif uri[0] == '/':
url = "https://%s%s" % (self.urlhost, uri)
else:
url = "https://%s/%s" % (self.urlhost, uri)
headers = {}
body = {}
sign_url = url
if post is not None:
body = json.dumps(post)
if action not in ('GET', 'POST', 'PUT', 'DELETE'):
action = 'POST' if post else 'GET'
if action == 'POST' and content_type is None:
content_type = 'application/json'
if content_type:
headers['Content-type'] = content_type
if query:
# note: signature must be calculated before URL-encoding!
if type(query) == str:
# if it's a string then assume no url-encoding is needed
if query[0] == '?':
url += query
else:
url += '?' + query
sign_url = url
else:
# dicts are unsorted, however Tuya requires the keys to be in alphabetical order for signing
# as per https://developer.tuya.com/en/docs/iot/singnature?id=Ka43a5mtx1gsc
if type(query) == dict:
sorted_query = []
for k in sorted(query.keys()):
sorted_query.append( (k, query[k]) )
query = sorted_query
# calculate signature without url-encoding
sign_url += '?' + '&'.join( [str(x[0]) + '=' + str(x[1]) for x in query] )
req = requests.Request(action, url, params=query).prepare()
url = req.url
else:
req = requests.Request(action, url, params=query).prepare()
sign_url = url = req.url
now = int(time.time()*1000)
headers = dict(list(headers.items()) + [('Signature-Headers', ":".join(headers.keys()))]) if headers else {}
if self.token is None:
payload = self.apiKey + str(now)
headers['secret'] = self.apiSecret
else:
payload = self.apiKey + self.token + str(now)
# If running the post 6-30-2021 signing algorithm update the payload to include it's data
if self.new_sign_algorithm:
payload += ('%s\n' % action + # HTTPMethod
hashlib.sha256(bytes((body or "").encode('utf-8'))).hexdigest() + '\n' + # Content-SHA256
''.join(['%s:%s\n'%(key, headers[key]) # Headers
for key in headers.get("Signature-Headers", "").split(":")
if key in headers]) + '\n' +
'/' + sign_url.split('//', 1)[-1].split('/', 1)[-1])
# Sign Payload
signature = hmac.new(
self.apiSecret.encode('utf-8'),
msg=payload.encode('utf-8'),
digestmod=hashlib.sha256
).hexdigest().upper()
# Create Header Data
headers['client_id'] = self.apiKey
headers['sign'] = signature
headers['t'] = str(now)
headers['sign_method'] = 'HMAC-SHA256'
headers['mode'] = 'cors'
if self.token is not None:
headers['access_token'] = self.token
# Send Request to Cloud and Get Response
if action == 'GET':
response = requests.get(url, headers=headers)
log.debug(
"GET: URL=%s HEADERS=%s response code=%d text=%s token=%s", url, headers, response.status_code, response.text, self.token
)
else:
log.debug(
"POST: URL=%s HEADERS=%s DATA=%s", url, headers, body,
)
response = requests.post(url, headers=headers, data=body)
log.debug(
"POST RESPONSE: code=%d text=%s token=%s", response.status_code, response.text, self.token
)
# Check to see if token is expired
if "token invalid" in response.text:
if recursive is True:
log.debug("Failed 2nd attempt to renew token - Aborting")
return None
log.debug("Token Expired - Try to renew")
self._gettoken()
if not self.token:
log.debug("Failed to renew token")
return None
else:
return self._tuyaplatform(uri, action, post, ver, True)
try:
response_dict = json.loads(response.content.decode())
self.error = None
except:
try:
response_dict = json.loads(response.content)
except:
self.error = error_json(
ERR_CLOUDKEY,
"Cloud _tuyaplatform() invalid response: %r" % response.content,
)
return self.error
# Check to see if token is expired
return response_dict
| (self, uri, action='GET', post=None, ver='v1.0', recursive=False, query=None, content_type=None) |
729,382 | tinytuya.Cloud | _update_device_list | null | def _update_device_list( self, result1, result2 ):
for new_device in result2:
if 'id' not in new_device or not new_device['id']:
continue
found = False
for existing_device in result1:
if 'id' in existing_device and existing_device['id'] == new_device['id']:
found = True
for k in new_device:
if k not in existing_device or not existing_device[k]:
existing_device[k] = new_device[k]
if not found:
result1.append( new_device )
| (self, result1, result2) |
729,383 | tinytuya.Cloud | cloudrequest |
Make a generic cloud request and return the results.
Args:
url: Required. The URL to fetch, i.e. "/v1.0/devices/0011223344556677/logs"
action: Optional. GET, POST, DELETE, or PUT. Defaults to GET, unless POST data is supplied.
post: Optional. POST body data. Will be fed into json.dumps() before posting.
query: Optional. A dict containing query string key/value pairs.
| def cloudrequest(self, url, action=None, post=None, query=None):
"""
Make a generic cloud request and return the results.
Args:
url: Required. The URL to fetch, i.e. "/v1.0/devices/0011223344556677/logs"
action: Optional. GET, POST, DELETE, or PUT. Defaults to GET, unless POST data is supplied.
post: Optional. POST body data. Will be fed into json.dumps() before posting.
query: Optional. A dict containing query string key/value pairs.
"""
if not self.token:
return self.error
if action is None:
action = 'POST' if post else 'GET'
return self._tuyaplatform(url, action=action, post=post, ver=None, query=query)
| (self, url, action=None, post=None, query=None) |
729,384 | tinytuya.Cloud | filter_devices | null | def filter_devices( self, devs, ip_list=None ):
json_mac_data = {}
# mutable json_mac_data will be modified
self._get_hw_addresses( json_mac_data, [i['id'] for i in devs] )
tuyadevices = []
icon_host = 'https://images.' + self.urlhost.split( '.', 1 )[1] + '/'
for i in devs:
dev_id = i['id']
item = {
'name': '' if 'name' not in i else i['name'].strip(),
'id': dev_id,
'key': '' if 'local_key' not in i else i['local_key'],
'mac': '' if 'mac' not in i else i['mac']
}
if dev_id in json_mac_data:
for k in ('mac','uuid','sn'):
if k in json_mac_data[dev_id]:
item[k] = json_mac_data[dev_id][k]
if ip_list and 'mac' in item and item['mac'] in ip_list:
item['ip'] = ip_list[item['mac']]
for k in DEVICEFILE_SAVE_VALUES:
if k in i:
if k == 'icon':
item[k] = icon_host + i[k]
else:
item[k] = i[k]
if 'gateway_id' in i:
k = 'gateway_id'
item[k] = i[k]
tuyadevices.append(item)
return tuyadevices
| (self, devs, ip_list=None) |
729,385 | tinytuya.Cloud | format_timestamp | null | @staticmethod
def format_timestamp( ts ):
# converts a 10-digit unix timestamp to the 13-digit stamp the servers expect
if type(ts) != int:
if len(str(int(ts))) == 10:
ts = int( ts * 1000 )
else:
ts = int( ts )
elif len(str(ts)) == 10:
ts *= 1000
return ts
| (ts) |
729,386 | tinytuya.Cloud | getconnectstatus |
Get the device Cloud connect status.
| def getconnectstatus(self, deviceid=None):
"""
Get the device Cloud connect status.
"""
if not self.token:
return self.error
if not deviceid:
return error_json(
ERR_PARAMS,
"Missing DeviceID Parameter"
)
uri = 'devices/%s' % (deviceid)
response_dict = self._tuyaplatform(uri, ver='v1.0')
if not response_dict['success']:
log.debug("Error from Tuya Cloud: %r", response_dict['msg'])
return(response_dict["result"]["online"])
| (self, deviceid=None) |
729,387 | tinytuya.Cloud | getdevicelog |
Get the logs for a device.
https://developer.tuya.com/en/docs/cloud/0a30fc557f?id=Ka7kjybdo0jse
Note: The cloud only returns logs for DPs in the "official" DPS list.
If the device specifications are wrong then not all logs will be returned!
This is a limitation of Tuya's servers and there is nothing we can do about it.
Args:
devid: Required. Device ID
start: Optional. Get logs starting from this time. Defaults to yesterday
end: Optional. Get logs until this time. Defaults to the current time
evtype: Optional. Limit to events of this type. 1 = Online, 7 = DP Reports. Defaults to all events.
size: Optional. Target number of log entries to return. Defaults to 0 (all, up to max_fetches*100).
Actual number of log entries returned will be between "0" and "size * 2 - 1"
max_fetches: Optional. Maximum number of queries to send to the server. Tuya's server has a hard limit
of 100 records per query, so the maximum number of logs returned is "max_fetches * 100"
start_row_key: Optional. The "next_row_key" from a previous run.
params: Optional. Additional values to include in the query string. Defaults to an empty dict.
Returns:
Response from server
| def getdevicelog(self, deviceid=None, start=None, end=None, evtype=None, size=0, max_fetches=50, start_row_key=None, params=None):
"""
Get the logs for a device.
https://developer.tuya.com/en/docs/cloud/0a30fc557f?id=Ka7kjybdo0jse
Note: The cloud only returns logs for DPs in the "official" DPS list.
If the device specifications are wrong then not all logs will be returned!
This is a limitation of Tuya's servers and there is nothing we can do about it.
Args:
devid: Required. Device ID
start: Optional. Get logs starting from this time. Defaults to yesterday
end: Optional. Get logs until this time. Defaults to the current time
evtype: Optional. Limit to events of this type. 1 = Online, 7 = DP Reports. Defaults to all events.
size: Optional. Target number of log entries to return. Defaults to 0 (all, up to max_fetches*100).
Actual number of log entries returned will be between "0" and "size * 2 - 1"
max_fetches: Optional. Maximum number of queries to send to the server. Tuya's server has a hard limit
of 100 records per query, so the maximum number of logs returned is "max_fetches * 100"
start_row_key: Optional. The "next_row_key" from a previous run.
params: Optional. Additional values to include in the query string. Defaults to an empty dict.
Returns:
Response from server
"""
if not deviceid:
return error_json(
ERR_PARAMS,
"Missing DeviceID Parameter"
)
# server expects times as unixtime * 1000
if not end:
end = int((time.time() + self.server_time_offset) * 1000)
elif end < 0:
end = int(((time.time() + self.server_time_offset) + (end * 86400) ) * 1000)
else:
end = Cloud.format_timestamp( end )
if not start:
start = end - (86400*1000)
elif start < 0:
start = int(((time.time() + self.server_time_offset) + (start * 86400) ) * 1000)
else:
start = Cloud.format_timestamp( start )
if start > end:
tmp = start
start = end
end = tmp
if not evtype:
# get them all by default
# 1 = device online, 7 = DP report
evtype = '1,2,3,4,5,6,7,8,9,10'
elif type(evtype) == str:
pass
elif type(evtype) == bytes:
evtype = evtype.decode('utf8')
elif type(evtype) == int:
evtype = str(evtype)
elif type(evtype) == list or type(evtype) == tuple:
evtype = ','.join( [str(i) for i in evtype] )
else:
raise ValueError( "Unhandled 'evtype' type %s - %r" % (type(evtype), evtype) )
want_size = size
if not size:
size = 100
elif size > 100:
size = 100
#if (want_size / size) * 2 > max_fetches:
# max_fetches = round( (want_size / size) * 2 ) + 1
if not max_fetches or max_fetches < 1:
max_fetches = 50
params = {} if type(params) != dict else params.copy()
if 'start_time' not in params:
params['start_time'] = start
if 'end_time' not in params:
params['end_time'] = end
if 'type' not in params:
params['type'] = evtype
if 'size' not in params:
params['size'] = size
if 'query_type' not in params:
params['query_type'] = 1
if start_row_key:
params['start_row_key'] = start_row_key
ret = self.cloudrequest( '/v1.0/devices/%s/logs' % deviceid, query=params)
max_fetches -= 1
fetches = 1
if ret and 'result' in ret:
# ret['result'] is a dict so the 'result' below will be a reference, not a copy
result = ret['result']
again = True
next_row_key = ''
while (
again and max_fetches and
'logs' in result and
'has_next' in result and result['has_next'] and
(not want_size or len(result['logs']) < size) and
'next_row_key' in result and result['next_row_key'] and next_row_key != result['next_row_key']
):
again = False
max_fetches -= 1
fetches += 1
params['start_row_key'] = result['next_row_key']
next_row_key = result['next_row_key']
result['next_row_key'] = None
result['has_next'] = False
res = self.cloudrequest( '/v1.0/devices/%s/logs' % deviceid, query=params)
if res and 'result' in res:
result2 = res['result']
if 'logs' in result2:
result['logs'] += result2['logs']
again = True
if 'has_next' in result2:
result['has_next'] = result2['has_next']
if 'next_row_key' in result2:
result['next_row_key'] = result2['next_row_key']
else:
break
ret['fetches'] = fetches
return ret
| (self, deviceid=None, start=None, end=None, evtype=None, size=0, max_fetches=50, start_row_key=None, params=None) |
729,388 | tinytuya.Cloud | getdevices |
Return dictionary of all devices.
If verbose is true, return full Tuya device
details.
| def getdevices(self, verbose=False, oldlist=[], include_map=False):
"""
Return dictionary of all devices.
If verbose is true, return full Tuya device
details.
"""
old_devices = {}
if oldlist:
for dev in oldlist:
dev_id = dev['id']
old_devices[dev_id] = dev
if self.apiDeviceID and self.use_old_device_list:
json_data = {}
uid_list = {}
# apiDeviceID can be a comma-separated list, so process them all
for dev_id in self.apiDeviceID.split(','):
dev_id = dev_id.strip()
if not dev_id:
continue
uid = self._getuid( dev_id )
if not uid:
# no user for this device?
continue
if isinstance( uid, dict ):
# it's an error_json dict
return uid
else:
uid_list[uid] = True
if not uid_list:
return error_json(
ERR_CLOUD,
"Unable to get uid for device list"
)
for uid in uid_list:
# Use UID to get list of all Devices for User
uri = 'users/%s/devices' % uid
json_run = self._tuyaplatform(uri)
# merge the dicts
for k in json_run:
if (k not in json_data) or (k != 'result'):
# replace if key is not 'result'
json_data[k] = json_run[k]
else:
# merge 'result' keys
json_data[k] += json_run[k]
else:
json_data = self._get_all_devices()
users = {}
# loop through all devices and build a list of user IDs
for dev in json_data['result']:
if 'uid' in dev:
users[dev['uid']] = True
if users:
# we have at least 1 user id, so fetch the device list again to make sure we have the local key
# this also gets us the gateway_id for child devices
for uid in users.keys():
json_data2 = self._get_all_devices( uid=uid )
self._update_device_list( json_data['result'], json_data2['result'] )
if verbose:
return json_data
elif not json_data or 'result' not in json_data:
return error_json(
ERR_CLOUD,
"Unable to get device list"
)
self.getdevices_raw = json_data
devs = json_data['result']
changed_devices = []
unchanged_devices = []
# check to see if anything has changed. if so, re-download factory-infos and DP mapping
for dev in devs:
dev_id = dev['id']
if dev_id not in old_devices:
# newly-added device
changed_devices.append( dev )
continue
old = old_devices[dev_id]
if 'key' not in old or old['key'] != dev['local_key']:
# local key changed
changed_devices.append( dev )
continue
if (('icon' not in old) and ('icon' in dev)) or (include_map and ('mapping' not in old or old['mapping'] is None)):
# icon or mapping added
changed_devices.append( dev )
continue
is_same = True
for k in DEVICEFILE_SAVE_VALUES:
if k in dev and k != 'icon' and k != 'last_ip' and (k not in old or old[k] != dev[k]):
is_same = False
break
if not is_same:
changed_devices.append( dev )
continue
unchanged_devices.append( old )
if include_map:
mappings = self.getmappings( changed_devices )
for productid in mappings:
for dev in changed_devices:
if 'product_id' in dev and dev['product_id'] == productid:
dev['mapping'] = mappings[productid]
# also set unchanged devices just in case the mapping changed
for dev in unchanged_devices:
if 'product_id' in dev and dev['product_id'] == productid:
dev['mapping'] = mappings[productid]
log.debug( 'changed: %d', len(changed_devices) )
log.debug( 'unchanged: %d', len(unchanged_devices) )
# Filter to only Name, ID and Key
return self.filter_devices( changed_devices ) + unchanged_devices
| (self, verbose=False, oldlist=[], include_map=False) |
729,389 | tinytuya.Cloud | getdps |
Get the specifications including DPS IDs of the device.
| def getdps(self, deviceid=None):
"""
Get the specifications including DPS IDs of the device.
"""
if not self.token:
return self.error
if not deviceid:
return error_json(
ERR_PARAMS,
"Missing DeviceID Parameter"
)
uri = 'devices/%s/specifications' % (deviceid)
response_dict = self._tuyaplatform(uri, ver='v1.1')
if not response_dict['success']:
log.debug(
"Error from Tuya Cloud: %r", response_dict['msg'],
)
return response_dict
| (self, deviceid=None) |
729,390 | tinytuya.Cloud | getfunctions |
Get the functions of the device.
| def getfunctions(self, deviceid=None):
"""
Get the functions of the device.
"""
return self._getdevice('functions', deviceid)
| (self, deviceid=None) |
729,391 | tinytuya.Cloud | getmapping | null | def getmapping( self, productid, deviceid=None ):
# return a mapping for the given product id, or download it from the cloud using a device id
# Return value: None on failure, or a dict on success (may be an empty dict if device does not have DPs)
if not self.mappings:
self.mappings = {} #load_mappings()
if productid in self.mappings:
# already have this product id, so just return it
return self.mappings[productid]
if deviceid:
# we do not have this product id yet, so download it via this device id
result = self.getdps(deviceid)
if result:
if 'result' in result:
result = result['result']
dps = {}
# merge result['status'] and result['functions'] into a single result
if 'status' in result:
self._build_mapping( result['status'], dps )
if 'functions' in result:
self._build_mapping( result['functions'], dps )
self.mappings[productid] = dps
log.debug( 'Downloaded mapping for device %r: %r', deviceid, dps)
elif ('code' in result and result['code'] == 2009) or ('msg' in result and result['msg'] == 'not support this device'):
# this device does not have any DPs!
self.mappings[productid] = {}
if productid in self.mappings:
# download success, so return it
return self.mappings[productid]
# no device id, or download failed
return None
| (self, productid, deviceid=None) |
729,392 | tinytuya.Cloud | getmappings | null | def getmappings( self, devices ):
# get all mappings for all tuya devices
# returns a dict with product ids as keys
if not self.mappings:
self.mappings = {}
for dev in devices:
try:
devid = dev['id']
productid = dev['product_id']
except:
# we need both the device id and the product id to download mappings!
continue
if productid not in self.mappings:
self.getmapping( productid, devid )
return self.mappings
| (self, devices) |
729,393 | tinytuya.Cloud | getproperties |
Get the properties of the device.
| def getproperties(self, deviceid=None):
"""
Get the properties of the device.
"""
return self._getdevice('specification', deviceid)
| (self, deviceid=None) |
729,394 | tinytuya.Cloud | getstatus |
Get the status of the device.
| def getstatus(self, deviceid=None):
"""
Get the status of the device.
"""
return self._getdevice('status', deviceid)
| (self, deviceid=None) |
729,395 | tinytuya.Cloud | sendcommand |
Send a command to the device
| def sendcommand(self, deviceid=None, commands=None, uri='iot-03/devices/'):
"""
Send a command to the device
"""
if not self.token:
return self.error
if (not deviceid) or (not commands):
return error_json(
ERR_PARAMS,
"Missing DeviceID and/or Command Parameters"
)
uri += '%s/commands' % (deviceid)
response_dict = self._tuyaplatform(uri,action='POST',post=commands)
if not response_dict['success']:
log.debug(
"Error from Tuya Cloud: %r", response_dict['msg'],
)
return response_dict
| (self, deviceid=None, commands=None, uri='iot-03/devices/') |
729,396 | tinytuya.Cloud | setmappings | null | def setmappings( self, mappings ):
# sets an initial mapping set so we do not need to download everything
if type(mappings) == dict:
self.mappings = mappings
| (self, mappings) |
729,397 | tinytuya.Cloud | setregion | null | def setregion(self, apiRegion=None):
# Set hostname based on apiRegion
if apiRegion is None:
apiRegion = self.apiRegion
self.apiRegion = apiRegion.lower()
self.urlhost = "openapi.tuyacn.com" # China Data Center
if self.apiRegion == "us":
self.urlhost = "openapi.tuyaus.com" # Western America Data Center
if self.apiRegion == "us-e":
self.urlhost = "openapi-ueaz.tuyaus.com" # Eastern America Data Center
if self.apiRegion == "eu":
self.urlhost = "openapi.tuyaeu.com" # Central Europe Data Center
if self.apiRegion == "eu-w":
self.urlhost = "openapi-weaz.tuyaeu.com" # Western Europe Data Center
if self.apiRegion == "in":
self.urlhost = "openapi.tuyain.com" # India Datacenter
| (self, apiRegion=None) |
729,398 | tinytuya.CoverDevice | CoverDevice |
Represents a Tuya based Smart Window Cover.
| class CoverDevice(Device):
"""
Represents a Tuya based Smart Window Cover.
"""
DPS_INDEX_MOVE = "1"
DPS_INDEX_BL = "101"
DPS_2_STATE = {
"1": "movement",
"101": "backlight",
}
def open_cover(self, switch=1, nowait=False):
"""Open the cover"""
self.set_status("on", switch, nowait=nowait)
def close_cover(self, switch=1, nowait=False):
"""Close the cover"""
self.set_status("off", switch, nowait=nowait)
def stop_cover(self, switch=1, nowait=False):
"""Stop the motion of the cover"""
self.set_status("stop", switch, nowait=nowait)
| (dev_id, address=None, local_key='', dev_type='default', connection_timeout=5, version=3.1, persist=False, cid=None, node_id=None, parent=None, connection_retry_limit=5, connection_retry_delay=5, port=6668) |
729,400 | tinytuya.core | __init__ |
Represents a Tuya device.
Args:
dev_id (str): The device id.
address (str): The network address.
local_key (str, optional): The encryption key. Defaults to None.
cid (str: Optional sub device id. Default to None.
node_id (str: alias for cid)
parent (object: gateway device this device is a child of)
Attributes:
port (int): The port to connect to.
| def __init__(
self, dev_id, address=None, local_key="", dev_type="default", connection_timeout=5, version=3.1, persist=False, cid=None, node_id=None, parent=None, connection_retry_limit=5, connection_retry_delay=5, port=TCPPORT # pylint: disable=W0621
):
"""
Represents a Tuya device.
Args:
dev_id (str): The device id.
address (str): The network address.
local_key (str, optional): The encryption key. Defaults to None.
cid (str: Optional sub device id. Default to None.
node_id (str: alias for cid)
parent (object: gateway device this device is a child of)
Attributes:
port (int): The port to connect to.
"""
self.id = dev_id
self.cid = cid if cid else node_id
self.address = address
self.auto_ip = False
self.dev_type = dev_type
self.dev_type_auto = self.dev_type == 'default'
self.last_dev_type = ''
self.connection_timeout = connection_timeout
self.retry = True
self.disabledetect = False # if True do not detect device22
self.port = port # default - do not expect caller to pass in
self.socket = None
self.socketPersistent = False if not persist else True # pylint: disable=R1719
self.socketNODELAY = True
self.socketRetryLimit = connection_retry_limit
self.socketRetryDelay = connection_retry_delay
self.version = 0
self.dps_to_request = {}
self.seqno = 1
self.sendWait = 0.01
self.dps_cache = {}
self.parent = parent
self.children = {}
self.received_wrong_cid_queue = []
self.local_nonce = b'0123456789abcdef' # not-so-random random key
self.remote_nonce = b''
self.payload_dict = None
if not local_key:
local_key = ""
# sub-devices do not need a local key, so only look it up if we are not a sub-device
if not parent:
devinfo = device_info( dev_id )
if devinfo and 'key' in devinfo and devinfo['key']:
local_key = devinfo['key']
self.local_key = local_key.encode("latin1")
self.real_local_key = self.local_key
self.cipher = None
if self.parent:
# if we are a child then we should have a cid/node_id but none were given - try and find it the same way we look up local keys
if not self.cid:
devinfo = device_info( dev_id )
if devinfo and 'node_id' in devinfo and devinfo['node_id']:
self.cid = devinfo['node_id']
if not self.cid:
# not fatal as the user could have set the device_id to the cid
# in that case dev_type should be 'zigbee' to set the proper fields in requests
log.debug( 'Child device but no cid/node_id given!' )
XenonDevice.set_version(self, self.parent.version)
self.parent._register_child(self)
elif (not address) or address == "Auto" or address == "0.0.0.0":
# try to determine IP address automatically
self.auto_ip = True
bcast_data = find_device(dev_id)
if bcast_data['ip'] is None:
log.debug("Unable to find device on network (specify IP address)")
raise Exception("Unable to find device on network (specify IP address)")
self.address = bcast_data['ip']
self.set_version(float(bcast_data['version']))
time.sleep(0.1)
elif version:
self.set_version(float(version))
else:
# make sure we call our set_version() and not a subclass since some of
# them (such as BulbDevice) make connections when called
XenonDevice.set_version(self, 3.1)
| (self, dev_id, address=None, local_key='', dev_type='default', connection_timeout=5, version=3.1, persist=False, cid=None, node_id=None, parent=None, connection_retry_limit=5, connection_retry_delay=5, port=6668) |
729,419 | tinytuya.CoverDevice | close_cover | Close the cover | def close_cover(self, switch=1, nowait=False):
"""Close the cover"""
self.set_status("off", switch, nowait=nowait)
| (self, switch=1, nowait=False) |
729,424 | tinytuya.CoverDevice | open_cover | Open the cover | def open_cover(self, switch=1, nowait=False):
"""Open the cover"""
self.set_status("on", switch, nowait=nowait)
| (self, switch=1, nowait=False) |
729,440 | tinytuya.core | set_version | null | def set_version(self, version): # pylint: disable=W0621
self.version = version
self.version_str = "v" + str(version)
self.version_bytes = str(version).encode('latin1')
self.version_header = self.version_bytes + PROTOCOL_3x_HEADER
self.payload_dict = None
if version == 3.2: # 3.2 behaves like 3.3 with device22
self.dev_type="device22"
if self.dps_to_request == {}:
self.detect_available_dps()
| (self, version) |
729,442 | tinytuya.CoverDevice | stop_cover | Stop the motion of the cover | def stop_cover(self, switch=1, nowait=False):
"""Stop the motion of the cover"""
self.set_status("stop", switch, nowait=nowait)
| (self, switch=1, nowait=False) |
729,444 | tinytuya.core | turn_off | Turn the device off | def turn_off(self, switch=1, nowait=False):
"""Turn the device off"""
return self.set_status(False, switch, nowait)
| (self, switch=1, nowait=False) |
729,445 | tinytuya.core | turn_on | Turn the device on | def turn_on(self, switch=1, nowait=False):
"""Turn the device on"""
return self.set_status(True, switch, nowait)
| (self, switch=1, nowait=False) |
729,454 | tinytuya.core | Device | null | class Device(XenonDevice):
#def __init__(self, *args, **kwargs):
# super(Device, self).__init__(*args, **kwargs)
def set_status(self, on, switch=1, nowait=False):
"""
Set status of the device to 'on' or 'off'.
Args:
on(bool): True for 'on', False for 'off'.
switch(int): The switch to set
nowait(bool): True to send without waiting for response.
"""
# open device, send request, then close connection
if isinstance(switch, int):
switch = str(switch) # index and payload is a string
payload = self.generate_payload(CONTROL, {switch: on})
data = self._send_receive(payload, getresponse=(not nowait))
log.debug("set_status received data=%r", data)
return data
def product(self):
"""
Request AP_CONFIG Product Info from device. [BETA]
"""
# open device, send request, then close connection
payload = self.generate_payload(AP_CONFIG)
data = self._send_receive(payload, 0)
log.debug("product received data=%r", data)
return data
def heartbeat(self, nowait=True):
"""
Send a keep-alive HEART_BEAT command to keep the TCP connection open.
Devices only send an empty-payload response, so no need to wait for it.
Args:
nowait(bool): True to send without waiting for response.
"""
# open device, send request, then close connection
payload = self.generate_payload(HEART_BEAT)
data = self._send_receive(payload, 0, getresponse=(not nowait))
log.debug("heartbeat received data=%r", data)
return data
def updatedps(self, index=None, nowait=False):
"""
Request device to update index.
Args:
index(array): list of dps to update (ex. [4, 5, 6, 18, 19, 20])
nowait(bool): True to send without waiting for response.
"""
if index is None:
index = [1]
log.debug("updatedps() entry (dev_type is %s)", self.dev_type)
# open device, send request, then close connection
payload = self.generate_payload(UPDATEDPS, index)
data = self._send_receive(payload, 0, getresponse=(not nowait))
log.debug("updatedps received data=%r", data)
return data
def set_value(self, index, value, nowait=False):
"""
Set int value of any index.
Args:
index(int): index to set
value(int): new value for the index
nowait(bool): True to send without waiting for response.
"""
# open device, send request, then close connection
if isinstance(index, int):
index = str(index) # index and payload is a string
payload = self.generate_payload(CONTROL, {index: value})
data = self._send_receive(payload, getresponse=(not nowait))
return data
def set_multiple_values(self, data, nowait=False):
"""
Set multiple indexes at the same time
Args:
data(dict): array of index/value pairs to set
nowait(bool): True to send without waiting for response.
"""
out = {}
for i in data:
out[str(i)] = data[i]
payload = self.generate_payload(CONTROL, out)
return self._send_receive(payload, getresponse=(not nowait))
def turn_on(self, switch=1, nowait=False):
"""Turn the device on"""
return self.set_status(True, switch, nowait)
def turn_off(self, switch=1, nowait=False):
"""Turn the device off"""
return self.set_status(False, switch, nowait)
def set_timer(self, num_secs, dps_id=0, nowait=False):
"""
Set a timer.
Args:
num_secs(int): Number of seconds
dps_id(int): DPS Index for Timer
nowait(bool): True to send without waiting for response.
"""
# Query status, pick last device id as that is probably the timer
if dps_id == 0:
status = self.status()
if "dps" in status:
devices = status["dps"]
devices_numbers = list(devices.keys())
devices_numbers.sort()
dps_id = devices_numbers[-1]
else:
log.debug("set_timer received error=%r", status)
return status
payload = self.generate_payload(CONTROL, {dps_id: num_secs})
data = self._send_receive(payload, getresponse=(not nowait))
log.debug("set_timer received data=%r", data)
return data
| (dev_id, address=None, local_key='', dev_type='default', connection_timeout=5, version=3.1, persist=False, cid=None, node_id=None, parent=None, connection_retry_limit=5, connection_retry_delay=5, port=6668) |
729,500 | tinytuya.core | MessagePayload | MessagePayload(cmd, payload) | from tinytuya.core import MessagePayload
| (cmd, payload) |
729,502 | namedtuple_MessagePayload | __new__ | Create new instance of MessagePayload(cmd, payload) | from builtins import function
| (_cls, cmd, payload) |
729,505 | collections | _replace | Return a new MessagePayload object replacing specified fields with new values | def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
# Validate the field names. At the user's option, either generate an error
# message or automatically replace the field name with a valid name.
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = _sys.intern(str(typename))
if rename:
seen = set()
for index, name in enumerate(field_names):
if (not name.isidentifier()
or _iskeyword(name)
or name.startswith('_')
or name in seen):
field_names[index] = f'_{index}'
seen.add(name)
for name in [typename] + field_names:
if type(name) is not str:
raise TypeError('Type names and field names must be strings')
if not name.isidentifier():
raise ValueError('Type names and field names must be valid '
f'identifiers: {name!r}')
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
f'keyword: {name!r}')
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
f'{name!r}')
if name in seen:
raise ValueError(f'Encountered duplicate field name: {name!r}')
seen.add(name)
field_defaults = {}
if defaults is not None:
defaults = tuple(defaults)
if len(defaults) > len(field_names):
raise TypeError('Got more default values than field names')
field_defaults = dict(reversed(list(zip(reversed(field_names),
reversed(defaults)))))
# Variables used in the methods and docstrings
field_names = tuple(map(_sys.intern, field_names))
num_fields = len(field_names)
arg_list = ', '.join(field_names)
if num_fields == 1:
arg_list += ','
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
tuple_new = tuple.__new__
_dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
# Create all the named tuple methods to be added to the class namespace
namespace = {
'_tuple_new': tuple_new,
'__builtins__': {},
'__name__': f'namedtuple_{typename}',
}
code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
__new__ = eval(code, namespace)
__new__.__name__ = '__new__'
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults
@classmethod
def _make(cls, iterable):
result = tuple_new(cls, iterable)
if _len(result) != num_fields:
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
return result
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
'or iterable')
def _replace(self, /, **kwds):
result = self._make(_map(kwds.pop, field_names, self))
if kwds:
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
return result
_replace.__doc__ = (f'Return a new {typename} object replacing specified '
'fields with new values')
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + repr_fmt % self
def _asdict(self):
'Return a new dict which maps field names to their values.'
return _dict(_zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return _tuple(self)
# Modify function metadata to help with introspection and debugging
for method in (
__new__,
_make.__func__,
_replace,
__repr__,
_asdict,
__getnewargs__,
):
method.__qualname__ = f'{typename}.{method.__name__}'
# Build-up the class namespace dictionary
# and use type() to build the result class
class_namespace = {
'__doc__': f'{typename}({arg_list})',
'__slots__': (),
'_fields': field_names,
'_field_defaults': field_defaults,
'__new__': __new__,
'_make': _make,
'_replace': _replace,
'__repr__': __repr__,
'_asdict': _asdict,
'__getnewargs__': __getnewargs__,
'__match_args__': field_names,
}
for index, name in enumerate(field_names):
doc = _sys.intern(f'Alias for field number {index}')
class_namespace[name] = _tuplegetter(index, doc)
result = type(typename, (tuple,), class_namespace)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython), or where the user has
# specified a particular module.
if module is None:
try:
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
if module is not None:
result.__module__ = module
return result
| (self, /, **kwds) |
Subsets and Splits