Tuya switch

Hey Everybody,

First of: A big thank you to all those contributing to this platform that I just discovered yesterday. I have a small issue with the Tuya switches (I use a version from Smart Life). I am using a pre-loaded component in Hassio. I see the switches in my Home Assistant and I can toggle them. The proper switch will change state. However, as soon as it does, the slider in Home Assistant automatically slides back to the previous state. After this the switch no longer responds to HA. It does however still react to Google Assistant and/or the Smart Life app.

Any hints on how to fix this behaviour?

Thanks in advance and all the best!

Update: I have removed these switches from every app (smart life, google home) so only Hass.io has the interface. This does seem to improve behaviour. However it remains unpredictable. Sometimes the switches don’t react and then as soon as I restart Hass.io all commands that hadn’t been executed up to that point are fired in rapid succesion…

Hi,
I was able to access all my Jinvoo Smart plugs by following this guide and adding optional platform as ‘jinvoo_smart’.

hi there!
im new to HA. Therefor i struggle a lot.
I have a tuya switchan i set it up as “kngharv” told.
In my configuration.yaml under “switch:” i have following

  - platform: tuya
    host: 192.168.178.xxx
    local_key: f3a83578e8931xxx
    device_id: 01530667b4e62d517xxx
    switches:
      switch1:
        friendly_name:  schalter
        id: 1

BUT on HASSIO Webinterface there ist no switch visible. What can I do to switch on and off my device from webinterface.

Sorry for my horrible englisch :slight_smile:

I was able to use my tuya power strip via the cloud service but I’d like to keep things local. I was able to grab my local_key and device_id but it looks like HA no longer supports local connectivity. I’m on 0.83.2 and with the following switch settings:

  - platform: tuya
    name: powerstrip
    host: 192.168.1.239
    local_key: 6555asdfasdff02
    device_id: 02200145asdfasdfasdf
    switches:
      switch1:
        friendly_name: 'powersocket 1'
        id: 1
      switch2:
        friendly_name: 'powersocket 2'
        id: 2
      switch3:
        friendly_name: 'powersocket 3'
        id: 3
      switch4:
        friendly_name: 'powersocket 4'
        id: 4

I get the following error:

2018-12-01 23:33:41 ERROR (MainThread) [homeassistant.setup] Error during setup of component tuya
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/homeassistant/setup.py", line 148, in _async_setup_component
    component.setup, hass, processed_config)  # type: ignore
  File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/tuya.py", line 59, in setup
    username = config[DOMAIN][CONF_USERNAME]
KeyError: 'tuya'

Unfortunately this github repo of sean6541 is gone.
I’ve found another one, but this isn’t working:
https://github.com/aneisch/home-assistant-config/blob/master/custom_components/switch/tuya.py

Can some publish a working version?

1 Like

Great, thanks @boggiano!!

Hi all

I’ve just added my first Tuya (Smart Life) in HA.

The switch is a smart plug Houzetek AWP07L

It also measures power consumption that I can see in the Smart Life app.

Is there a way to get it also in HA?

BTW, I haven’t used the custom components, but only the integrated configuration

Thanks

1 Like

This is my config for Tuya:

tuya:
  username: !secret tuya_user
  password: !secret tuya_pass
  country_code: 31
  platform: tuya

I also added two switches, used the pull_devices and force_update procedures. I get no error messages, but I also see no sign of tuya or any switches in my dashboard. What could be causing this?

My experience with Tuya/Smart-life is the “tuya:” configuration does indeed work but only for switches, outlets and light bulbs. Also, the power monitoring does not report to HA.

These are (switchable) outlets; as described I haven’t got anything to work concerning Tuya yet. Minutes ago, I changed platform value to another value and that produced an error message. So, it is being loaded; it just refuses to pick up on my devices.

Tuya works for my cover fine for me.
But sometimes when i restart HA the following error message and the device is not found:
I restart HA then again and then the device works fine.
Has anyone the same issue?
(see below=)

