Tuya LOCAL with energy monitoring and without tuya-convert

I believe that this problem has been fixed with the code currently in the master branch, can you apply it and try? I suggest you delete the integration and re-create it.
Let us know, thank you

Hi all, i have made some progress on the Kogan switches not reporting Energy DPS values when not connected to the internet.

Some details here:

I will need abit more time to make changes to localtuya.

In short:
A undocumented Command needs to be invoked, to ask the Switch to update its Energy Monitoring Values. This update request needs to be made periodically.
Then DP-QUERY ie Command 10 will work as normal. Returning all 3 energy monitoring values.

Iā€™m not sure whether the other switches which showed similiar issue requires the same fix. I only have the Kogan switch with 2 usb ports the rectangular one.

NOTE: This ties in with JSON Invalid error for command 10. This occurs if the energy values are undefined due to lack of update. This possibly occurs when internet is shut off as the code to monitor and submit to cloud is not working.
With the energy values being updating manually via command 18, command 10 no longer errors with invalid json.

I Had these from SmartLife, had to buy a hub in the end to get them to be seperate in HA.

Works fine now.

This is a fantastic integration, thanks :slight_smile:

Looking forward to Climate for my radiator and energy metering (so I can track kwh used).

:slight_smile:

Good afternoon, has anyone here tried the integration with SP20 smart plugs?
Iā€™ve been trying to get them to work for 2 days now and feeling dumbā€¦

at one point the integration seemed to at least recognize the plug but no control nor reporting of the power usage. Then the 99.9% of time unreachable.

So was wondering do they even work with this integration, as i see people mentioning SP 22 but no mentioning of SP20

my teckin sp10 stopped working yesterday. i was able to configure properly at first attempt using local tuya but after home assistant upgrade it no longer working. i am latest Home Assistant 2021.1.4

anyone else having same issue ? nothing has been changed from my end.

Just reporting an issue, I have about 20 tuya plugs of various brands. All but 2 have energy monitoring. With tuyalocal 3.10 and 3.20 after an HA restart some random number (between 3 and 8) of them are unavailable. I can reload the integration for each of the individual unavailable plugs and they start working again. They stay stable after that, and donā€™t ever become unavailable again. Itā€™s not a huge problem as I only restart every few weeks and reloading only takes a few seconds, I just have to remember to do it :smile:

If I reinstall 3.0.3 this behaviour stops.

Hi All - I am switching over to the localtuya integration. a couple of questions:
(1) should i block these switchā€™s external network access to these switches after changing from tuya to local tuya?
(2) I cannot add 1 of 7 of my switches with this localtuya integration. I have double checked my key which seems correctā€¦ any ideas how to resolve this?
EDIT I reset that particular plug ā€¦ and it now works

Thanks!

ā€˜Failed to authenticate with device. Verify that device id and local key are correct.ā€™

log:

