Giter Site home page Giter Site logo

rospogrigio / localtuya Goto Github PK

View Code? Open in Web Editor NEW

This project forked from mileperhour/localtuya-homeassistant

2.7K 2.7K 533.0 3.58 MB

local handling for Tuya devices

License: GNU General Public License v3.0

Python 100.00%
localtuya tuya tuya-api

localtuya's Introduction

localtuya's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

localtuya's Issues

New update by device is producing exception if device is not available

For the light bulbs, we can have some bulbs that are not logically off but physically off.

In that case, the new way of getting status (by device) produces exception traces in logs:

Traceback (most recent call last):
  File "/config/custom_components/localtuya/common.py", line 75, in __get_status
    status = self._interface.status()
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 381, in status
    data = self._send_receive(payload)
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 194, in _send_receive
    raise e
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 191, in _send_receive
    s.connect((self.address, self.port))
OSError: [Errno 113] Host is unreachable

Failed to get status when installing ceiling light

Hi, I've been having issues trying to install a ceiling light that works normally in Tuya.

I can see the ip and the Device ID in config via the GUI, but it throws up an error, logged as below. I have an energy monitoring switch set up that works so I don't think the component files are the cause.

Logger: custom_components.localtuya.pytuya
Source: custom_components/localtuya/pytuya/__init__.py:462
Integration: LocalTuya (documentation)
First occurred: 7:22:34 PM (7 occurrences)
Last logged: 7:23:12 PM

[68xxxxxxxxxxxxxxxxxxx4a] Failed to get status: Expecting value: line 1 column 1 (char 0)
[68xxxxxxxxxxxxxxxxxxx4a] Failed to get status:

If if helps, it's also showing this other error in the logs:

Logger: custom_components.localtuya.config_flow
Source: custom_components/localtuya/pytuya/__init__.py:206
Integration: LocalTuya (documentation)
First occurred: 7:22:43 PM (2 occurrences)
Last logged: 7:23:12 PM

Unexpected exception
Traceback (most recent call last):
  File "/share/CACHEDEV1_DATA/.qpkg/Home-Assistant/CONFIG_DIR/custom_components/localtuya/config_flow.py", line 236, in async_step_basic_info
    self.dps_strings = await validate_input(self.hass, user_input)
  File "/share/CACHEDEV1_DATA/.qpkg/Home-Assistant/CONFIG_DIR/custom_components/localtuya/config_flow.py", line 172, in validate_input
    detected_dps = await interface.detect_available_dps()
  File "/share/CACHEDEV1_DATA/.qpkg/Home-Assistant/CONFIG_DIR/custom_components/localtuya/pytuya/__init__.py", line 460, in detect_available_dps
    data = await self.status()
  File "/share/CACHEDEV1_DATA/.qpkg/Home-Assistant/CONFIG_DIR/custom_components/localtuya/pytuya/__init__.py", line 422, in status
    status = await self.exchange(STATUS)
  File "/share/CACHEDEV1_DATA/.qpkg/Home-Assistant/CONFIG_DIR/custom_components/localtuya/pytuya/__init__.py", line 401, in exchange
    msg = await self.dispatcher.wait_for(seqno)
  File "/share/CACHEDEV1_DATA/.qpkg/Home-Assistant/CONFIG_DIR/custom_components/localtuya/pytuya/__init__.py", line 206, in wait_for
    await asyncio.wait_for(self.listeners[seqno].acquire(), timeout=timeout)
  File "/opt/Home-Assistant/lib/python3.8/asyncio/tasks.py", line 490, in wait_for
    raise exceptions.TimeoutError()
asyncio.exceptions.TimeoutError

List of future improvements

