home-assistant / core

:house_with_garden: Open source home automation that puts local control and privacy first.
https://www.home-assistant.io
Apache License 2.0
69.62k stars 28.8k forks source link

Tuya Switch Not Keeping Its State When Toggled #36744

Closed homecb closed 3 years ago

homecb commented 4 years ago

The problem

Tuya switch component works, but the toggle does not keep its state. The issue is a resurrection of https://github.com/home-assistant/core/issues/25992 I couldn't comment on that thread (locked), thus created a new one.

Environment

Traceback/Error logs

Additional information

estebanz01 commented 4 years ago

Let me know if I can help you with something. I'm a ruby dev, but I can try my best 🙆‍♂️

ghost commented 4 years ago

It was driving me nuts for a few days now (maybe since i upgraded 111.3 or 111.4). All my 20 devices were not properly displaying the state. I applied the quick fix mentioned above in /tuyaha/tuyaapi.py. Everything works now, but a bit buggy. Thank you

memphis3 commented 4 years ago

Four Tuya light switches on WR4 chip, update the status in HA after 5 - 10 minutes. No solution can eliminate the delay in my case. I hope that the next HA update will solve the problem.

The problem with delay on Tuya lights switches has always been but since version 0.111.x it is so big that it prevents proper operation of the entire system

cannondale0815 commented 4 years ago

Past 5 days my 20+ Tuya switches were un-usable in HA, and just applied your fixed to my HA 111.3 running on docker and magic.....all switches started working again.

Thanks a lot....

It appears to be only a temporary fix though, as @AdmiralStipe has mentioned above. I myself also saw the problems resurface after an hour or two.

donnaran commented 4 years ago

Past 5 days my 20+ Tuya switches were un-usable in HA, and just applied your fixed to my HA 111.3 running on docker and magic.....all switches started working again. Thanks a lot....

It appears to be only a temporary fix though, as @AdmiralStipe has mentioned above. I myself also saw the problems resurface after an hour or two.

Yes its temporary fix as its not 100% working, if switch is turned on/off manually (outside off HA) then still takes very long delay (over 5mins +) to update state in HA.

nao-pon commented 4 years ago

The patch I posted seems incomplete. It works fine for about an hour after the HA restarts, but then this problem occurs again. The cause is still unknown.

donnaran commented 4 years ago

The patch posted only works fine about hour, after that same issue. Annoying & frustrating

nao-pon commented 4 years ago

I'm trying another method right now. It's still functioning properly after 4 hours. I will post the patch after a little more verification.

donnaran commented 4 years ago

I'm trying another method right now. It's still functioning properly after 4 hours. I will post the patch after a little more verification.

Looking forward for this. Thanks

nao-pon commented 4 years ago

I made a patch. My maintenance repository is below.

First of all, undo the last change I posted. Then apply this patch. Place diff.patch in the directory "/usr/local/lib/python3.7/site-packages/tuyaha" and run the patch command. Incidentally. This patch does not fix an issue where changes made elsewhere are not immediately reflected in HA.

patch -p2 < diff.patch

Be sure to save the backup so that you can revert to it, as the following files will be modified:

@@ -33,10 +26,14 @@ class TuyaFanDevice(TuyaDevice): self.api.device_control(self.obj_id, command)

 def turn_on(self):
ghost commented 4 years ago

@nao-pon , applied the patch, it looks good for HA control. Although, if you use an external app (ie. smart life app) to control the devices, the state won't be reflected in HA immediately (~a few seconds), it will only be refreshed at next pull devices interval. I tested a few switch devices and some refresh took up to 10 minutes to update the state in HA.

Thanks.

ollo69 commented 4 years ago

If I well understand the scope of this patch is Just "force" status change after togling from HA, so the real status can be different. Do not fix the original issue related to fail keep real status from Tuya Cloud.

nao-pon commented 4 years ago

@ollo69 Yes, I know my fix is ​​not a legitimate one. However, I used this method because it doesn't seem to get the correct value immediately from Tuya Cloud. I was used this as an interim fix, as the set switch state is only enforced when the "turnOnOff" command succeeds.