Traceback (most recent call last):
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 510, in detect_available_dps
    data = await self.status()
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 472, in status
    status = await self.exchange(STATUS)
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 457, in exchange
    payload = self._decode_payload(msg.payload)
  File "/config/custom_components/localtuya/pytuya/__init__.py", line 557, in _decode_payload
    payload = payload.decode()
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 5-6: invalid continuation byte
2021-01-19 12:53:25 ERROR (SyncWorker_13) [sonyapilib.device] HTTPError: HTTPConnectionPool(host='192.168.86.34', port=52323): Max retries exceeded with url: /dmr.xml (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0xa9be2628>: Failed to establish a new connection: [Errno 111] Connection refused'))
2021-01-19 12:53:25 ERROR (SyncWorker_13) [sonyapilib.device] Failed to get DMR
2021-01-19 12:53:25 ERROR (SyncWorker_13) [sonyapilib.device] HTTPError: HTTPConnectionPool(host='192.168.86.34', port=50002): Max retries exceeded with url: /getRemoteCommandList (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0xa676d370>: Failed to establish a new connection: [Errno 111] Connection refused'))
2021-01-19 12:53:26 ERROR (Recorder) [homeassistant.components.recorder] Error executing query: (sqlite3.DatabaseError) database disk image is malformed
[SQL: INSERT INTO events (event_type, event_data, origin, time_fired, created, context_id, context_user_id, context_parent_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)]
[parameters: ('state_changed', '{}', 'LOCAL', '2021-01-19 17:53:25.290739', '2021-01-19 17:53:25.290739', '904893df7edb005d996f6f78604c3ccc', None, None)]
(Background on this error at: http://sqlalche.me/e/13/4xp6)
2021-01-19 12:53:26 ERROR (Recorder) [homeassistant.components.recorder] Error saving events: (sqlite3.DatabaseError) database disk image is malformed
[SQL: INSERT INTO events (event_type, event_data, origin, time_fired, created, context_id, context_user_id, context_parent_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)]
[parameters: ('state_changed', '{}', 'LOCAL', '2021-01-19 17:53:25.290739', '2021-01-19 17:53:25.290739', '904893df7edb005d996f6f78604c3ccc', None, None)]
(Background on this error at: http://sqlalche.me/e/13/4xp6)
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1276, in _execute_context
    self.dialect.do_execute(
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 593, in do_execute
    cursor.execute(statement, parameters)
sqlite3.DatabaseError: database disk image is malformed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/recorder/__init__.py", line 454, in _commit_event_session_or_retry
    self._commit_event_session()
  File "/usr/src/homeassistant/homeassistant/components/recorder/__init__.py", line 509, in _commit_event_session
    self.event_session.flush()
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 2536, in flush
    self._flush(objects)
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 2678, in _flush
    transaction.rollback(_capture_exception=True)
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/util/langhelpers.py", line 68, in __exit__
    compat.raise_(
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 182, in raise_
    raise exception
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 2638, in _flush
    flush_context.execute()
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/unitofwork.py", line 419, in execute
    n.execute_aggregate(self, set_)
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/unitofwork.py", line 521, in execute_aggregate
    self.execute(uow)
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/unitofwork.py", line 586, in execute
    persistence.save_obj(
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py", line 239, in save_obj
    _emit_insert_statements(
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py", line 1135, in _emit_insert_statements
    result = cached_connections[connection].execute(
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1011, in execute
    return meth(self, multiparams, params)
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/sql/elements.py", line 298, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1124, in _execute_clauseelement
    ret = self._execute_context(
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1316, in _execute_context
    self._handle_dbapi_exception(
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1510, in _handle_dbapi_exception
    util.raise_(
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 182, in raise_
    raise exception
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1276, in _execute_context
    self.dialect.do_execute(
  File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 593, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.DatabaseError: (sqlite3.DatabaseError) database disk image is malformed
[SQL: INSERT INTO events (event_type, event_data, origin, time_fired, created, context_id, context_user_id, context_parent_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)]
[parameters: ('state_changed', '{}', 'LOCAL', '2021-01-19 17:53:25.290739', '2021-01-19 17:53:25.290739', '904893df7edb005d996f6f78604c3ccc', None, None)]
(Background on this error at: http://sqlalche.me/e/13/4xp6)

1 Like

i feel like my switches are not supported. No matter how i try to add them they are unreachable:

2021-01-23 17:36:58 DEBUG (MainThread) [custom_components.localtuya.discovery] Listening to broadcasts on UDP port 6666 and 6667
2021-01-23 17:37:42 DEBUG (MainThread) [custom_components.localtuya.discovery] Listening to broadcasts on UDP port 6666 and 6667
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Started heartbeat loop
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Sending command heartbeat (device type: type_0a)
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Send payload: b'{}'
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Waiting for sequence number -100
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Sending command status (device type: type_0a)
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Send payload: b'{"gwId":"0350507184f3eb411f1d","devId":"0350507184f3eb411f1d"}'
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Waiting for sequence number 1
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Dispatching message TuyaMessage(seqno=0, cmd=9, retcode=0, payload=b'', crc=2958142211)
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Got heartbeat response
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Decrypted payload: {}
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Dispatching message TuyaMessage(seqno=1, cmd=10, retcode=1, payload=b'data format error', crc=1908367780)
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Dispatching sequence number 1
2021-01-23 17:39:37 ERROR (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Failed to get status: The length of the provided data is not a multiple of the block length.
Traceback (most recent call last):
File "/home/homeassistant/homeassistant/custom_components/localtuya/pytuya/__init__.py", line 510, in detect_available_dps
data = await self.status()
File "/home/homeassistant/homeassistant/custom_components/localtuya/pytuya/__init__.py", line 472, in status
status = await self.exchange(STATUS)
File "/home/homeassistant/homeassistant/custom_components/localtuya/pytuya/__init__.py", line 457, in exchange
payload = self._decode_payload(msg.payload)
File "/home/homeassistant/homeassistant/custom_components/localtuya/pytuya/__init__.py", line 544, in _decode_payload
payload = self.cipher.decrypt(payload, False)
File "/home/homeassistant/homeassistant/custom_components/localtuya/pytuya/__init__.py", line 196, in decrypt
return self._unpad(decryptor.update(enc) + decryptor.finalize()).decode()
File "/usr/local/share/homeassistant/lib/python3.8/site-packages/cryptography/hazmat/primitives/ciphers/base.py", line 164, in finalize
data = self._ctx.finalize()
File "/usr/local/share/homeassistant/lib/python3.8/site-packages/cryptography/hazmat/backends/openssl/ciphers.py", line 181, in finalize
raise ValueError(
ValueError: The length of the provided data is not a multiple of the block length.
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Closing connection
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Stopped heartbeat loop
2021-01-23 17:39:37 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Connection lost: None
2021-01-23 17:39:44 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Started heartbeat loop
2021-01-23 17:39:44 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Sending command heartbeat (device type: type_0a)
2021-01-23 17:39:44 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Send payload: b'{}'
2021-01-23 17:39:44 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Waiting for sequence number -100
2021-01-23 17:39:44 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Sending command status (device type: type_0a)
2021-01-23 17:39:44 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Send payload: b'{"gwId":"0350507184f3eb411f1d","devId":"0350507184f3eb411f1d"}'
2021-01-23 17:39:44 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Waiting for sequence number 1
2021-01-23 17:39:44 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Dispatching message TuyaMessage(seqno=0, cmd=9, retcode=0, payload=b'', crc=2958142211)
2021-01-23 17:39:44 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Got heartbeat response
2021-01-23 17:39:44 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Decrypted payload: {}
2021-01-23 17:39:45 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Dispatching message TuyaMessage(seqno=1, cmd=10, retcode=0, payload=b'{"devId":"0350507184f3eb411f1d","dps":{"1":true,"2":0,"4":269,"5":195,"6":1222}}', crc=3883895955)
2021-01-23 17:39:45 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Dispatching sequence number 1
2021-01-23 17:39:45 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Decrypted payload: {"devId":"0350507184f3eb411f1d","dps":{"1":true,"2":0,"4":269,"5":195,"6":1222}}
2021-01-23 17:39:45 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Closing connection
2021-01-23 17:39:45 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Stopped heartbeat loop
2021-01-23 17:39:45 DEBUG (MainThread) [custom_components.localtuya.pytuya] [035...f1d] Connection lost: None
2021-01-23 17:41:46 DEBUG (MainThread) [custom_components.localtuya.discovery] Listening to broadcasts on UDP port 6666 and 6667
2021-01-23 17:41:46 DEBUG (MainThread) [custom_components.localtuya.binary_sensor] [035...f1d] Adding binary_sensor.ltvstandon with configuration: {'state_on': 'True', 'state_off': 'False', 'friendly_name': 'LTVStandOn', 'id': 1, 'device_class': 'power', 'platform': 'binary_sensor'}
2021-01-23 17:41:46 DEBUG (MainThread) [custom_components.localtuya.sensor] [035...f1d] Adding sensor.ltvstandsensor with configuration: {'friendly_name': 'LTVstandsensor', 'unit_of_measurement': 'V', 'id': 4, 'device_class': 'current', 'scaling': 0.1, 'platform': 'sensor'}

If you plug something in to consume power then try those values are easier to match

Unfortunately I canā€™t find a way to search this thread as my answer may already be in here.
Iā€™ve recently moved my home network onto new gear and now have an IoT vlan.
The two tuya power monitoring sockets I have are now on this vlan which is separate to my main lan where the HA server sits.

I havenā€™t purposely blocked any traffic across the vlans yet, so I can get everything migrated, checked as working and then potentially begin breaking things :rofl:

So, Iā€™ve updated the config.yaml with the new keys/secrets now the devices are on the vlan, but they are not showing as available. Should cross-vlan work out of the box, or do I need to do something specific in the config?

Was there any change in recent HA updates? I do not see my switches anymore (entity not available)ā€¦

I can confirm the FORCED supervisor update removed these too for me

I added them back by adding latest integration of https://github.com/rospogrigio/localtuya via HACS

1 Like

Hi,
How often is energy monitor supposed to refresh in HA ?
I have a Teckin plug, and values are refreshed somewhat every 30sec, when I read it should be at every change ?
Did I miss something ?
(yes, I killed the Smart Life app and even tried with my phone in airplane mode).
Thanks for your work btw, great integration !

I have various Tuya-compatible smart plugs, 2 of which report power values (Girier plugs, not ESP based). Iā€™ve managed to integrate them through Tuya-local in HA along with power readings. My only problem is that after some hours they stop reporting power readings altogether. This means to both HA and the Tuya app. I have to unplug and replug them manually, in order for them to start reporting power readings again.

The switching part works as it should. The number of hours until they stop reporting is completely random, so I cannot troubleshoot. I have not blocked internet to them, nor disconnected them from Tuya app (since Iā€™ve read that they would stay in a zombie state, not reporting anything, and I have no way of also blocking their DNS requests to my local router). When I blocked internet to one of them, it immediately stopped reporting power values.
Local tuya logs show no error, apart from the same devices being discovered over and over again (I donā€™t know if this is the expected behavior after they are discovered in the first place):

2021-02-15 22:09:01 DEBUG (MainThread) [custom_components.localtuya.discovery] Discovered device: {'ip': '192.168.1.67', 'gwId': 'bf4fbfdd0c0d77bb16rewi', 'active': 2, 'ablilty': 0, 'encrypt': True, 'productKey': 'keyt4addwh57c5wf', 'version': '3.3'}
2021-02-15 22:09:01 DEBUG (MainThread) [custom_components.localtuya] Device bf4fbfdd0c0d77bb16rewi found with IP 192.168.1.67
2021-02-15 22:09:02 DEBUG (MainThread) [custom_components.localtuya.pytuya] [bf4...ewi] Sending command heartbeat (device type: type_0a)
2021-02-15 22:09:02 DEBUG (MainThread) [custom_components.localtuya.pytuya] [bf4...ewi] Send payload: b'{}'
2021-02-15 22:09:02 DEBUG (MainThread) [custom_components.localtuya.pytuya] [bf4...ewi] Waiting for sequence number -100
2021-02-15 22:09:02 DEBUG (MainThread) [custom_components.localtuya.pytuya] [bf4...ewi] Dispatching message TuyaMessage(seqno=0, cmd=9, retcode=0, payload=b'', crc=2958142211)
2021-02-15 22:09:02 DEBUG (MainThread) [custom_components.localtuya.pytuya] [bf4...ewi] Got heartbeat response
2021-02-15 22:09:02 DEBUG (MainThread) [custom_components.localtuya.pytuya] [bf4...ewi] Decrypted payload: {}
2021-02-15 22:09:02 DEBUG (MainThread) [custom_components.localtuya.discovery] Discovered device: {'ip': '192.168.1.69', 'gwId': 'bf8234672ac806862ahzvs', 'active': 2, 'ablilty': 0, 'encrypt': True, 'productKey': 'teuu8swy9614jrxm', 'version': '3.3'}
2021-02-15 22:09:02 DEBUG (MainThread) [custom_components.localtuya] Device bf8234672ac806862ahzvs found with IP 192.168.1.69
2021-02-15 22:09:02 DEBUG (MainThread) [custom_components.localtuya.discovery] Discovered device: {'ip': '192.168.1.68', 'gwId': 'bf0de23c1216a32827ri7e', 'active': 2, 'ablilty': 0, 'encrypt': True, 'productKey': 'teuu8swy9614jrxm', 'version': '3.3'}
2021-02-15 22:09:02 DEBUG (MainThread) [custom_components.localtuya] Device bf0de23c1216a32827ri7e found with IP 192.168.1.68
2021-02-15 22:09:03 DEBUG (MainThread) [custom_components.localtuya.discovery] Discovered device: {'ip': '192.168.1.64', 'gwId': 'bf697f0ad7fe77d240lujc', 'active': 2, 'ablilty': 0, 'encrypt': True, 'productKey': 'keyt4addwh57c5wf', 'version': '3.3'}
2021-02-15 22:09:03 DEBUG (MainThread) [custom_components.localtuya] Device bf697f0ad7fe77d240lujc found with IP 192.168.1.64
2021-02-15 22:09:04 DEBUG (MainThread) [custom_components.localtuya.discovery] Discovered device: {'ip': '192.168.1.66', 'gwId': 'bf6f4443b3500f8180xazz', 'active': 2, 'ablilty': 0, 'encrypt': True, 'productKey': 'keyt4addwh57c5wf', 'version': '3.3'}
2021-02-15 22:09:04 DEBUG (MainThread) [custom_components.localtuya] Device bf6f4443b3500f8180xazz found with IP 192.168.1.66
2021-02-15 22:09:04 DEBUG (MainThread) [custom_components.localtuya.discovery] Discovered device: {'ip': '192.168.1.65', 'gwId': 'bf86b0cb0ee78d13652vne', 'active': 2, 'ablilty': 0, 'encrypt': True, 'productKey': 'keyt4addwh57c5wf', 'version': '3.3'}
2021-02-15 22:09:04 DEBUG (MainThread) [custom_components.localtuya] Device bf86b0cb0ee78d13652vne found with IP 192.168.1.65

Iā€™m starting to think that itā€™s the plugsā€™ fault and I should just replace them. Any ideas?

Hi all, if you are able to understand german, you will find here a HowTo video about this topic. It covered the finding of Local Key and Device ID as well! https://youtu.be/dBtrsXZOk8M

So glad I stumbled upon this integration, everything is so much faster! Canā€™t wait until Climate devices are available, only one left to move off the cloud :slight_smile:

I bought some somewhat expensive bright WiFi LED floodlights with separate white and coloured leds. I only wanted dimmable warm white really but there you go. I only know of one other manufacture doing dimmable and they use standard dimmer switch. These esp based work with local Tuya , at least on off does, will be looking at brightness next.

Just noticed I have this same issue. I can reload them back after a restart but because I have light entities based off a switch entity, the light entity remains unavailable regardless of reloading.

I am on v3.2.2, might downgrade to 3.0.3 and see how I go