Log Details (ERROR)
Mon Jan 21 2019 16:31:55 GMT+0100 (Mitteleuropäische Normalzeit)

Error during setup of component tuya
Traceback (most recent call last):
File “/usr/local/lib/python3.5/dist-packages/homeassistant/setup.py”, line 148, in _async_setup_component
component.setup, hass, processed_config) # type: ignore
File “/usr/lib/python3.5/asyncio/futures.py”, line 380, in iter
yield self # This tells Task to wait for completion.
File “/usr/lib/python3.5/asyncio/tasks.py”, line 304, in _wakeup
future.result()
File “/usr/lib/python3.5/asyncio/futures.py”, line 293, in result
raise self._exception
File “/usr/lib/python3.5/concurrent/futures/thread.py”, line 55, in run
result = self.fn(*self.args, **self.kwargs)
File “/usr/local/lib/python3.5/dist-packages/homeassistant/components/tuya.py”, line 65, in setup
tuya.init(username, password, country_code, platform)
File “/home/pi/.homeassistant/deps/lib/python3.5/site-packages/tuyapy/tuyaapi.py”, line 45, in init
self.discover_devices()
File “/home/pi/.homeassistant/deps/lib/python3.5/site-packages/tuyapy/tuyaapi.py”, line 108, in discover_devices
response = self._request(‘Discovery’, ‘discovery’)
File “/home/pi/.homeassistant/deps/lib/python3.5/site-packages/tuyapy/tuyaapi.py”, line 161, in _request
response_json = response.json()
File “/usr/local/lib/python3.5/dist-packages/requests/models.py”, line 897, in json
return complexjson.loads(self.text, **kwargs)
File “/usr/lib/python3/dist-packages/simplejson/init.py”, line 516, in loads
return _default_decoder.decode(s)
File “/usr/lib/python3/dist-packages/simplejson/decoder.py”, line 374, in decode
obj, end = self.raw_decode(s)
File “/usr/lib/python3/dist-packages/simplejson/decoder.py”, line 404, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Like many of you, I am using hassio to set up as much local control of my devices as I can. Because of that, I didn’t want to use the built in Tuya integration. Figuring out how to get this to work has been a challenge, partly because of the conflicting information between self-installed HA, Hassio, and Haspbian. Thanks to a bunch of folks on these forums, I finally got my pair of Tuya switches working locally as a custom device. I figured I should post what I did to get them working in case my route can help someone else. Thanks to everyone who has shared information on this topic. Apologies for the lack of links, I can’t currently post more than 2 links. I’ll update this post should that ever change.

This guide describes how I got a pair of TanTan Smart Sockets (B071LLWLLP at Amazon) working with local control on a Pi based Hassio install.

Getting the device_id and local_key values
Note, you’ll need to match your id/key pair to your device’s IP address. If you haven’t already set your devices up in an app (eg: Smart Life), set them up and perform the following steps one at a time to keep the data organized. Otherwise you will have to use trial-and-error to match the IP up to the IDs.