I hope the someone's legitimate fix will be included in the next update and will overwrite my childish fix.

ollo69 commented 4 years ago

I did some test that confirm that the problem is Tuya API side. Seems that call to discovery method (that is used to check switch status) often return the error "FrequentlyInvoke", so probably Tuya is trying to limit the used band. Anyway this method return status for all device so calling it for enery device is not really correct. What I did now is limit the call to this method once every 15 seconds and use cached result for all other devices. I still have sometime the error but probably this provide better result. To simplify test I created a custom component (https://github.com/ollo69/ha_tuya_custom) that is the exact copy of the standard but use a built-in version of modded library. You can install this component using hacs, but before install remove configuration for default ha component, than after installation of custom component search and configure componet "Tuya Custom" Please let me know if this provide better result, in any case the Tuya API is really unreliable so a different solution in the future should be found.

nao-pon commented 4 years ago

@ollo69 I installed "tuya_custom" via HACS and restarted HA. However, I can only see "Tuya" in the integration search, not found "Tuya Custom".

nao-pon commented 4 years ago

@ollo69 I was able to use "Tuya Custom" by adding the configuration to configuration.yaml. However, the light switch is unable to maintain that state, which is causing this issue. In addition, the problem that changes made in the SmartLife app etc. were not reflected immediately was not resolved.

ollo69 commented 4 years ago

This is because my change only consider switch :) Ok, could you enable the debug log adding this in configuration.yaml:

logger:
  default: info
  logs:
    custom_components.tuya_custom: debug

and than post here the the log file. I need to know if all information are inside discovery message also for light, in this way I can reduce the call to API for all devices type and this should generally improve performance.

Thx

gdr2404 commented 4 years ago

I have quite a few automations set up through node red with tuya switches. This problem seems to have stopped any tuya messages passing from the switches at all when debugging them making them useless inside node red? Let's hope this is only a tempory issues.

nao-pon commented 4 years ago

@ollo69 I'm changing all device types to be checked by the discovery method for validation and testing by adjusting the API call interval to avoid "Frequently Invoke" error. An error occurred continuously up to 60 seconds. When I set it to 90 seconds, the error almost disappeared.

It seems that we need to cache the value if the command succeeds after executing the command in HA, and lengthen the API call interval considerably.

ollo69 commented 4 years ago

In my test seems that error appear "randomly", so probably is better to not slow down to mutch and stay with cached value when occurs, we can have better response in most case. I wonder if this is also related to high trafic generate by all user and moving all to this solution can provide general benefit. Can you PR your change so that we can move technical discussion on repository?

nao-pon commented 4 years ago

@ollo69 Yes, I will try to fix it and make a Pull Request. However, since this is my first time dealing with Python, I will start by learning Python, so it may take a week or so.

nao-pon commented 4 years ago

@ollo69 It's still a draft, but I sent PR immediately.

https://github.com/ollo69/ha_tuya_custom/pull/1

acs-lux commented 4 years ago

Is this of any use to somehow locally poll tuya devices?

https://github.com/mileperhour/localtuya-homeassistant

iwzoo commented 4 years ago

Same here, exception occurs:

[tuyaha.tuyaapi] control device error, error code is FrequentlyInvoke

I think Tuya limits the requests frequency.

GBCRAS1 commented 4 years ago

Is this of any use to somehow locally poll tuya devices?

https://github.com/mileperhour/localtuya-homeassistant

I've just turn my switches locally using above custom integration. Had to get the local_key and i got them using a YouTube step by step

cannondale0815 commented 4 years ago

Is this of any use to somehow locally poll tuya devices? https://github.com/mileperhour/localtuya-homeassistant

I've just turn my switches locally using above custom integration. Had to get the local_key and i got them using a YouTube step by step

@GBCRAS1 can you share some more details? So you didn't have to flash a custom firmware like Tasmota and used the linked Github project to now locally talk to your Tuya devices and also obtain status from your Tuya devices entirely locally without needing to speak to the Tuya cloud back-end?

