jasonacox / tinytuya

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

Group control #514

Open measwel opened 4 months ago

measwel commented 4 months ago

Hi,

Would it be possible to control a group of devices like with the smartlife app? The app controls the devices in a group practically simultanously. When I try the same with tinytuya, I need to send commands to each device separately and I get a delay for each device. Sorry if the question has been asked before.

uzlonewolf commented 4 months ago

Not easily. You basically have to pre-open persistent connections to every device in the group and then send the commands as needed. If no data is received in ~29 seconds the devices close the connection, so a keep-alive/heartbeat must be implemented as well. The quick-n-dirty way of doing this uses a thread for each device, though I personally don't like doing that and instead use non-blocking sockets and dump them all into select() with a timeout.

measwel commented 4 months ago

Thanks @uzlonewolf.

My usecase. I use 5 RGB LED bulbs in my darkroom app (https://github.com/measwel/darkroom). I switch these off, before I switch on the enlarger (via smart outlet). They go out one by one and sometimes not all are off when the enlarger switches on. It would be useful to:

(1) switch them all off in one go. (2) have a light weight way to know if they are all off.

As to (1) could you perhaps show some example code? As to (2) is polling the status the only way to find out if the bulb is off? It introduces another delay. The turn_off() command does not return the status of the bulb. What would be a smart way to find out if the bulb is off?

uzlonewolf commented 4 months ago

Unfortunately I don't have any simple code to demonstrate it, the best I got is the "multiserver" I was working on https://github.com/uzlonewolf/tinytuya/blob/socket-server/multiserver/multiserver.py#L777 . It still has some rough edges such as lag when it's attempting to (re-)connect devices, but it otherwise works.

As long as the connections are persistent the devices should send async status updates whenever their state changes, so it shouldn't be too hard to just track the last state received.