I used the Bluestacks android emulator to set up my switches in the Smart Life app. This made it easy to root and get the values. I highly recommend following HolgiHab’s guide for this (note, that links to the openhab community forum). To summarize the guide, you will:

  • Install Bluestacks Tweaker
  • Install Bluestacks (find a link on the Bluestacks Tweaker page)
  • Root Bluestacks: BmB8I63ea-o at YouTube
  • Install SmartLife version 3.6.1 (newer versions seem to be hiding the key and localKey data we need)
  • Install ES File Explorer
  • Navigate to the app’s data directory (in my case, /data/data/com.tuya.smartlife/shared_prefs
  • Open preferences_global_key<numbers and characters>.xml
  • Search for your ids and keys
  • Write these down along with each device’s IP

Set up the custom device type
You’ll need both tuya.py and it’s dependency, pytuya. I wasn’t able to get pytuya installed via pip, so ended up dropping it in locally and modifying tuya.py to look for it there. I’ve created a zip containing the appropriate custom component files and directory structure. Be smart and scan the zip file before you use it. You can do the following via ssh, samba, or Configurator.

  • Download the zip file
    The structure of the zip is:
switch/
   pytuya/
      __init__.py
   mytuya.py
  • Extract the contents of the zip to the /config/custom_components directory
    • You may need to create the custom_components directory
    • The resulting directory structure should look like this:
config/
  custom_components/
    switch/
       pytuya/
         __init__.py
       mytuya.py

Configure your switches
In /config/configuration.yaml, configure your switches

switch:
  - platform: mytuya
    host: 192.168.1.100
    local_key: 321df149e4ff79bf
    device_id: 1212d408ba1e7dc0bc7f
    name: tuya_01
    id: 1
    optimistic: 1
  - platform: mytuya
    host: 192.168.1.101
    local_key: 57f9c957db5909d7
    device_id: 75d262abb4366d5521ef
    name: tuya_02
    id: 1
    optimistic: 1

Restart
Finally, perform a config check, and then restart hassio. With any luck, your newly defined switches should show up and be functional!

Back-up!
Now that you’ve finally got this working (hopefully), don’t forget to back up your config at hassio.local/hassio/snapshots!

Edit 2019-02-27:
Release 0.88 broke the custom tuya integration. It appears that the custom component (“tuya” in this case) can no longer conflict with built in components (“tuya” in this case) even if they are unused. To solve this, you just need to rename config/custom_components/switch/tuya.py to config/custom_components/switch/mytuya.py, and update the “platform” key to “mytuya” in your configuration.yaml. I have updated the tutorial to reflect the change.

Also, the Tuya SmartLife app no longer stores the key and localKey data in the preferences_global_key* file. I wasn’t able to find a new location. I recommend you use an apk mirror to download an older version. I found that SmartLife 3.6.1 works fine.

The zip file has been updated with the new filename.

4 Likes

I’ve made something similiar for thermostat ( BHT-6000 Thermostat (tuya) support )

Have you found if there is a delay on retrieving states?
Example: if I manually set the thermostat hass is updated after a while

I know that it depends by scan_interval, but with low values the device does not responds

I’ve found that tuya app has low delay, so I think that it pushes data to tuya server on events, maybe is possible to listen to that states

If I toggle the switch manually or via the Smart Life app, it takes about a minute before the new state is reflected in hassio. I’ve not found a way to make it faster. Adding scan_interval made no difference.

do i need old tuya component to be listed in configuration file

From here you get the first 30 seconds delay:

def status(self):
    """Get state of Tuya switch and cache the results."""
    self._lock.acquire()
    try:
        now = time()
        if not self._cached_status or now - self._cached_status_time > 30:
            self._cached_status = self.__get_status()
            self._cached_status_time = time()
        return self._cached_status
    finally:
        self._lock.release()

That combined to the standard hass scan_interval (30 seconds) can explain your 1 minute delay

In my code i’m testing without the if statement and with a scan interval of 5sec, for now it seems to work and the average delay is acceptable (and maybe the scan interval can be lowered)

Remember that if the tuya app is open readings will fail

Anyone tried to get this going with the Eurom Heaters or any other re-branded Tuya Heater?
I got one hooked up and configured via the Tuya component but it is really unreliable, gets unreachable after a couple of days and need to be power cycled.
Would love to get local control over it to see if it fixes the problem.

Probably this can work out-of-the-box BHT-6000 Thermostat (tuya) support
Or at least can be a start point (most probably parameters ids won’t fit, but device specific ids can be retrieved with https://github.com/clach04/python-tuya and the following code)

import pytuya

d = pytuya.OutletDevice('<devid>','<devip>', '<devlocalkey>')
data = d.status()  
print('Data %r' % data)

No. In fact, you need to take it out. You are effectively defining your own custom tuya component. If you have the built in tuya component in your config file, the custom component will not work.