I think it's a good idea to make a list of features and improvements we can make in the future. I'll start with my list:

  • Extract code and create base class for entities, e.g. LocalTuyaEntity based on a config entry.
  • Update entity on-the-fly when options are changed without having to restart Home Assistant (depends first bullet and #14).
  • Scanning support in config flow.
  • Use scanning to find a device before connecting to it, to handle dynamic IP address changes. I use a similar scheme in the Apple TV component.
  • Break out status polling from individual entities and inform entities about updates via the signal interface. This allows us to update devices with multiple entities, e.g. double gang switches, with one request instead of one per entity.
  • Make our pytuya implementation actually support the protocol, e.g. by inserting correct sequence number (and other stuff that needs to be handled). The outcome I'm after is to have the network connection up at all time instead of connecting, sending command and immediately disconnect when done. I believe this will be a lot more stable and faster.
  • Convert pytuya to asyncio (and the rest of the integration as well).
  • Add generic sensor and binary_sensor platforms that can read any DPS value and present as state.
  • Easy set up of helper sensor, e.g. integration sensor that calculates kWh for used energy.
  • General code clean up, removing commented code (it's still available via git history), remove print statements and change some to debug, run black, pylint and flake8 on all code.
  • Improve documentation, translations in config flows, etc.

Anything I have missed? After some discussion we could make a priority list, create issues for things to do and come up with a roadmap (as supported here on GitHub).

Support for Door / Window sensors

Came across your integration today and managed to set up my GoSund switched outlets with no trouble . Thanks.

I also have a Door Sensor (https://www.amazon.co.uk/gp/product/B07GXTV4C1/ref=ppx_yo_dt_b_asin_title_o07_s00?ie=UTF8&psc=1) and wondered if you plan to add support for this type of device?

It links with no problem and worked for about 5 mins and then became unavailable and has stayed that way ever since.
Looking at the logs it can no longer connect to the device. I believe the device is only connected to the WiFi for a very brief period each time the state changes in order to save battery life.

Cant add light bulb RGBCCT wifi using config flow

2020-10-11 (5)

It is fn unknown error occurred. See log for details.

Log
Logger: custom_components.localtuya.config_flow
Source: custom_components/localtuya/pytuya/init.py:224
Integration: LocalTuya integration (documentation)
First occurred: 12:44:54 (1 occurrences)
Last logged: 12:44:54

Unexpected exception
Traceback (most recent call last):
File "/config/custom_components/localtuya/config_flow.py", line 235, in async_step_basic_info
self.dps_strings = await validate_input(self.hass, user_input)
File "/config/custom_components/localtuya/config_flow.py", line 171, in validate_input
detected_dps = await hass.async_add_executor_job(
File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/config/custom_components/localtuya/pytuya/init.py", line 271, in detect_available_dps
data = self.status()
File "/config/custom_components/localtuya/pytuya/init.py", line 244, in status
return self.exchange(STATUS)
File "/config/custom_components/localtuya/pytuya/init.py", line 239, in exchange
return self.exchange(command, dps)
File "/config/custom_components/localtuya/pytuya/init.py", line 224, in exchange
data = s.recv(1024)
socket.timeout: timed out

Logger: custom_components.localtuya.pytuya
Source: custom_components/localtuya/pytuya/init.py:273
Integration: LocalTuya integration (documentation)
First occurred: 12:44:54 (1 occurrences)
Last logged: 12:44:54

Failed to get status: timed out

support for nebula lights

Hello, I just got this and it uses a different dps for status, I tried 1.2 and master. It's working on 1.2 by modifying the DEFAULT_ID from 1 to 20.
Below is the DPS:

{ dps:
{ '20': true,
'21': 'white',
'22': 10,
'24': '013103e803e8',
'25': '000e0d00002e03e802cc00000000',
'26': 120,
'101': 1000,
'102': false,
'103': true } }

102 - laser light control/status
103 - nebula control/status
22 - laser brightness default 800 (80%) max 1000 (100%)
101 - laser/rotation speed default 500 (50%) max 1000 (100%)
24 - color (first four digit - color, 2nd four digit - contrast, last four digit - brightness of nebula)
26 - timer in seconds
25 -?
20 - state
21 - mode (colour/white)

Forcing light status update from "unavailable" to "on"

Hi @rospogrigio @postlund @ultratoto14,
I have noticed that often when I turn off the light bulb from the switch, when I turn it on after many hours, the status remains on "unavailable" and does not update even after many minutes. (even after the smartlife app detects the status update)

To update the status, I have to click on settings / server management / Reload LocalTuya integration

To change state from "on" to "unavailable", however, takes a few seconds.

If I try to turn the light back on immediately after turning it off with the switch, however, the status from unavailable to off changes quite quickly, about a minute.

Is it possible to force the update of the status of the bulbs (also switches?) turned off by the switch?

Thanks

Memory/load

Hi @postlund , more than an issue is a discussion I'd like to have. In the recent weeks, I have noticed HA having an increasing load on my Rpi3, the memory usage increases and I have set an auto-reboot each morning. Also, I have load peaks during which the system becomes unresponsive, and I usually need to reboot it during the day. Now, I've been wondering whether this is due to HA, and also whether localtuya might play a role. I am a C++ developer so I don't know much about python and how it behaves with memory allocation but I would like to have your opinion, and also would like to know if anybody else noticed what I'm reporting.
Also, I don't know if you have any suggestion for troubleshooting, I am seriously thinking to upgrade to Rpi4 since this is becoming more and more annoying every day.
Thank you

Scene mode

@rospogrigio @postlund @ultratoto14

Hi,
I remember that by setting the value to 63 of the bulb supported features (in local tuya I see the value 19) the "effect" menu was displayed, as happens in the original Smart Life app.

In the other custom component (Tuya Custom) even though the scene menu was displayed, it was still empty.

Could you bring the scenes from the Smart Life app back to Local tuya?

It is not an indispensable function, but it would be an added value.

homeassistant:
customize:
light.xxxx: #entity name
supported_features: 63

86342278-ab47af80-bc57-11ea-8d49-0b363e9b2159

86342270-a7b42880-bc57-11ea-96ec-eefaef86fed7

Error while setting up switch

I am seeing the below error in log after adding config in yaml file.

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 231, in async_setup
    result = await component.async_setup_entry(hass, self)  # type: ignore
  File "/config/custom_components/localtuya/__init__.py", line 135, in async_setup_entry
    device = TuyaDevice(hass, entry.data)
  File "/config/custom_components/localtuya/common.py", line 98, in __init__
    self._interface = pytuya.TuyaInterface(
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 205, in __init__
    self.cipher = AESCipher(self.local_key)
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 156, in __init__
    self.cipher = Cipher(algorithms.AES(key), modes.ECB(), default_backend())
  File "/usr/local/lib/python3.8/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py", line 35, in __init__
    self.key = _verify_key_size(self, key)
  File "/usr/local/lib/python3.8/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py", line 20, in _verify_key_size
    raise ValueError("Invalid key size ({}) for {}.".format(
ValueError: Invalid key size (40) for AES.

My config is as follows. I am using the ip address of the smart plug..not sur eif this should be the ip of home assistant host?

localtuya:
  - host: 192.168.1.26
    device_id: XXXXX
    local_key: XXXX
    friendly_name: SmartPlug_Office
    protocol_version: "3.3"
    entities:
      - platform: switch
        friendly_name: SmartPlug_Office
        id: 1
        current: 18
        current_consumption: 19
        voltage: 20

Different fan control dimmers

Hi, i have two fan controllers, they have 5 step control step and can't control it now.

  1. This if first product with additional light turn on off, which works. https://aliexpress.com/item/4000214394624.html

Standard Function Set

Code Type Values
switch Boolean {true,false}
light Boolean {true,false}
fan_speed_percent Integer {"min":1,"max":5,"scale":0,"step":1}

Standard State Set

Code Type Values
switch Boolean {true,false}
light Boolean {true,false}
fan_speed_percent Integer {"min":1,"max":5,"scale":0,"step":1}
  1. In app it has only 5 steps of controlling a fan, but it shows more https://aliexpress.com/item/4000235813178.html

Standard Function Set

Code Type Values
switch Boolean {true,false}
fan_speed Enum {"range":["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26"]}
countdown Enum {"range":["0","1","2","3","4","5","6"]}

Standard State Set

Code Type Values
switch Boolean {true,false}
fan_speed Enum {"range":["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26"]}
countdown Enum {"range":["0","1","2","3","4","5","6"]}

Thanks for integration, hope it helps.

[FEATURE] Polling Interval

There doesn't seem to be a way to set the poling rate, which currently seems to be every 30 seconds. With 15 devices, and async not working yet, it takes quite a toll on the server.

Can you add a poll_interval property or something similar? Thank you!

Color temperature range

Hello,
thanking you for all the work, just for information and to keep track of the things to develop, as you advised me to do, I report that the color temperature works, but the value is not reported correctly and does not correspond with the balance of the SmartLife app and therefore of the light bulb.

You should be able to set the right range through a minimum and maximum value of the kelvin degrees supported by the bulb, as you did for the brightness.

Here are some examples:

Center of the slider on LocalTuya (color temp 258) corresponds to 13% on Smartlife app (instead it should be 50%)

Other test:

SmartLife color temp: 0%
LocalTuya color_temp: 370

SmartLife color temp: 10%
LocalTuya color_temp: 284

SmartLife color temp: 50%
LocalTuya color_temp: -57

SmartLife color temp: 100%
LocalTuya color temp: -480

Thanks

If you need more information I will be happy to provide it

Good night

Disconnect from Tuya Cloud

Is it possible to disconnect the devices from Tuya Cloud, and only use them local?
I tried to prevent them from connecting to the internet, but the devices became unavailable. A reboot did not help, and they were not showing as connected devices in my router anymore.
After allowing internet access again, and reloading the integration, they were available again.

When the device is removed from the Tuya app (with internet access allowed) they will go to pairing mode (flashing light).

I would like to use them only locally, to make my network more secure.

Circadian Lighting

FIXED - I needed to set the options
min_colortemp: 3000
max_colortemp: 5700

I have some RGBWW lights that Im trying to use with Circadian Lighting component that will not be working for CT option? .Any insight into why it wont work?

works for XY and RGB but not CT?

Example of Attributes available

min_mireds: 154
max_mireds: 370
brightness: 254
color_temp: 299
hs_color: 27, 48.6
rgb_color: 255, 186, 131
xy_color: 0.468, 0.375
friendly_name: Fridge Light
supported_features: 19

Error message: The length of the provided data is not a multiple of the block length

I got this error messages which not sure why, also disable for the device on tuya integrations. Still got this messages during the startup, unsure what happen:

    raise ValueError("Config entry has already been setup!"),
ValueError: Config entry has already been setup!,
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 155, in async_setup_entry,
    return await hass.data[DOMAIN].async_setup_entry(entry),
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 67, in async_setup_entry,
    result = await component.async_setup_entry(hass, self)  # type: ignore,
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 231, in async_setup,
Traceback (most recent call last):,
2020-10-13 14:38:59 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry AC Front Guest Room for sensor,
Failed to update status of device [xxx.xxx.xxx.xxx]: [The length of the provided data is not a multiple of the block length.]

Control Tuya RGB (W or C or CW) from localtuya

Control Tuya RGB (W or C or CW) from localtuya
I have several bubs from tuya with RGB + WC and RGB + WW and bought configuration
Just tell me what I need to test to send you feedback for you can accomplish this

Unable to add my devices - errors

Hi,

I am having some issues with the LocalTuya Integration, I am getting errors when trying to add my devices.

I installed LocalTuya via HACS, all appeared to install without issue however when i try to add a device i get an error with a failure to authenticate.

Environment details -

HASSIO - 0.117.2
HACS - 1.6.1
LocalTuya - 3.0.3

I got my IDs using the TuyaAPI instructions here
https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP.md

Which when running the cli-wizard gave me an output like this
[ { name: 'Study Lamp', id: '938xxxxxxxxxx60c', key: '93xxxxxxxxx0c' } ]
Replaced with xxxx's just to mask it.

Assuming ID is my "Device ID" and Key is "Local Key" when trying to add my device on the integrations page

image

Logs showing the following

image

Log Detail

unexptected-exception.txt
unexptected-exception-2.txt
[93xxxxxx0c] Failed to get status.txt
[938fxxxxxxxx60c] Failed to get status.txt
[938xxxxxxx60c] Failed to get status Expecting value line 1 column 1 (char 0).txt

[QUESTION] Setting Device Area - Not Using Config Flow

Is it possible to assign devices to areas without using the config flow method to create the devices?

I added my devices manually in configuration.yaml and am unable to assign a device to an area in the Config Devices Dashboard.

Maybe an area: property can be set for each device in the configuration file?

configuration check error

I want to use the new integration (2.0) with config flow, so i added only localtuya: to configuration.yaml, but when doing a configuration check, it claims:
Invalid config for [localtuya]: required key not provided @ data['localtuya'][0]['device_id']. Got None required key not provided @ data['localtuya'][0]['entities']. Got None required key not provided @ data['localtuya'][0]['friendly_name']. Got None required key not provided @ data['localtuya'][0]['host']. Got None required key not provided @ data['localtuya'][0]['local_key']. Got None. (See ?, line ?).

I think this is not the expected behaviour, right?

Suggestion to move YAML configuration to component

Currently we define new entities on platform level like this:

switch:
  - platform: localtuya
    host: 192.168.0.1
    local_key: 1234567891234567
    device_id: 12345678912345671234
    name: tuya_01
    friendly_name: tuya_01
    protocol_version: 3.3
    current: 18
    current_consumption: 19
    voltage: 20

We also support two notions (in some case), where a single device can be defined "directly" but two or more are defined under another key, e.g. switches: like this:

switch:
 - platform: localtuya
    host: 192.168.0.1
    local_key: 1234567891234567
    device_id: 12345678912345671234
    name: tuya_01
    friendly_name: tuya_01
    protocol_version: 3.3
    switches:
      sw01:
        name: main_plug
        friendly_name: Main Plug
        id: 1
        current: 18
        current_consumption: 19
        voltage: 20
      sw02:
        name: usb_plug
        friendly_name: USB Plug
        id: 7  

This has a few cons, e.g. not being consistent and you can't mix different platforms for the same device. I suggest that we move all configuration to the component so we can write something like this:

localtuya:
    host: 192.168.0.1
    local_key: 1234567891234567
    device_id: 12345678912345671234
    name: tuya_01
    protocol_version: 3.3
    entities:
      - platform: switch
        friendly_name: Main Plug
        id: 1
        current: 18
        current_consumption: 19
        voltage: 20
      - platform: switch
        friendly_name: USB Plug
        id: 7  

This provides a consistent configuration interface which also maps directly to how config entries work. It would be a big breaking change, but would be a good one.

Error during startup: Config entry has already been setup!

Seems to be some issue when setting up entities via YAML, yielding these error messages:

2020-10-18 20:28:10 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry Tuya Device (YAML) for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 228, in async_setup
    result = await component.async_setup_entry(hass, self)  # type: ignore
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 67, in async_setup_entry
    return await hass.data[DOMAIN].async_setup_entry(entry)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 155, in async_setup_entry
    raise ValueError("Config entry has already been setup!")
ValueError: Config entry has already been setup!
2020-10-18 20:28:10 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry Tuya Device (YAML) for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 228, in async_setup
    result = await component.async_setup_entry(hass, self)  # type: ignore
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 67, in async_setup_entry
    return await hass.data[DOMAIN].async_setup_entry(entry)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 155, in async_setup_entry
    raise ValueError("Config entry has already been setup!")
ValueError: Config entry has already been setup!
2020-10-18 20:28:10 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry Tuya Plug 2 (YAML) for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 228, in async_setup
    result = await component.async_setup_entry(hass, self)  # type: ignore
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 67, in async_setup_entry
    return await hass.data[DOMAIN].async_setup_entry(entry)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 155, in async_setup_entry
    raise ValueError("Config entry has already been setup!")
ValueError: Config entry has already been setup!
2020-10-18 20:28:10 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry Tuya Plug 2 (YAML) for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 228, in async_setup
    result = await component.async_setup_entry(hass, self)  # type: ignore
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 67, in async_setup_entry
    return await hass.data[DOMAIN].async_setup_entry(entry)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 155, in async_setup_entry
    raise ValueError("Config entry has already been setup!")
ValueError: Config entry has already been setup!
2020-10-18 20:28:10 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry Tuya Plug 3 (YAML) for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 228, in async_setup
    result = await component.async_setup_entry(hass, self)  # type: ignore
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 67, in async_setup_entry
    return await hass.data[DOMAIN].async_setup_entry(entry)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 155, in async_setup_entry
    raise ValueError("Config entry has already been setup!")
ValueError: Config entry has already been setup!
2020-10-18 20:28:10 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry Tuya Plug 3 (YAML) for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 228, in async_setup
    result = await component.async_setup_entry(hass, self)  # type: ignore
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 67, in async_setup_entry
    return await hass.data[DOMAIN].async_setup_entry(entry)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 155, in async_setup_entry
    raise ValueError("Config entry has already been setup!")
ValueError: Config entry has already been setup!

Config looks like this:

localtuya:
  - host: 192.168.1.44  
    local_key: xxx
    device_id: xxx
    friendly_name: Tuya Plug 1
    protocol_version: "3.3"
    entities:
      - platform: switch
        friendly_name: Kitchen Plug 1
        id: 1
        current: 18
        current_consumption: 19
        voltage: 20
      - platform: sensor
        friendly_name: Plug 1 Current
        id: 18
        device_class: current # 18 # Optional
        scaling: 0.001
        unit_of_measurement: "A"
      - platform: sensor
        friendly_name: Plug 1 Power
        id: 19
        device_class: power
        scaling: 0.1
        unit_of_measurement: "W"
      - platform: sensor
        friendly_name: Plug 1 Voltage
        id: 20
        device_class: voltage
        scaling: 0.1
        unit_of_measurement: "V"
        # voltage: 20
  - host: 192.168.1.51
    local_key: yyy
    device_id: yyy
    friendly_name: Tuya Plug 2
    protocol_version: "3.3"
    entities:
      - platform: switch
        friendly_name: Kitchen Plug 2
        id: 1
        current: 18
        current_consumption: 19
        voltage: 20
      - platform: sensor
        friendly_name: Plug 2 Current
        id: 18
        device_class: current # 18 # Optional
        scaling: 0.001
        unit_of_measurement: "A"
      - platform: sensor
        friendly_name: Plug 2 Power
        id: 19
        device_class: power
        scaling: 0.1
        unit_of_measurement: "W"  
      - platform: sensor
        friendly_name: Plug 2 Voltage
        id: 20
        device_class: voltage
        scaling: 0.1
        unit_of_measurement: "V"
  - host: 192.168.1.52
    local_key: zzz
    device_id: zzz
    friendly_name: Tuya Plug 3
    protocol_version: "3.3"
    entities:
      - platform: switch
        friendly_name: TV Plug
        id: 1
        current: 18
        current_consumption: 19
        voltage: 20
      - platform: sensor
        friendly_name: TV Plug Current
        id: 18
        device_class: current # 18 # Optional
        scaling: 0.001
        unit_of_measurement: "A"
      - platform: sensor
        friendly_name: TV Plug Power
        id: 19
        device_class: power
        scaling: 0.1
        unit_of_measurement: "W"  
      - platform: sensor
        friendly_name: TV Plug Voltage
        id: 20
        device_class: voltage
        scaling: 0.1
        unit_of_measurement: "V"

Reported in #86 (output copied from there). Will have to look into that.

Unable to add Lumary LED Controller

Hello, I'm unable to add the Lumary RGBCCT LED Controller after trying to add it via config flow. On the "Add Tuya device" screen it says "An unknown error occurred. See log for details." Here's the log as well:

2020-10-02 23:21:08 ERROR (MainThread) [custom_components.localtuya.config_flow] Unexpected exception
Traceback (most recent call last):
  File "/config/custom_components/localtuya/config_flow.py", line 235, in async_step_basic_info
    self.dps_strings = await validate_input(self.hass, user_input)
  File "/config/custom_components/localtuya/config_flow.py", line 171, in validate_input
    detected_dps = await hass.async_add_executor_job(
  File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 271, in detect_available_dps
    data = self.status()
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 244, in status
    return self.exchange(STATUS)
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 239, in exchange
    return self.exchange(command, dps)
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 224, in exchange
    data = s.recv(1024)
socket.timeout: timed out

Add status (binary_)sensor for each device

It's currently very hard to provide decent feedback to the user regarding if the connection works or not. It's also a bit tricky since the same error affects all the entities at the same time, so we would over-report problems. I suggest that we add a new sensor per device, which shows the current state and can include additional error information via attributes. That way we can signal if the whole device is broken or and and possibly also what is broken. I know some other integrations do this as well. Either we keep it simple with a binary_sensor or we use a regular sensor which gives us better feedback via state name.

What do you think @rospogrigio?

Failed to update status of device

When adding my switches through the UI everything works fine. I was able to setup template to show the power consumption as well. But after a few minutes somehow the connection gets lost and never comes back. I can only see these log messages every few seconds:

2020-10-15 23:08:37 ERROR (SyncWorker_47) [custom_components.localtuya.common] Failed to update status of device 192.168.178.51
2020-10-15 23:08:42 ERROR (SyncWorker_26) [custom_components.localtuya.common] Failed to update status of device 192.168.178.37
2020-10-15 23:08:46 ERROR (SyncWorker_59) [custom_components.localtuya.common] Failed to update status of device 192.168.178.52

Maintain the last state of the bulb

Hello,
I have always had the problem that when the electricity goes out, on its return, all the bulbs turn on and stay on.

Would it be possible to plan to keep the last state when the electricity returns?

I know some bulbs have this feauteres, but on mine this setting is not present.

@rospogrigio @postlund @ultratoto14 I trust you! :-)

Problem with setting up LED light and cover

Hi,
I have some problems with my Tuya devices, that work normally in SmartLife.

  1. First one is LED light. I use two or even three kinds of lights, most of them work normally with localtuya (configured via YAML). One kind causes problem, It's all the time offline. It's defined like other devices:
  - host: some_ip
    device_id: some_id
    local_key: some_key
    friendly_name: some_name
    protocol_version: "3.3"
    entities:
      - platform: light
        friendly_name: name
        id: 1

It's DPS (below) is differend from other devices, so I changed ID from 20 to 1, but it didn't change anything. IP, key and ID are correct.

        "dps":{
          "1":false,
          "10":"ffff2e0600fff24d00ff16ff00008affff0000ffac00",
          "2":"white",
          "3":91,
          "4":178,
          "5":"6e3c000021ff6c",
          "6":"bd76000168ffff",
          "7":"ffff500100ff00",
          "8":"ffff80040000ff58ff00ff0000ffd400000000000000",
          "9":"ffff5001ff0000"
        }
  1. Second device - blind curtain switch (https://a.aliexpress.com/_BU4g2c). I even don't know how to configure it :) I have IP, ID and local key, but in DPS I see only this:
        "dps":{
          "1":"3"
        }

In Tuya app, this device has three control buttons (up, down and pause). is it possible to control it via localtuya?

  1. All my LED lamps are RGB, what have I to add to YAML configuration to see dimming, color and temperature controls? Now I can only turn them on and off.

Thank you in advance for support.

Tuya Ceiling Fan Light Controller

Hey Guys,
I see that you are working to make the tuya stuff local and wanted to throw some data your way regarding the QIACHIP Ceiling Fan Remote Control Kit, WI-FI Smart Universal Ceiling Fan with Amazon Alexa
by QIACHIP Store
Learn more: https://www.amazon.com/dp/B07RYD632T/ref=cm_sw_em_r_mt_dp_5CNCFbHYWT4JV

I was able to pair this thing to the Tuya App on my iPhone and was able to find it get it paired on iot.tuya.com.
Not sure what you need to get it to work locally. I was able to pair the controller as a switch and it does turn the fan on and off. However, I was not able to add the device as a fan, so I have no control over the speed at this time.

So I pulled what I could from iot.tuya.com.
Standard Function Set

Code Type Values
switch Boolean {true,false}
fan_speed Enum {"range":["1","2","3"]}
countdown Enum {"range":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"]}
light Boolean {true,false}
fan_beep Boolean {true,false}

Standard State Set

Code Type Values
switch Boolean {true,false}
fan_speed Enum {"range":["1","2","3"]}
countdown Enum {"range":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"]}
light Boolean {true,false}
fan_beep Boolean {true,false}

Zigbee devices

Hi, could you please consider adding support for Zigbee devices connected via Tuya gateway, e.g. temperature / humidity sensors, thermostatic radiator valves etc.?

Unable to add string like sensor

I wanted to use sensors to help debugging light scenes.
I added a sensor in yaml with ID 25

  - host: 192.168.15.160
    device_id: xxxxxxxxxxxxxxxxxx
    local_key: xxxxxxxxxxxxxxxx
    friendly_name: RGBW Led Strip LSC
    protocol_version: "3.3"
    entities:
      - platform: light
        friendly_name: RGBW Led Strip LSC
        id: 20
        color_mode: 21
        brightness: 22
        color_temp: 23
        color: 24
        brightness_upper: 1000
        color_temp_min_kelvin: 2700
        color_temp_max_kelvin: 6500

      - platform: sensor
        friendly_name: RGBW Led Strip LSC - 25
        id: 25

Even if not set a scale factor of 1.0 is applied, preventing the ability to have String sensors.

wrong folder after last update (3.0.2)

it seems that the last update has a bug. it's writing files in directory /config/custom_components/localtuya/custom_components/localtuya.
Had to move them manually.

Add contextual logging to platforms

Recently I added contextual logging in pytuya, so all log points contains the device id. This helps a lot when debugging as it's really hard to decode which log points comes from which device (due to the async network of communication). We should do the same in LocalTuyaEntity, so all subclasses can use for instance self.log to log with contextual output. We can start by adding device id here as well.

Failure current_consumption update

Hi,
I installed localtuya and, after retrieving the localKeys, everything works, but I have a problem.
The current_consumption value of the switch not update automatically, but if I open the app from the smartphone and go to the electric page, it also updates on hassio.

I tried with both integration procedures: yaml and flow.
I used this PD:
current: 18
current_consumption: 19
voltage: 20

Can you help me?
Thanks

Unable to connect to a switch

I have successfully added 4 switches with the integration. They were all available through the auto discovery with HACS integration. One of the switches were not available to so tried a manual connection. This switch is not connecting and giving me error for some reason. The switch is working find and is available in the Smart Life and and also in the list using Tuya CLI(wizard).

What should I do to get it working?

Suggestions for datapoints to use in config flow

It's quite tedious and sometime hard to know which datapoints to use. We have some knowledge of which datapoints that are commonly used, so I suggest that we integrate a suggestion system into the config flow so we get pre-filled settings. We can start by building it using DP indices, but it would be good if this system can be extended with more fine-grained control later. We should also not suggest already used datapoints, e.g. if a double gang switch is added we should suggest the second outlet when adding the second switch.

I can take on the task of creating an outcast to this.

Integration tuya+gsm alarm

I have some alarms from aliexpress. They work with tuya apps and have gsm channels. What need for support this alarms?

This alarms have dps from 1 to 40, but need change only dps 1. It set and get string value (for status of alarm): disarmed, armed, home, stay.

Can localtuya support it?

Registering localtuya as default component in HACS

@postlund I am trying to register localtuya as a HACS default component but I am having difficulties with which you can help me out. Some automatic checks are failing:

  1. I needed to create this PR: home-assistant/wheels-custom-integrations#161 but a check fails. I believe it wants some kind of requirement about the python version to be stated in the manifest.json , do you know what we should add and where?
  2. the PR for HACS is hacs/default#662 . Apart from the wheels failure above, I get the following error in one of the checks:
::INFO:: Category: integration
::INFO:: Repository: rospogrigio/localtuya-homeassistant
Error:  ::error:: No hacs.json file in the root of the repository.

But hacs.json is actually present in the root... why is it not being detected? should it be copied also within custom_components/localtuya ?

Thank you for your help

Changing the brightness parameter.

Hi, I have a Tuya dimmer in which the brightness is 0-1000, but the integration allows you to change the brightness only from 0-255 and the lamp glows dimly. can I add the ability to change this parameter ?

dps: { '20': false, '21': 'white', '22': 1000, '26': 0 }

Component error: localtuya - Integration 'localtuya' not found.

I just upgraded to 3.0.3 in HACS and I got this error message "Component error: localtuya - Integration 'localtuya' not found."

It was working for my switch before but not my light (which I've raised another issue for).

I've commented it out of my configuration.yaml for now. Am I the only one seeing this?

help with the integration

Hi
I have added one of my devices through the integration localtuya. Now I want to add one more.
How can I added because I don't see an option there. Should I use the configuration.yaml??

4 speed ceiling fan/light dimmer and an air purifier..

I guess I get to break things.

I have a combo light/fan controller also, that's tuya based.

It is a 4 speed controller, and a can dim the light.

Code Type Values
switch Boolean {true,false}
fan_speed Enum {"range":["1","2","3","4"]}
light Boolean {true,false}
bright_value Integer {"min":10,"max":1000,"scale":0,"step":1}

Note that is a 4 speed controller, and not 3. So 'low', 'medium', 'high' does not fit.

Here's what is actually discovered:
fan-controller

Now, to really mess this up.. I also have a air purifier, that's tuya based.

iot-tuya says this for it:

code type values
switch boolean true,false
lock boolean true,false
light boolean true,false
countdown enum range:["cancel"]

but this is so wrong..
air-purifier

It shows the 4 filters, the fan speed (low/medium/high/auto), power on/off, child lock, air quality, and few other things.

I am planning on digging around more in the code for this.. once I figure out how to do development work in it.

One of the questions I have - is an air purifier a fan, or something else in home-assistant?

TypeError: argument of type 'NoneType' is not iterable

Hello everyone,
I'm trying to add smart sockets via this integration but I get 2 errors. I'll briefly explain the situation and then I'll attach the error logs.

I own 6 smart sockets from 2 different brand, teckin and bakibo both have the possibility to track the energy consumption and both brands works fine the official "Tuya" integration.
I obtained, via the tuya developer account both the Device ID and the product ID (or the Local key) list of all my product (How will I proceed once the trial will end?)

I firstly removed the official Tuya Integration and then, after reboot, I installed the integration via HACS, rebooted, and, via the auto discovery feature, try to add my sockets, it found but when I tried to config it gets an error. Here it's the error in the GUI:
GUI
I'm sure both the Devide ID and the product ID are exact (direct copy).
On the logs I got:

Logger: custom_components.localtuya.pytuya
Source: custom_components/localtuya/pytuya/__init__.py:429
Integration: LocalTuya integration (documentation, issues)
First occurred: 22:59:15 (1 occurrences)
Last logged: 22:59:15

[031530xxxxxxxxxxxxx] Failed to get status: argument of type 'NoneType' is not iterable
Traceback (most recent call last):
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 466, in detect_available_dps
    data = await self.status()
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 429, in status
    if "dps" in status:
TypeError: argument of type 'NoneType' is not iterable

and also:

Logger: custom_components.localtuya.config_flow
Source: custom_components/localtuya/pytuya/__init__.py:429
Integration: LocalTuya integration (documentation, issues)
First occurred: 22:59:15 (1 occurrences)
Last logged: 22:59:15

Unexpected exception
Traceback (most recent call last):
  File "/config/custom_components/localtuya/config_flow.py", line 238, in async_step_basic_info
    self.dps_strings = await validate_input(self.hass, user_input)
  File "/config/custom_components/localtuya/config_flow.py", line 173, in validate_input
    detected_dps = await interface.detect_available_dps()
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 466, in detect_available_dps
    data = await self.status()
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 429, in status
    if "dps" in status:
TypeError: argument of type 'NoneType' is not iterable

--------------EDIT:

Sometimes, at the first try it gives me "An unknown error occurred. See log for details."

in the logs:

Unable to find referenced entities switch.xxxxxxxxxxxxxxxxxxxxx

[xxxxxxxxxxxxxxxxxxxxxxxxx] Failed to get status: argument of type 'NoneType' is not iterable
Traceback (most recent call last):
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 466, in detect_available_dps
    data = await self.status()
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 429, in status
    if "dps" in status:
TypeError: argument of type 'NoneType' is not iterable

Unexpected exception
Traceback (most recent call last):
  File "/config/custom_components/localtuya/config_flow.py", line 238, in async_step_basic_info
    self.dps_strings = await validate_input(self.hass, user_input)
  File "/config/custom_components/localtuya/config_flow.py", line 173, in validate_input
    detected_dps = await interface.detect_available_dps()
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 466, in detect_available_dps
    data = await self.status()
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 429, in status
    if "dps" in status:
TypeError: argument of type 'NoneType' is not iterable
[xxxxxxxxxxxxxxxxxxxxxxxx] Failed to get status: Expecting value: line 1 column 1 (char 0)
Traceback (most recent call last):
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 466, in detect_available_dps
    data = await self.status()
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 428, in status
    status = await self.exchange(STATUS)
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 413, in exchange
    payload = self._decode_payload(msg.payload)
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 515, in _decode_payload
    return json.loads(payload)
  File "/usr/local/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

---------------------------------- finish edit------------------

So I tried the traditional way:
Code
and I get:

Logger: custom_components.localtuya.common
Source: custom_components/localtuya/pytuya/__init__.py:593
Integration: LocalTuya integration (documentation, issues)
First occurred: 23:12:54 (3 occurrences)
Last logged: 23:13:03

Connect to 192.168.178.47 failed
Traceback (most recent call last):
  File "/config/custom_components/localtuya/common.py", line 141, in _make_connection
    self._interface = await pytuya.connect(
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 593, in connect
    _, protocol = await loop.create_connection(
  File "/usr/local/lib/python3.8/asyncio/base_events.py", line 1025, in create_connection
    raise exceptions[0]
  File "/usr/local/lib/python3.8/asyncio/base_events.py", line 1010, in create_connection
    sock = await self._connect_sock(
  File "/usr/local/lib/python3.8/asyncio/base_events.py", line 924, in _connect_sock
    await self.sock_connect(sock, address)
  File "/usr/local/lib/python3.8/asyncio/selector_events.py", line 494, in sock_connect
    return await fut
  File "/usr/local/lib/python3.8/asyncio/selector_events.py", line 526, in _sock_connect_cb
    raise OSError(err, f'Connect call failed {address}')
ConnectionResetError: [Errno 104] Connect call failed ('192.168.178.47', 6668)

and also:

Logger: custom_components.localtuya.common
Source: custom_components/localtuya/pytuya/__init__.py:429
Integration: LocalTuya integration (documentation, issues)
First occurred: 23:13:04 (3 occurrences)
Last logged: 23:13:19

Connect to 192.168.178.47 failed
Traceback (most recent call last):
  File "/config/custom_components/localtuya/common.py", line 151, in _make_connection
    status = await self._interface.status()
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 429, in status
    if "dps" in status:
TypeError: argument of type 'NoneType' is not iterable

as you can see I tried also another socket.
Anyone could help me?
Thank you

Energy monitoring not refreshing

Energy monitoring sometimes refreshes the very second the switch toggles, but sometimes it doesn't refresh at all. Heater in the smartplug is running, but the current and current consumption show 0, or vice-versa (heater is off, but the consumption shows 10A / 2300W). Restarting HA may or may not help resolving it (cca 50% success rate).

Additional issue for me: status changes (from physical buttons) are not instant, instead they take from 10 to 30 seconds (as before the last release).

System
Operating system
Raspbian GNU/Linux 10 (buster) on Raspberry PI 4B
Docker version
19.03.13

Supervisor version: 247
Host system version: Home Assistant 0.116.3, running on Raspberry Pi 4B in Docker (Supervised install)

looses connection to bulb after every ha restart

First, thanks for the integration.
When I have set it up, it works great, unfortunatly after every ha restart this integration seems to loose the connection, as the bulb gets unavailable. I then have to remove it and add it again, then it works fine.

Failed to authenticate with Tuya Switch

Thanks for your custom component.
I have a problem when add Tuya switch by Tuyalocal:

  1. Home Assistant 0.115.6
  2. LocalTuya: lastest release.
  3. Yesterday, i add an Tuya 2 Gang switch to my HA (I had localkey an DevID) and it worked.
  4. Today, i changed my router (because i go to my farther-in-law house), when i add Tuya device, system noti: Failed to authenticate with device. Verify that device id and local key are correct.
    Screenshot 2020-10-05 200415
    Log: "
    Logger: custom_components.localtuya.pytuya
    Source: custom_components/localtuya/pytuya/init.py:273
    Integration: localtuya (documentation)
    First occurred: 7:57:12 PM (3 occurrences)
    Last logged: 8:05:42 PM

Failed to get status: 'utf-8' codec can't decode byte 0xdf in position 0: invalid continuation byte
Failed to get status: [Errno 104] Connection reset by peer
Failed to get status: Expecting value: line 1 column 1 (char 0)"
Anyone can help me?
Thanks!

Integration not found (0.117)

Hi!
Seems like the update of Home assistant to 0.117 broke the integration some how.
I've installed via HACS and it was working up until I updated HA today. The integrations page doesn't seem to find localtuya anymore. I have tried reinstalling via HACS and rebooting HA, but no difference.

Got this in the log:

Logger: homeassistant.setup
Source: setup.py:138
First occurred: 11:36:18 AM (1 occurrences)
Last logged: 11:36:18 AM
Setup failed for localtuya: Integration not found. 

Let me know if I can provide any more information to resolve the issue.
Best regards,
phkr

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.