jasonacox / tinytuya

Python API for Tuya WiFi smart devices using a direct local area network (LAN) connection or the cloud (TuyaCloud API).
MIT License
939 stars 167 forks source link

Multiple received packets results in none getting decoded #152

Closed uzlonewolf closed 2 years ago

uzlonewolf commented 2 years ago

While debugging something completely unrelated I noticed a DEBUG:tinytuya.core:incomplete payload=... go flying by. Further investigation reveals the "incomplete" payload actually contained 3 completely separate payloads: one which was just requested, and 2 async DPS updates. This "multiple = none" explains why I was sometimes only seeing one or 2 of my thermostat sensor list updates instead of all 5.

I see there is a "length" field in the header; is there any reason this is not used? unpack_message() blindly assumes everything minus the footer length is part of a single packet.

As for fixing this, I can think of 2 options: 1) change the self.socket.recv(1024) to only read the header length and then do a 2nd recv() for the body once we know the length (leaving any remaining message(s) for the next receive() call to deal with), or 2) keep the large read and return it in the dict as "next_packet" or something and make the user handle the detection of this and the feeding of it back into receive(). I'm really not feeling option 2 as in addition to being clunky you are also going to have problems if a message isn't completely received in a single recv() call.