GBCRAS1 commented 4 years ago

I just followed below YouTube video to get the local_key for each switch. I had to use a Tuya Smart App v3.1.5 as my devices are added to Tuya Smart and not Smart Life:

https://www.youtube.com/watch?v=jjREXNUQ5fY

After you have the local_keys you can follow the steps described into https://github.com/mileperhour/localtuya-homeassistant

acs-lux commented 4 years ago

My Tuya devices are keeping their state but state changes are very very slow. If I control device with HA state changes instantly then sometimes changes back until presumably the Tuya states are received from the cloud. Using HA Tuya integration not the local.

iwzoo commented 4 years ago

I just followed below YouTube video to get the local_key for each switch. I had to use a Tuya Smart App v3.1.5 as my devices are added to Tuya Smart and not Smart Life:

https://www.youtube.com/watch?v=jjREXNUQ5fY

After you have the local_keys you can follow the steps described into https://github.com/mileperhour/localtuya-homeassistant

thank you so much, I've successfully got the local key following the video, and finally make it working.

the original localtuya repository set 20 seconds between updates. I forked the repo and added new option 'update_interval', leave 3 seconds works just perfect. new repo at https://github.com/iwzoo/localtuya-homeassistant

GBCRAS1 commented 4 years ago

What have you changed to be able to set the update_interval ?

donnaran commented 4 years ago

I just followed below YouTube video to get the local_key for each switch. I had to use a Tuya Smart App v3.1.5 as my devices are added to Tuya Smart and not Smart Life: https://www.youtube.com/watch?v=jjREXNUQ5fY After you have the local_keys you can follow the steps described into https://github.com/mileperhour/localtuya-homeassistant

thank you so much, I've successfully got the local key following the video, and finally make it working.

the original localtuya repository set 20 seconds between updates. I forked the repo and added new option 'update_interval', leave 3 seconds works just perfect. new repo at https://github.com/iwzoo/localtuya-homeassistant

I just tried your repo, i'm getting following error. the original repo work fine except the 20 seconds delay in state update.

2020-06-23 22:23:19 ERROR (MainThread) [homeassistant.components.switch] Error while setting up localtuya platform for switch

Traceback (most recent call last):

File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 178, in _async_setup_platform

await asyncio.wait_for(asyncio.shield(task), SLOW_SETUP_MAX_WAIT)

File "/usr/local/lib/python3.7/asyncio/tasks.py", line 442, in wait_for

return fut.result()

File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run

result = self.fn(*self.args, **self.kwargs)

File "/config/custom_components/localtuya/switch.py", line 77, in setup_platform

config.get(CONF_ID)

File "/config/custom_components/localtuya/switch.py", line 140, in init

self._status = self._device.status()

File "/config/custom_components/localtuya/switch.py", line 124, in status

self._cached_status = self.__get_status()

File "/config/custom_components/localtuya/switch.py", line 106, in __get_status

status = self._device.status()

File "/config/custom_components/localtuya/pytuya/init.py", line 259, in status

data = self._send_receive(payload)

File "/config/custom_components/localtuya/pytuya/init.py", line 171, in _send_receive

data = s.recv(1024)

socket.timeout: timed out

iwzoo commented 4 years ago

I just followed below YouTube video to get the local_key for each switch. I had to use a Tuya Smart App v3.1.5 as my devices are added to Tuya Smart and not Smart Life: https://www.youtube.com/watch?v=jjREXNUQ5fY After you have the local_keys you can follow the steps described into https://github.com/mileperhour/localtuya-homeassistant

thank you so much, I've successfully got the local key following the video, and finally make it working. the original localtuya repository set 20 seconds between updates. I forked the repo and added new option 'update_interval', leave 3 seconds works just perfect. new repo at https://github.com/iwzoo/localtuya-homeassistant

I just tried your repo, i'm getting following error. the original repo work fine except the 20 seconds delay in state update.

2020-06-23 22:23:19 ERROR (MainThread) [homeassistant.components.switch] Error while setting up localtuya platform for switch

Traceback (most recent call last):

File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 178, in _async_setup_platform

await asyncio.wait_for(asyncio.shield(task), SLOW_SETUP_MAX_WAIT)

File "/usr/local/lib/python3.7/asyncio/tasks.py", line 442, in wait_for

return fut.result()

File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run

result = self.fn(*self.args, **self.kwargs)

File "/config/custom_components/localtuya/switch.py", line 77, in setup_platform

config.get(CONF_ID)

File "/config/custom_components/localtuya/switch.py", line 140, in init

self._status = self._device.status()

File "/config/custom_components/localtuya/switch.py", line 124, in status

self._cached_status = self.__get_status()

File "/config/custom_components/localtuya/switch.py", line 106, in __get_status

status = self._device.status()

File "/config/custom_components/localtuya/pytuya/init.py", line 259, in status

data = self._send_receive(payload)

File "/config/custom_components/localtuya/pytuya/init.py", line 171, in _send_receive

data = s.recv(1024)

socket.timeout: timed out

please paste your configuration, here is mime

switch:
  - platform: localtuya
    host: 192.168.10.122
    local_key: !secret tuya_local_key
    device_id: !secret tuya_device_id
    update_interval: 3
Yonny24 commented 4 years ago

This is such a major bug affecting many users globally. Surely HA team are working on a fix for the integration?

donnaran commented 4 years ago

please paste your configuration, here is mime

switch:
  - platform: localtuya
    host: 192.168.10.122
    local_key: !secret tuya_local_key
    device_id: !secret tuya_device_id
    update_interval: 3

I have exact same config, like yours...

switch:

  • platform: localtuya host: 10.10.1.118 local_key: !secret tuya_local_key device_id: !secret tuya_device_id update_interval: 3
iwzoo commented 4 years ago

please paste your configuration, here is mime

switch:
  - platform: localtuya
    host: 192.168.10.122
    local_key: !secret tuya_local_key
    device_id: !secret tuya_device_id
    update_interval: 3

I have exact same config, like yours...

switch:

  • platform: localtuya host: 10.10.1.118 local_key: !secret tuya_local_key device_id: !secret tuya_device_id update_interval: 3

please get the latest code (I made changes hours ago, which uses device id for name by default). Otherwise, you need to add "name" option

switch:
  - platform: localtuya
    host: 192.168.10.122
    local_key: !secret tuya_local_key
    device_id: !secret tuya_device_id
    name: name of the switch
    update_interval: 3

or add "switches" option

ollo69 commented 4 years ago

This is such a major bug affecting many users globally. Surely HA team are working on a fix for the integration?

The root cause of this issue is not strictly related to HA but to Tuya API that is not providing the same level of service. I'm trying to find a solution, but the issue is related to the communication library that is not maintained by HA team.

donnaran commented 4 years ago

please get the latest code (I made changes hours ago, which uses device id for name by default). Otherwise, you need to add "name" option

switch:
  - platform: localtuya
    host: 192.168.10.122
    local_key: !secret tuya_local_key
    device_id: !secret tuya_device_id
    name: name of the switch
    update_interval: 3

or add "switches" option

tried the new updated code but still getting same error swtich:

iwzoo commented 4 years ago

please get the latest code (I made changes hours ago, which uses device id for name by default). Otherwise, you need to add "name" option

switch:
  - platform: localtuya
    host: 192.168.10.122
    local_key: !secret tuya_local_key
    device_id: !secret tuya_device_id
    name: name of the switch
    update_interval: 3

or add "switches" option

tried the new updated code but still getting same error swtich:

  • platform: localtuya host: 10.10.1.118 local_key: !secret tuya_local_key device_id: !secret tuya_device_id name: office update_interval: 3

HA version?

donnaran commented 4 years ago

HA version?

I am running HA 111.4

acs-lux commented 4 years ago

My suggestion of local polling was intended for the HA Tuya Integration but I suppose the threads are vaguely related.

cannondale0815 commented 4 years ago

@iwzoo I am trying your repo but can't get past the following error:

2020-06-23 18:06:28 INFO (SyncWorker_24) [custom_components.localtuya.pytuya] Python 3.7.7 (default, Apr 28 2020, 13:57:57) 2020-06-23 18:06:28 INFO (SyncWorker_24) [custom_components.localtuya.pytuya] Using PyCrypto (3, 9, '7') 2020-06-23 18:06:28 INFO (SyncWorker_24) [custom_components.localtuya.pytuya] Using PyCrypto from '/usr/local/lib/python3.7/site-packages/Crypto/__init__.py' 2020-06-23 18:06:28 DEBUG (SyncWorker_24) [custom_components.localtuya.switch] fetch device status every 20 seconds 2020-06-23 18:06:28 DEBUG (SyncWorker_24) [custom_components.localtuya.pytuya] status() entry 2020-06-23 18:06:28 DEBUG (SyncWorker_24) [custom_components.localtuya.pytuya] json_payload=b'{"gwId":"XYZ","devId":"XYZ"}' 2020-06-23 18:06:38 WARNING (MainThread) [homeassistant.components.switch] Setup of switch platform localtuya is taking over 10 seconds. 2020-06-23 18:06:38 ERROR (MainThread) [homeassistant.components.switch] Error while setting up localtuya platform for switch File "/config/custom_components/localtuya/switch.py", line 77, in setup_platform File "/config/custom_components/localtuya/switch.py", line 140, in __init__ File "/config/custom_components/localtuya/switch.py", line 124, in status File "/config/custom_components/localtuya/switch.py", line 106, in __get_status File "/config/custom_components/localtuya/pytuya/__init__.py", line 259, in status File "/config/custom_components/localtuya/pytuya/__init__.py", line 171, in _send_receive

Config as follows:

switch:
  - platform: localtuya
    host: 192.168.5.53
    local_key: ABC
    device_id: XYZ
    name: sunflower

This is for a wall light switch. Of course ABC/XYZ are the proper key/id in both the config file and also the log file output.

I'm assuming host needs to be the local IP of the switch itself? Also, do I really need to edit the switch.py file, as mentioned in the instructions?

iwzoo commented 4 years ago

HA version?

I am running HA 111.4

try bigger value for update_interval, make sure the ip address, id and local key are correct.

Yonny24 commented 4 years ago

I wonder if it's possible to use nodered to update the states of the entities. Possibly polling every few seconds to update the states if any change is detected.

Not sure if this is feasible but just crossed my mind after building a polling flow for some motion sensors.

JorgeMaTeixeira-zz commented 4 years ago

How people read the XML file? I can't find the readerxmltuya.

cannondale0815 commented 4 years ago

How people read the XML file? I can't find the readerxmltuya.

You can just open it in any text editor. There is a key and a localKey per Tuya device. The former is the device ID, the latter the local key. Only use the alphanumeric characters and ignore any special characters before and after.

JorgeMaTeixeira-zz commented 4 years ago

I can´t get to work.. configuration.yaml is in error when i put exacly the same configuration as above (with my device settings off course,..

cannondale0815 commented 4 years ago

I can´t get to work.. configuration.yaml is in error when i put exacly the same configuration as above (with my device settings off course,..

I have issues with localtuya myself, but post the relevant excerpt of your configuration here so others can take a look

JorgeMaTeixeira-zz commented 4 years ago

How i did.

image image

With that configuration the server don´t restart for some reason.

smic717394 commented 4 years ago

Hi guys, how you decode the xml, there is a configuration for each individual switch, plugs and sensors? How about the ip, I guess each has to be assign a static IP.

nao-pon commented 4 years ago

As @ollo69 said, the cause of this problem is the Tuya API request limit. The HA side cannot solve the cause.

I tried the verification and correction by the following PR.

As a result of taking measures for the time being, the status change made in HA is reflected immediately and the problem disappears even on the UI.

However, if you change the status with the Smart Life app, etc., there will be a time lag of several seconds to 2 minutes before it is reflected in HA.

In order to do a complete sync, you have to do the sync locally, such as with localtuya, but there is no way to get the device local key automatically and integrating it is very expensive.