Operating environment (Hass.io/Docker/Windows/etc.):
Hassio.io on a Pi4 4GB manually configured TPLink as a strip pointing to the device (HS300)
Integration:
https://www.home-assistant.io/integrations/tplink/
Description of problem:
TPLink does not auto discovery so I setup manually as a script. On startup / discovery sometimes the plug is reported as 5 sometimes as 6. it is a HS300 power strip.
Problem-relevant configuration.yaml
entries and (fill out even if it seems unimportant):
Traceback (if applicable):
Additional information:
Hey there @rytilahti, mind taking a look at this issue as its been labeled with a integration (tplink
) you are listed as a codeowner for? Thanks!
Just curious if only comes back with 5 or does it get discovered with an "unnamed_device"? Mine seems to always discover all 6 but it doesn't always discover the names correctly and sometimes comes back with switch.unnamed_device and maybe a switch_unnamed_device2. I was wondering if this also related to the tplink discovery not always discovering all devices if you have a large number of devices. I have 23 tplink devices and it is almost impossible to get all of them discovered without many restarts of HA.
I am currently running the PIP install on a PI 3B+ running 0.101.3 and the discovery issue has existed on every version HA for me.
mine also does the weird naming thing but it is inconsistent on the plugs. I don't believe it is a timing issue as I only have one tplink device.
Can you enable logging for both the integration as well as for pyHS100
? Is it working fine with the console tool pyhs100
?
I added the following to my configuration.yaml:
logger:
logs:
homeassistant.components.tplink: debug
pyHS100: debug
After a few minutes I did the following:
egrep "tplink|HS100" home-assistant.log >/tmp/tp.log
On this start at least all of my devices appeared to be discovered (22, I miscounted before when I wrote 23). But for the power strip, 2 of the ports came back as unnamed_devices (they are Monitor 2 and 3 in the log). I will try the pyhs100 console, but I do remember playing with it before the code was merged and I didn't notice any issue, but I didn't do too much with it.
@TheGardenMonkey If my gut feeling is right, I think your problem will be fixed when I manage to do a new pyhs100 release. I have experienced with some bulbs that they stop responding after receiving too many requests in a short period of time. In the case of HS300, homeassistant (to my understanding) requests an update for each socket separately, meaning that there will be at minimum 6 requests made to a single device (but considering emeter etc., it'll be in practice much more). The new release will fix this issue by transparently caching the results for a short amount of time.
Thank you and that makes sense. I do remember seeing something similar before regarding too many connection attempts.
Based on your comments @rytilahti , I decided to try increasing the "interval" value from 60 to 120 in the common.py in the tplink directory and so far all of my 22 devices come back now and the HS300 is showing all the ports / devices.
Changing interval to 120 on line 136 in /srv/homeassistant/lib/python3.7/site-packages/homeassistant/components/tplink/common.py:
async def async_add_entities_retry(
hass: HomeAssistantType,
async_add_entities: Callable[[List[Any], bool], None],
objects: List[Any],
callback: Callable[[Any, Callable], None],
interval: timedelta = timedelta(seconds=120),
):
That at least allows all of the devices to show up, but I still see an error updating the state for the HS300 so it doesn't always show the correct state of each port (192.168.86.166 is my HS300):
2019-11-16 18:08:38 WARNING (SyncWorker_8) [homeassistant.components.tplink.switch] Could not read state for 192.168.86.166: Communication error
One additional change I just tried which at least fixes the state becoming unavailable was to wrap the "update" in a for loop with a sleep to retry after 1 second up to 10 times (i also tried 2 seconds up to 5 times). So not at least the state doesn't flop, it now only delayed in updating (which I think is already the case anyway):
MAX_ATTEMPS = 5
SLEEP_TIME = 2
def update(self):
"""Update the TP-Link switch's state."""
for update_attempt in range(MAX_ATTEMPS):
try:
if not self._sysinfo:
self._sysinfo = self.smartplug.sys_info
self._mac = self.smartplug.mac
self._model = self.smartplug.model
if self.smartplug.context is None:
self._alias = self.smartplug.alias
self._device_id = self._mac
else:
self._alias = [
child
for child in self.smartplug.sys_info["children"]
if child["id"] == self.smartplug.context
][0]["alias"]
self._device_id = self.smartplug.context
if self.smartplug.context is None:
self._state = self.smartplug.state == self.smartplug.SWITCH_STATE_ON
else:
self._state = [
child
for child in self.smartplug.sys_info["children"]
if child["id"] == self.smartplug.context
][0]["state"] == 1
if self.smartplug.has_emeter:
emeter_readings = self.smartplug.get_emeter_realtime()
self._emeter_params[ATTR_CURRENT_POWER_W] = "{:.2f}".format(
emeter_readings["power"]
)
self._emeter_params[ATTR_TOTAL_ENERGY_KWH] = "{:.3f}".format(
emeter_readings["total"]
)
self._emeter_params[ATTR_VOLTAGE] = "{:.1f}".format(
emeter_readings["voltage"]
)
self._emeter_params[ATTR_CURRENT_A] = "{:.2f}".format(
emeter_readings["current"]
)
emeter_statics = self.smartplug.get_emeter_daily()
try:
self._emeter_params[ATTR_TODAY_ENERGY_KWH] = "{:.3f}".format(
emeter_statics[int(time.strftime("%e"))]
)
except KeyError:
# Device returned no daily history
pass
self._available = True
except (SmartDeviceException, OSError) as ex:
_LOGGER.warning(
f"Retrying in {SLEEP_TIME} seconds for {self.smartplug.host}|{self._alias} due to: {ex}"
)
time.sleep(SLEEP_TIME)
else:
break
else:
if self._available:
_LOGGER.warning(
f"Could not read state for {self.smartplug.host}|{self._alias}"
)
self._available = False
@TheGardenMonkey - Trying to test your modifications for the TP-Link switch to see if it stops the random "unavailable" status on them. The TP-Link lights do the same thing randomly.
Probably something minor I missed on the cut and paste, but got this error after trying your changes:
2019-12-12 13:44:24 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry TP-Link Smart Home for switch
Traceback (most recent call last):
File "d:homeassistantlibsite-packageshomeassistantconfig_entries.py", line 192, in async_setup
hass, self
File "d:homeassistantlibsite-packageshomeassistantcomponentsswitch__init__.py", line 79, in async_setup_entry
return await hass.data[DOMAIN].async_setup_entry(entry)
File "d:homeassistantlibsite-packageshomeassistanthelpersentity_component.py", line 142, in async_setup_entry
platform_type,
File "d:homeassistantlibsite-packageshomeassistantsetup.py", line 245, in async_prepare_setup_platform
platform = integration.get_platform(domain)
File "d:homeassistantlibsite-packageshomeassistantloader.py", line 232, in get_platform
f"{self.pkg_path}.{platform_name}"
File "D:PythonPython37libimportlib__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "
File "
File "
File "
File "
File "
File "
File "
File "d:homeassistantlibsite-packageshomeassistantcomponentstplinkswitch.py", line 127
def update(self):
^
IndentationError: unexpected indent
Attaching the full file instead...i should have done that in the first place
Awesome, thanks!!! Just updated mine over here and it loaded fine this time. Will report back tomorrow after I give it time to run for awhile. I have a good number of TP-Link switches, and a bulb, so should be a good test.
I updated the log outputs just in case so you can see each retry attempt for each device...
2019-12-12 19:06:41 WARNING (SyncWorker_4) [homeassistant.components.tplink.switch] Retrying in 2 for 192.168.86.166|Office Monitor 2 due to: Communication error
As long as all the devices show up after you restart HA, mine seem to stay. There are sometimes where I need to restart HA an extra time for it to poll all of the devices (which has always been an issue for me), but it seems to just be once as opposed to the 4 or 5 times I would try before.
@TheGardenMonkey - Working great so far (been around 12 hours). Not a single "unavailable" or "status unknown" flap of any TP-Link switch. I never had issues with the tplink switches at startup, but they would randomly for "unknown" in the log, but always recovered instantly. It was cluttering up the log and chart - as it seems the tplink devices can't handle lots of polling and will occasionally drop a reply. Your routine seems to have fixed that! Will update later, but if all continues well we should have this entered as a pull request! I know there is work being done on the back-end library, but this looks to fix it, too. Can't hurt to have both in there.
Would it be possible for you to modify and post the same routine for the tplink "light"? I have the same issues with that one occasionally.
Below you can see the history of all the random "unknowns" and the clean past 12 hours after using your update. :)
I'm happy to report that your updates have completely fixed my random "unavailable" or "unknowns" that I was getting in the log and on the history. The routine appears to be solid and should be added as a pull request. I would like to see it in the light component as well, since TP-link is notorious for this issue and I have seen it on my lights, too.
I am seeing the communication errors in the log (which we could probably just ignore or delete) since this is just the way the tplink devices work. They are not always quick to respond to lots of requests.
Update of switch.christmas_alex_room is taking over 10 seconds
8:08 PM D:PythonPython37libasyncioevents.py (WARNING) - message first occurred at 7:58 PM and shows up 2 times
Update of switch.alex_humidifier is taking over 10 seconds
8:08 PM D:PythonPython37libasyncioevents.py (WARNING) - message first occurred at 12:55 PM and shows up 5 times
Could not read state for 192.168.0.187|Alex Humidifier
2:42 PM d:homeassistantlibsite-packageshomeassistantcomponentstplinkswitch.py (WARNING)
Updating tplink switch took longer than the scheduled update interval 0:00:30
2:42 PM d:homeassistantlibsite-packageshomeassistanthelpersentity_platform.py (WARNING)
But, the log and history looks clean. Just one unavailable at 2:42pm where there was apparently too many drops in a row. Would increasing the MAX_ATTEMPTS from 5 to 10 help?
Awesome and yes I was thinking of increasing it to 10 attempts (I originally tried 1 second and 10 attempts but that still resulted in drops, but 2 seconds and 10 attempts seems reasonable to me). I will take a look at the light component in the morning.
Attached is an updated for the light component that matches the switch one. I don't have a bulb to validate but no startup errors at least. For the hs300 I still do see one of the switches not respond sometimes so not sure if 10 attempts in enough...might need to be at least 12 (2 seconds x 6 switches). Going to test increasing it to 20 to be safe (just wasn't sure if I missing something).
Awesome, just updated my light.py over here and restarted. All working perfect. So happy to finally get to the bottom of the status unknown or unavailable in the history and log. Your update handles the random response behavior of the tplinks and keeps it working clean. I guess it isn't a big deal to see all the communication errors in the log since that doesn't impact anything. Having clean history and status are the main things. I have a ton of these switches and just ordered another 8.. :) Most are HS105, but have HS200s (wall switches), a few of their light bulbs, and a KP400 (outdoor 2-outlet strip - using for xmas lights this year). All working great now!!!
Trying to test out the tplink switch .py but can not figure out where it is stored on hassio. Any luck pointing me to where its at?
Trying to test out the tplink switch .py but can not figure out where it is stored on hassio. Any luck pointing me to where its at?
On my Windows install, I have it in: D:homeassistantLibsite-packageshomeassistantcomponentstplink
Should be a similar directory structure on hassio.
On my Windows install, I have it in: D:homeassistantLibsite-packageshomeassistantcomponentstplink
Should be a similar directory structure on hassio.
Doesn't seem to exist cant find it using smb or configurator
ok so I was able to get it running by adding it as a custom component. It appears to be working with my HS300 as the strip. It does however under integrations still pick a random name. Shouldn't it be picking the switch.tp_link_power_strip_797d as the name?
You might have to delete the device by going to the entity registry page...I am pretty sure I had to do that and then on restart it discovered the names correctly. Under integrations it shows up under one device and it is the name of my 6th port as defined in the kasa app.
So I removed the entity today thinking everything was good to go. But now I am still getting the random devices not showing in the list. Its never the same one its always different. Been through 4 restarts of ha and can't get a perfect match yet.
Can you try changing the MAX_ATTEMPTS to 20? I forgot the version I uploaded was only at 5 and that is not enough for the HS300.
Can you try changing the MAX_ATTEMPTS to 20? I forgot the version I uploaded was only at 5 and that is not enough for the HS300.
Set it to 10 - had a missing device. Set it to 20 - seemed to pop up and survive two restarts. Third one popped up with a device missing.
(device still takes whatever name it wants)
What version of HA are you on? I am on latest 0.103.0.
@rlsmntr Can you try this version instead?
I updated it based on some feedback on the pull request and after going through a bunch more test, I no longer see the issue where the devices do not show up with the proper name (even with my last version I saw it a few times, but I believe the last change prevents that). The only issue I still see is a 1 second delay on updating the status which I am still working on.
@rlsmntr Can you try this version instead?
I updated it based on some feedback on the pull request and after going through a bunch more test, I no longer see the issue where the devices do not show up with the proper name (even with my last version I saw it a few times, but I believe the last change prevents that). The only issue I still see is a 1 second delay on updating the status which I am still working on.
I wanted to test this for a while and got wrapped up in the holidays. This seems to have resolved the issue with HA not finding all the plugs on reboot. My HA has seen every plug on reboot for that strip since I updated to this. The device does show as randomly any of the plugs. That doesn't really bother me as long as the plugs work - which they do.
@rlsmntr Can you try this version instead?
I was having the same problem, things are much better with this patch. All six plugs seem to show up every time. Sometimes their status is incorrect (switch incorrectly displayed as "off" when it's actually "on," and all the power usage information being unavailable), but that clears up after a second or two. Previously, the entities would appear as "unavailable" and the only thing one could do was restart HomeAssistant and hope to get lucky (seemed to take about 10-20 restarts to have all six).
I haven't looked at the code, but based on the error messages in the logs, it seems the underlying error is still there. Previously, I would get errors like these (HS300 is the strip's DNS hostname):
2020-01-19 20:42:20 WARNING (SyncWorker_24) [homeassistant.components.tplink.switch] Could not read state for HS300: Communication error
Now the error is similar but different:
2020-01-20 11:37:08 WARNING (SyncWorker_3) [homeassistant.components.tplink.switch] Retrying in 1 for HS300| due to: Communication error
(Note there seems to be a stray |
character in this version)
Retrying on this error is certainly better than just making the entity permanently unavailable. However, it leaves the question of why it's happening in the first place? A couple of data points:
I'm also using a couple of HS105 and HS110 "smart plugs" from the same manufacturer with HomeAssistant, for a couple of months, and those never have this kind of error or any other problem that I've noticed. They're all on the same network.
I also have this command line script to query the device directly. When I use the info
command on the HS300, it always returns a successful and complete response with the correct state of all six plugs. So it would seem the issue must be a bug somewhere in the HomeAssistant integration for this specific device?
@morninglite the root of the problem is known and has been discussed previously, but to summarize: my understanding is that the devices stop responding to commands if it thinks it is being flooded by too many requests at once. This is also the reason why that retry PR has not been merged, it does not really solve the underlying problem whatsoever (but I agree that homeassistant should allow/do retries in case of communication failures, but that's a topic for another day..).
At the moment HS105 (w/o emeter) will receive a single request where HS110 will get three requests per update cycle. For HS300 this number jumps to 21 requests (one for current state, current consumption, daily consumption) per device, as each of the socket is also queried separately (so 3*6=18). I have personally experienced some bulbs having issues with far fewer number of requests. Assuming it's only a single device that is being unnamed, maybe the device allows only up to 20 request in X seconds? That would not explain the problem with some other devices having fewer sockets though.
Anyway, the problem is being slowly solved in the new backend library (by avoiding unnecessary I/O), but as none of the developers have a test device (and are otherwise busy), it will take some time to get this properly fixed. One potential temporary solution could be to distribute the updates for the child devices more uniformly over the update period.
Someone with access to HS300 could do some experiments using the library directly to see what are the limits when the problems appear, that could also be helpful so we could add throttling to the backend lib.
@rytilahti sorry, I wasn't around for the previous discussions but thank you for that excellent explanation! I'll do as you suggested and experiment using the library (you mean pyHS100, right?) directly.
One thing I notice is that when using the aforementioned command-line tool, I get the statuses of all the plugs with just one request: the get_sysinfo
response contains a children
json array with six elements, each one containing a plug's ID and state (on/off state, plus on_time). Unfortunately, this doesn't include the power usage info, but even if that has to be queried separately it seems we could at least reduce the total number of requests from 21 to 15, unless I'm missing something.
I imagine there must be constraints in the current code that make that difficult, but is it at least a reasonable goal to work towards?
@morninglite that is indeed the approach I have in my mind, alas, I have not had time to dug into that part yet. We have been lately cleaning up the pyhs100 library under its new name here: https://github.com/python-kasa/python-kasa . The preliminary PR to convert homeassistant to use it is already linked above, but it is not yet ready for the prime time until the multisocket accesses are optimized.
Considering the json payload calls it child_ids
containing an array, maybe it can be a list of all the sockets? This way the number of requests would be three instead of the current 21. Unfortunately, I have no test device as there is no EU variant for this, so doing development work requires going through some hoops.
I'd be happy to help with testing.
I have 3 of the HS300's (I'm in the USA) and am having issues getting them connected to Hass. 3 x 6 sockets means I have 18 sockets to come online after a Hass/Hass.io reboot, and I've never seen it successfully bring all 18 online.
I'm running .107.5 with Hass.io Supervisor 209 on Ubuntu 18.04.4. I am having no issues with either my Alexa integration nor my Sense integration.
Brilliant! Added this as a custom component and things have been much more reliable. Not quite perfect, but darn close.
I'm on dev channel of Hassio and have 3x HS300s also.
Agreed! I really wish the modified light.py and switch.py would be added to the release builds. Each time I upgrade, I keep re-copying the modified light.py and switch.py to keep things working properly with no random unavailables.
@TheGardenMonkey - Created a pull request with your MAX_RETRIES and SLEEP_TIME using the latest dev build. I have been using your code ever since you posted it and it works perfect. Did this so I don't have to keep re-copying over the component to get rid of the "unknown" status errors on the TPLink devices. https://github.com/home-assistant/core/pull/35460
I have an open one but it hasn't been approved. There are some changes coming to the kasa library to attempt to prevent the main issue.
As a side note, I just use my code as a custom component so that way I don't have to keep copying it everytime I do an upgrade. So i just have the files in ~/.homeassistant/custom_components/tplink (I am using the pip install method,)
When I pulled the latest switch.py and light.py from dev, there have been several changes since I added your mod almost 6 months ago. I applied your changes to the very latest versions and used that for the pull request. Also running that updated version over here now - working flawlessly as always. I know there is work being done to the kasa library, but see no harm in putting this fix in for the time being. It works great!
I think I merged those changes in a few weeks ago as well...they are part of my pull request.
I found this thread because I just got 7 HS300's and 3 HS110's and I'm getting some instability in the discovered entities. Every restart of the server seems to make some active and others become orphaned.
I'm guessing the fix hasn't been released yet and I should expect this for a bit more until it is.
In order to fix this in the meantime, you can run @TheGardenMonkey 's updated switch.py and light.py as a custom component. We both had submitted pull requests that technically work, but were not approved. Probably because it is a work-around, but I have been running the modified code for the past 6 months with no issues. Eventually the new backend will be added, but you can fix it today by doing the above.
So I moved my Home Assistant installation from a fast PC to the classic Raspberry Pi Model B. Anyway, in the process I forgot to put the modified switch.py
on the Pi, and didn't even notice for a couple of weeks!
The error still occurs, but very rarely compared to the fast machine. On the pi, the web interface almost always looks correct, and the "Could not read state" error only appears a handful of times a day. On the fast machine it was the opposite: web interface was almost always missing at least one plug, if not several, and the logs were flooded with this message.
I guess it's ok to send as many requests as you want, as long as you do it slowly? :P
Yes, the devices I have tested/gotten tested by others allow something between 4-20 requests per second. IIRC, current implementation for HS300 will cause the total of 18 requests per update cycle, which likely hits the limit when going fast enough, for HS110 I have gotten stable 20 requests per second without problems, the bulbs seem also be much stricter than that.
So what happens there during the start process with the current implementation is the following:
Those tests were run with python-kasa using code like this:
import asyncio
import logging
logging.basicConfig(level=logging.DEBUG)
from kasa import SmartPlug
async def loopy():
b = SmartPlug("192.168.250.188")
while True:
await b.update()
print(b.emeter_realtime)
await asyncio.sleep(0.1)
asyncio.run(loopy())
while adjusting the sleep interval.
The reason for all of these issues is a large amount of consecutive requests, that's why python-kasa (and the linked PR) takes a different approach.
edit: added a clarification what happens during the initialization to make it clearer why the current implementation is problematic.
Hello, could someone provide some assistance on how to use @TheGardenMonkey switch.py ? I am running Hass.io on a RP4, I see that @rlsmntr was able to add it as a custom component however I am a little lost, from what I understand I need to go to add-on store then add repositories however not sure which repository to add?
Although I have been using my code since December now, I am still a little hesitant to recommend it. For one thing I haven't updated it to use the new SwitchDevice, but regardless, in case it does help, I am attaching a simple zip of what you need. This just needs to be unzipped into your custom_components folder.
:~/.homeassistant/custom_components/tplink $ ll
total 52
-rw-r--r-- 1 homeassistant homeassistant 5735 Jan 11 09:19 common.py
-rw-r--r-- 1 homeassistant homeassistant 364 Jan 11 09:19 config_flow.py
-rw-r--r-- 1 homeassistant homeassistant 44 Jan 11 09:19 const.py
-rw-r--r-- 1 homeassistant homeassistant 3764 Jan 11 09:19 __init__.py
-rw-r--r-- 1 homeassistant homeassistant 8651 Jan 11 09:19 light.py
-rw-r--r-- 1 homeassistant homeassistant 248 Jan 11 09:19 manifest.json
drwxr-xr-x 2 homeassistant homeassistant 4096 Jan 11 09:23 __pycache__
-rw-r--r-- 1 homeassistant homeassistant 381 Jan 11 09:19 strings.json
-rw-r--r-- 1 homeassistant homeassistant 6422 Jan 11 09:19 switch.py
I have been watching the WIP pull request and hoping that gets released soon. The last time I tested it though it wasn't working but I haven't tried the last version.
Thank you so much @TheGardenMonkey ! This has helped and my HS300 is working much better, all of the outlets show up now and the on/off functionality is working consistent enough to be used for my intended purposes. Thanks again.
While I understand there is a new setup being worked on, it is a shame the
several pull requests were not merged with these fixes. I have been
running the modified tplink integration over here flawlessly ever
since @TheGardenMonkey made the updates - somewhere around 7 months ago.
On Sat, Jul 11, 2020 at 11:27 AM jaysalazar notifications@github.com
wrote:
Thank you so much @TheGardenMonkey https://github.com/TheGardenMonkey !
This has helped and my HS300 is working much better, all of the outlets
show up now and the on/off functionality is working consistent enough to be
used for my intended purposes. Thanks again.—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/home-assistant/core/issues/28590#issuecomment-657080890,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/ADEX7OKPXFAX2YZBHUTHQZTR3CAGBANCNFSM4JJWUR6Q
.
@TheGardenMonkey Thank you for sharing your tplink update! It definitely works better than the native integration! But I do see an issue that you may or may not be interested in addressing. When trying to control multiple switches on the HS300 simultaneously (in a group) or one after another fairly quickly, I am getting the below error.
Log Details (ERROR)
Logger: homeassistant.components.websocket_api.http.connection.139934390209504
Source: custom_components/tplink/switch.py:131
Integration: Home Assistant WebSocket API (documentation, issues)
First occurred: 8:43:46 PM (2 occurrences)
Last logged: 8:44:14 PMCommunication error
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 115, in _query_helper
response = self.protocol.query(
File "/usr/local/lib/python3.8/site-packages/pyHS100/protocol.py", line 47, in query
sock = socket.create_connection((host, port), timeout)
File "/usr/local/lib/python3.8/socket.py", line 808, in create_connection
raise err
File "/usr/local/lib/python3.8/socket.py", line 796, in create_connection
sock.connect(sa)
socket.timeout: timed outThe above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 125, in handle_call_service
await hass.services.async_call(
File "/usr/src/homeassistant/homeassistant/core.py", line 1308, in async_call
task.result()
File "/usr/src/homeassistant/homeassistant/core.py", line 1343, in _execute_service
await handler.func(service_call)
File "/usr/src/homeassistant/homeassistant/components/homeassistant/__init__.py", line 87, in async_handle_turn_service
await asyncio.gather(tasks)
File "/usr/src/homeassistant/homeassistant/core.py", line 1308, in async_call
task.result()
File "/usr/src/homeassistant/homeassistant/core.py", line 1343, in _execute_service
await handler.func(service_call)
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 208, in handle_service
await self.hass.helpers.service.entity_service_call(
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 454, in entity_service_call
future.result() # pop exception if have
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 583, in async_request_call
await coro
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 485, in _handle_entity_call
await result
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 618, in async_turn_off
await self.hass.async_add_executor_job(ft.partial(self.turn_off, *kwargs))
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/tplink/switch.py", line 121, in turn_off
self.update_state()
File "/config/custom_components/tplink/switch.py", line 139, in update_state
self._state = self._plug_from_context["state"] == 1
File "/config/custom_components/tplink/switch.py", line 131, in _plug_from_context
children = self.smartplug.sys_info["children"]
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 186, in sys_info
return defaultdict(lambda: None, self.get_sysinfo())
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 196, in get_sysinfo
return self._query_helper("system", "get_sysinfo")
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 120, in _query_helper
raise SmartDeviceException('Communication error') from ex
pyHS100.smartdevice.SmartDeviceException: Communication error
@TheGardenMonkey Thank you for sharing your tplink update! It definitely works better than the native integration! But I do see an issue that you may or may not be interested in addressing. When trying to control multiple switches on the HS300 simultaneously (in a group) or one after another fairly quickly, I am getting the below error.
Log Details (ERROR)
Logger: homeassistant.components.websocket_api.http.connection.139934390209504
Source: custom_components/tplink/switch.py:131
Integration: Home Assistant WebSocket API (documentation, issues)
First occurred: 8:43:46 PM (2 occurrences)
Last logged: 8:44:14 PM
Communication error
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 115, in _query_helper
response = self.protocol.query(
File "/usr/local/lib/python3.8/site-packages/pyHS100/protocol.py", line 47, in query
sock = socket.create_connection((host, port), timeout)
File "/usr/local/lib/python3.8/socket.py", line 808, in create_connection
raise err
File "/usr/local/lib/python3.8/socket.py", line 796, in create_connection
sock.connect(sa)
socket.timeout: timed out
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 125, in handle_call_service
await hass.services.async_call(
File "/usr/src/homeassistant/homeassistant/core.py", line 1308, in async_call
task.result()
File "/usr/src/homeassistant/homeassistant/core.py", line 1343, in _execute_service
await handler.func(service_call)
File "/usr/src/homeassistant/homeassistant/components/homeassistant/init.py", line 87, in async_handle_turn_service
await asyncio.gather(tasks)
File "/usr/src/homeassistant/homeassistant/core.py", line 1308, in async_call
task.result()
File "/usr/src/homeassistant/homeassistant/core.py", line 1343, in _execute_service
await handler.func(service_call)
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 208, in handle_service
await self.hass.helpers.service.entity_service_call(
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 454, in entity_service_call
future.result() # pop exception if have
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 583, in async_request_call
await coro
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 485, in _handle_entity_call
await result
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 618, in async_turn_off
await self.hass.async_add_executor_job(ft.partial(self.turn_off, *kwargs))
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/tplink/switch.py", line 121, in turn_off
self.update_state()
File "/config/custom_components/tplink/switch.py", line 139, in update_state
self._state = self._plug_from_context["state"] == 1
File "/config/custom_components/tplink/switch.py", line 131, in _plug_from_context
children = self.smartplug.sys_info["children"]
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 186, in sys_info
return defaultdict(lambda: None, self.get_sysinfo())
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 196, in get_sysinfo
return self._query_helper("system", "get_sysinfo")
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 120, in _query_helper
raise SmartDeviceException('Communication error') from ex
pyHS100.smartdevice.SmartDeviceException: Communication error
I will see if I can reproduce that. I currently have a group like this though and I turn the group on and off daily (weekdays anyway) and I haven't noticed that.
office_desk:
name: Office Desk
all: true
entities:
- switch.office_monitor_1
- switch.office_monitor_2
- switch.office_monitor_3
- switch.office_laptop_dock
- switch.office_desk_light
I currently have a group like this though and I turn the group on and off daily
Hmmm... To be honest, I didn't have them in a "real" group. I have a Lovelace screen that I let HA manage so that I have all of my devices dumped into one place for testing. These fell into a Switch group by default. When I try turning that group on an off, I receive the error. I also receive it when I quickly turn the switches on and off individually.
Interestingly though, after reading your post I created an actual group for them. It does seem to work a little more consistently, but still not 100%. Not sure why there would be a difference between a group created by Lovelace and one created in YAML? I did notice that even though the switches all work at the group level, they are very slow to turn on and off when you toggle the group. And even in the new group, they still fail when I try to toggle individual switches quickly.
Not sure if any of this was helpful, but just wanted to give you as many details as possible! Thanks!
I take that back. After more testing, I am seeing that they really aren't any better in the new group. Please let me know if there is any other info I can give you to help debug!
I take that back. After more testing, I am seeing that they really aren't any better in the new group. Please let me know if there is any other info I can give you to help debug!
I'll play around with it this weekend. It makes sense to me that this could happen though. I want to compare with some of the other changes proposed as well...I think there is a collection of changes that will make this integration more robust.
Sounds great! Thanks!
Seeing similar issues reported here with my HS300. HA sees only 5 of six outlets, and outlets frequently go into an Unavailable state. It sounds like this could be an issue hitting the API limit. Perhaps this could be a user-configurable option to set this to be less frequent?
@MarkHofmann11 (and anyone else) if you have a chance, would you mind testing out my latest pull request, specifically I want to confirm that the latest one still works correctly for the "lights". I have a ton of switches but no light bulbs currently. I basically re-implemented my original retry attempt but on top of the latest set of changes from the past few months. The light component has changed a fair amount so I wanted to confirm that my the "retry" is in fact still needed there and of course that my latest attempt does work.
@TheGardenMonkey - Would you happen to have the updated files available that I can download and copy into my current install? I used your original updates from back in December and had re-updated the latest tplink switch.py and light.py about 2 or so months ago. Looks like more has changed since then. If you can archive the files somewhere, I can download and copy them over my current modified version for testing. I have loads of tplink switches, outlets, wall switches, lights, strips, etc. All work perfect with what I am using at the moment.
These are what I have as of now
These are what I have as of now
Finally got a chance to test this today. For some reason, getting "Unable to prepare setup for platform tplink.switch: Platform not found (cannot input name 'async_add_entities_retry' from 'homeassistant.components.tplink.common'. None of my tplink switches are showing online - so will revert back to my modified version and see if I can figure out what is going on.
tplink.zip
These are what I have as of nowFinally got a chance to test this today. For some reason, getting "Unable to prepare setup for platform tplink.switch: Platform not found (cannot input name 'async_add_entities_retry' from 'homeassistant.components.tplink.common'. None of my tplink switches are showing online - so will revert back to my modified version and see if I can figure out what is going on.
My bad, I added the wrong version of the switch.py. I am making a few updates based on the pull request review so I will upload something shortly. If you are comfortable pulling from the repo directly that is best anyway. Not sure how I zipped that version up now :(.
Made some updates, the correct files should be in my repo...
https://github.com/TheGardenMonkey/core/tree/dev/homeassistant/components/tplink
Ok, just cloned your repo and copied over your modded tplink component. Everything is working perfect here so far. Will watch it for the next two days and make sure none go unavailable.
Thank you @MarkHofmann11 !
@mikesalz and @aLTeReGo-SWI was curious if either or both of you wouldn't also mind validating. I am not seeing issues with controlling multiple switches at once and the hs300 seems to respond a little better than with my previous change.
@TheGardenMonkey I installed it tonight and ran some tests. It seems to be working pretty well. Here are my findings:
Thank you SO much for your hard work on this! I'm excited to be able to use this powerstrip. I was about 2 days away from returning it!
@TheGardenMonkey Also, just wondering what your thoughts are here. In this thread, (which you're already on) there are some other devs who are working on the integration. Just wondering if you're working with them to get your changes added back into HA? Or is this just kind of a side project?
@TheGardenMonkey I installed it tonight and ran some tests. It seems to be working pretty well. Here are my findings:
- All switches are showing up in HA and are available.
- I turned individual switches on and off multiple times, and it worked reliably every time.
- Turning the group on and off works, but HA seems to have about a 5 second delay registering the new state of the switches. I don't know that I would consider that a bug because it DOES work. It's just slow for some reason.
- When turning a switch on/off via the Kasa app, it sometimes takes up to 25 seconds for HA to register the state change.
- So far I do not have any instances of switch.unnamed_device showing up, but that sometimes takes a day or two to show up. So I'll keep an eye out for that one.
Thank you SO much for your hard work on this! I'm excited to be able to use this powerstrip. I was about 2 days away from returning it!
Thanks for the feedback. The delay sort of makes sense when using the kasa app because I think the act of using the app means that a connection (possibly multiple) are being made to the device which blocks HA from getting a status update. I am not sure if there is away around that. I will give it some more thought though.
@TheGardenMonkey Also, just wondering what your thoughts are here. In this thread, (which you're already on) there are some other devs who are working on the integration. Just wondering if you're working with them to get your changes added back into HA? Or is this just kind of a side project?
We have agreed to go for the quick hack for now while work continues on updating the new backend library. I am hoping once we get this out that I can spend some time assisting with the future / long term approach.
@TheGardenMonkey Bad news. I tried to turn on the group this morning and received this error. It did resume working after I unplugged the powerstrip and plugged it back in.
Log Details (ERROR)
Logger: homeassistant.components.websocket_api.http.connection.139809973655968
Source: custom_components/tplink/switch.py:94
Integration: Home Assistant WebSocket API (documentation, issues)
First occurred: 6:39:24 AM (1 occurrences)
Last logged: 6:39:24 AMCommunication error
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 115, in _query_helper
response = self.protocol.query(
File "/usr/local/lib/python3.8/site-packages/pyHS100/protocol.py", line 47, in query
sock = socket.create_connection((host, port), timeout)
File "/usr/local/lib/python3.8/socket.py", line 808, in create_connection
raise err
File "/usr/local/lib/python3.8/socket.py", line 796, in create_connection
sock.connect(sa)
socket.timeout: timed outThe above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 125, in handle_call_service
await hass.services.async_call(
File "/usr/src/homeassistant/homeassistant/core.py", line 1308, in async_call
task.result()
File "/usr/src/homeassistant/homeassistant/core.py", line 1343, in _execute_service
await handler.func(service_call)
File "/usr/src/homeassistant/homeassistant/components/homeassistant/__init__.py", line 87, in async_handle_turn_service
await asyncio.gather(tasks)
File "/usr/src/homeassistant/homeassistant/core.py", line 1308, in async_call
task.result()
File "/usr/src/homeassistant/homeassistant/core.py", line 1343, in _execute_service
await handler.func(service_call)
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 208, in handle_service
await self.hass.helpers.service.entity_service_call(
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 454, in entity_service_call
future.result() # pop exception if have
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 583, in async_request_call
await coro
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 485, in _handle_entity_call
await result
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 609, in async_turn_on
await self.hass.async_add_executor_job(ft.partial(self.turn_on, *kwargs))
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/tplink/switch.py", line 94, in turn_on
self.smartplug.turn_on()
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartplug.py", line 158, in turn_on
self._query_helper("system", "set_relay_state", {"state": 1})
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 120, in _query_helper
raise SmartDeviceException('Communication error') from ex
pyHS100.smartdevice.SmartDeviceException: Communication error
Does the group only contain the power strip? I am going to take a look shortly.
One thing that might be worth trying is adjusting the SLEEP_TIME = 2 in the switch.py which is what I had been using originally. I don't have a HS300, but I have a KP400 which has two outlets. I was using that setting this past Christmas to control the outside outlets on it with @TheGardenMonkey updates using that SLEEP_TIME setting with no issues.
Yeah I was also using 2 seconds but I was trying to see if the 1 second was really that bad. I haven't noticed an issue but I agree that 2 seconds might be the safer approach.
Yes, the group is only the power strip.
More info - I restarted HA (unrelated to configuring the HS300) and ended up with a switch.unnamed_device showing up.
@MarkHofmann11 Just curious if you tried SLEEP_TIME =1 and MAX_ATTEMPTS = 40 instead? This is the first time I am trying with a second sleep. @mikesalz can you try setting the SLEEP_TIME to 2 for now (this would only help to prevent the initial unnamed device and it would prevent them from becoming unvailable...not the turn_on issue).
For the turn_on, the backend library is throwing the exception so adding a try on that should work, but I am trying to see if there is a better way. Since this is really a band-aid until we can use the new library, that may be the safest option for now. I will try to confirm today.
Thanks @TheGardenMonkey. I changed SLEEP_TIME to 2 and restarted HA. Seems good for now.
Thanks @TheGardenMonkey. I changed SLEEP_TIME to 2 and restarted HA. Seems good for now.
Cool, I guess I was being too aggressive :). I did also get the same error you did btw on turning on my strip this morning (mine only has 5 of the ports, 1 port I always have on). I think the 1 second is hammering it too much and is likely the cause of the other issue since I haven't seen it before when doing 2 seconds. I am going to keep it at 2 for now.
My original mod was using the SLEEP_TIME = 2 which worked perfect for even the multiple outlet tplink. I am still using latest with the SLEEP_TIME = 1 - but I'm also not using the multiple tplink power outlet at the moment. Lots of single wall switches, plugs, lights, etc. I don't break out the strips until Christmas time - but I know they worked with SLEEP_TIME = 2. :)
@MarkHofmann11 I also have several HS105 single outlets and KP400 double outlets. All have worked pretty much perfectly for months. It's just this 6-outlet HS300 that has issues. Glad to know that SLEEP_TIME = 2 worked for you pretty consistently!
@mikesalz You can also try SLEEP_TIME = 3 if you still have issues with the HS300. I don't have any of those, just the KP400. I would think that it is just a matter of finding the best "SLEEP_TIME" setting for it.
@TheGardenMonkey - All my tplink devices have been working flawlessly over here with your fork of the tplink component. It sounds like adjusting the SLEEP_TIME = 2 works better with the strips, so that is the only change I would recommend. That is also the original setting I was using over here. Would be great to have this merged so I don't have to keep re-copying it after each upgrade. I know the long term plan is to go with the new back-end library, but we really need this merged prior - as this has been an issue for almost a year.
@TheGardenMonkey - All my tplink devices have been working flawlessly over here with your fork of the tplink component. It sounds like adjusting the SLEEP_TIME = 2 works better with the strips, so that is the only change I would recommend. That is also the original setting I was using over here. Would be great to have this merged so I don't have to keep re-copying it after each upgrade. I know the long term plan is to go with the new back-end library, but we really need this merged prior - as this has been an issue for almost a year.
I switched it back to 2 for now. I think we are almost there :)
This version is WAYYYY better than the HA version, but I wouldn't say it is flawless. I still encounter occasional errors with the HS300.
This version is WAYYYY better than the HA version, but I wouldn't say it is flawless. I still encounter occasional errors with the HS300.
Yeah definitely not flawless. Other than the "retry" attempts, what issue do you see still? The only thing I am seeing with the hs300 is there are potential for delays when turning on multiple at the same time (with the 1 second I didn't have delays but it is definitely too aggressive).
It works the majority of the time. But even with SLEEP_TIME = 2, I still occasionally get a switch.unnamed_device. I also occasionally get an error.
It works the majority of the time. But even with SLEEP_TIME = 2, I still occasionally get a switch.unnamed_device. I also occasionally get an error.
Just in case, can you try the very latest from my branch? I made a few more changes that in theory should speed up the startup which may make the unnamed_device less likely to happen. If that still doesn't work, can you try setting it to 3 seconds? Also, what are the errors you are seeing?
Yes sir, I will download the latest version today. Next time (if ever) an error pops up, I will share it. Thanks!
I just downloaded the latest and restarted HA. I got another switch.unnamed_device. But the switch was different than the previous one.
I just downloaded the latest and restarted HA. I got another switch.unnamed_device. But the switch was different than the previous one.
You happen to be on discord (i'm the same name there)? I would like to dive in to what you are seeing some more. Can you try with the 3 seconds?
I created a discord account once a while back, but never used it. I'll see if I can get in. In the meantime, I did change to 3. And I just got this error:
Logger: homeassistant
Source: custom_components/tplink/switch.py:103
First occurred: 11:57:25 AM (1 occurrences)
Last logged: 11:57:25 AMError doing job: Task exception was never retrieved
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 115, in _query_helper
response = self.protocol.query(
File "/usr/local/lib/python3.8/site-packages/pyHS100/protocol.py", line 47, in query
sock = socket.create_connection((host, port), timeout)
File "/usr/local/lib/python3.8/socket.py", line 808, in create_connection
raise err
File "/usr/local/lib/python3.8/socket.py", line 796, in create_connection
sock.connect(sa)
socket.timeout: timed outThe above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 802, in async_run
await asyncio.shield(run.async_run())
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 183, in async_run
await self._async_step(log_exceptions=False)
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 191, in _async_step
await getattr(
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 478, in _async_repeat_step
await async_run_sequence(iteration, extra_msg)
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 460, in async_run_sequence
await self._async_run_script(script)
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 526, in _async_run_script
await self._async_run_long_action(
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 342, in _async_run_long_action
long_task.result()
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 802, in async_run
await asyncio.shield(run.async_run())
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 183, in async_run
await self._async_step(log_exceptions=False)
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 191, in _async_step
await getattr(
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 380, in _async_call_service_step
await service_task
File "/usr/src/homeassistant/homeassistant/core.py", line 1308, in async_call
task.result()
File "/usr/src/homeassistant/homeassistant/core.py", line 1343, in _execute_service
await handler.func(service_call)
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 208, in handle_service
await self.hass.helpers.service.entity_service_call(
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 454, in entity_service_call
future.result() # pop exception if have
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 583, in async_request_call
await coro
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 485, in _handle_entity_call
await result
File "/usr/src/homeassistant/homeassistant/components/template/switch.py", line 220, in async_turn_off
await self._off_script.async_run(context=self._context)
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 802, in async_run
await asyncio.shield(run.async_run())
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 183, in async_run
await self._async_step(log_exceptions=False)
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 191, in _async_step
await getattr(
File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 380, in _async_call_service_step
await service_task
File "/usr/src/homeassistant/homeassistant/core.py", line 1308, in async_call
task.result()
File "/usr/src/homeassistant/homeassistant/core.py", line 1343, in _execute_service
await handler.func(service_call)
File "/usr/src/homeassistant/homeassistant/components/homeassistant/__init__.py", line 87, in async_handle_turn_service
await asyncio.gather(tasks)
File "/usr/src/homeassistant/homeassistant/core.py", line 1308, in async_call
task.result()
File "/usr/src/homeassistant/homeassistant/core.py", line 1343, in _execute_service
await handler.func(service_call)
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 208, in handle_service
await self.hass.helpers.service.entity_service_call(
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 454, in entity_service_call
future.result() # pop exception if have
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 583, in async_request_call
await coro
File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 485, in _handle_entity_call
await result
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 618, in async_turn_off
await self.hass.async_add_executor_job(ft.partial(self.turn_off, *kwargs))
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/tplink/switch.py", line 103, in turn_off
self.smartplug.turn_off()
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartplug.py", line 166, in turn_off
self._query_helper("system", "set_relay_state", {"state": 0})
File "/usr/local/lib/python3.8/site-packages/pyHS100/smartdevice.py", line 120, in _query_helper
raise SmartDeviceException('Communication error') from ex
pyHS100.smartdevice.SmartDeviceException: Communication error
I have 2 H300's experiencing issues with plugs going unavailable.
Just tried your latest changes. First time I have ever seen all my plugs online. All seem to be reporting properly and updating.
Amazing work!
Hey everyone, I'm getting up the courage to enable this because I've gotten tired of waiting for the real fix. I'm pretty new to all this so I don't wanna mess things up. I'm running Hassio on a rpi3. from what I understand, I can do the following to install this:
is that it? Do I need to disable my current tpLink integration before restarting? Do I need to delete all my existing devices and entities?
Thanks for the help
Hey everyone, I'm getting up the courage to enable this because I've gotten tired of waiting for the real fix. I'm pretty new to all this so I don't wanna mess things up. I'm running Hassio on a rpi3. from what I understand, I can do the following to install this:
- using the hassio sidebar file editor, create a folder named custom_components in /config
- using the hassio sidebar file editor, create a new file and call it switch.py
- from TheGardenMonkey's GitHub page copy the contents of switch.py and paste it into /config/custom_components/switch.py
- restart hassio
is that it? Do I need to disable my current tpLink integration before restarting? Do I need to delete all my existing devices and entities?
Thanks for the help
under custom_components
you would add a directory named tplink
. You should download all of the files from the repo so that the contents look like:
homeassistant@rpimain1:~/.homeassistant/custom_components/tplink $ ll
-rw-rw-r-- 1 homeassistant homeassistant 5785 Sep 24 20:50 common.py
-rw-rw-r-- 1 homeassistant homeassistant 364 Sep 13 13:37 config_flow.py
-rw-rw-r-- 1 homeassistant homeassistant 117 Sep 13 13:37 const.py
-rw-rw-r-- 1 homeassistant homeassistant 3764 Sep 13 13:37 __init__.py
-rw-rw-r-- 1 homeassistant homeassistant 16646 Sep 24 20:49 light.py
-rw-rw-r-- 1 homeassistant homeassistant 263 Sep 13 13:37 manifest.json
-rw-rw-r-- 1 homeassistant homeassistant 306 Sep 13 13:38 strings.json
-rw-rw-r-- 1 homeassistant homeassistant 5244 Sep 24 20:49 switch.py
You do not have to delete your existing devices or disable anything else. HA will just ignore the out of the box one.
For my existing PR, all of the checks are passing so I am hopeful that means it will be merged soon.
Just added an HS210 wall switch this weekend. Maybe never noticed this, but when you turn it on in HA, it appears to do nothing and the switch goes back to off, then in a few seconds it toggles itself back to on again and the icon color is highlighted as it should. Seems to be timing and could be something with the new switch I just installed. Just figured I would mention it - will do more investigation tomorrow.
My new HS210 is still a mystery, but here are some interesting results of my testing. In HA, turning the HS210 (3-way wall switch) on while watching it in the KASA app shows the light turning on right away. HA doesn't show it turning on until about 8-10 seconds later, resulting in the switch showing off in HA again, then flipping back to an "on" status in HA after 8-10 seconds. Turning off the switch doesn't behave like this, only turning on. It appears to be something in the HA switch status in lovelace is not getting updated right away causing this behavior. None of my other switches behave like this, but I have not added anything new since the tplink integration setup was added. This is also my only HS210 - but they are just a 3-way version of the HS200. I have HS200s and HS220s that don't do this, only the new HS210. Trying to figure out what is different somewhere, as this appears to be a cosmetic issue in HA not showing the updated status right away vs. functionality.
Sorry, forgot to mention one other item. If you have the wrong IP address for a tplink host device and you start HA, it will hang the entire switch component endlessly. I think there was a pull request to fix that issue somewhere.
Just found what might fix this - need to make some changes and will report back. I originally had your retry attempts added under "def update(self)" in switch.py - which should add the retry/pause logic to the switch status. That appears to be where the issue is (switch status). Will try and make the updates here and will report back.
Are you testing with the very latest version (with all files being updated including common.py)? I had made a few updates based on a few tests not being accounted for. I have a bunch of those switches but haven't observed that behavior at all.
I had updated HA to 115.6 this morning and then ensured I had your latest tplink files copied over (from this morning). Not sure what happened with tplink between 114 and 115, but the tplink light doesn't work using your modified files anymore (post the 115.6 upgrade).
You get any errors, you might need to enable debug on custom_components.tplink
No errors - and I'm not running it as a custom_component - just copying over the released tplink version. How would I go about enabling debug on the tplink released component (non-custom)?
Figured out how to turn debugging on. Still nothing of value, all my tplink lights show up "unavailable" - switches, strips, etc working fine.
2020-10-04 12:33:04 DEBUG (MainThread) [homeassistant.components.tplink.common] Getting static devices
2020-10-04 12:33:04 DEBUG (MainThread) [homeassistant.components.tplink] Got 4 lights: 192.168.0.161, 192.168.0.192, 192.168.0.72, 192.168.0.158
2020-10-04 12:33:04 DEBUG (MainThread) [homeassistant.components.tplink] Got 11 switches: 192.168.0.179, 192.168.0.165, 192.168.0.73, 192.168.0.186, 192.168.0.60, 192.168.0.187, 192.168.0.188, 192.168.0.184, 192.168.0.175, 192.168.0.153, 192.168.0.80
I might be wrong, but that looks like the release version...i think it should show custom_component.tplink in the log
Using the original tplink 115 and an old copy of my modded light.py based off your mods works (they are available and functioning properly). Attaching my light.py for reference.
light.zip
The HS210 functions perfect (from a on/off perspective). The issue is with the status of the switch lagging as long as 10 seconds later. The switch actually toggles back off (even though the light turned on instantly) and then around 10-15 seconds later, it toggles back on and shows it being on. It is almost like it is trying to get the switch status from the cloud and not local. The light itself turns off/on instantly. Is it possible that when doing a "switch.garage_light" toggle to on, that is working, but HA isn't getting the result back that it is indeed on? That is what seems to be going on. It later polls and updates the status to on - thus the lag.
Just upgraded and I am not seeing any differences. But your light.py is very different from what is in my repo :). I also simplified the common.py file so you would have to get at least both (and of course the new switch.py).
Also, just wanted to confirm if you are putting them in custom_components/tplink/ or you just overriding the files in the ha install folder for tplink...not that it matters, just curious.
Yes, I am copying over the tplink files from the HA install. I pulled down your latest files from this morning and copied them over the 115.4 install. I recorded a short screen capture of what I am seeing with the HA210.
Overview - Home Assistant - Google Chrome 2020-10-04 13-30-10.zip
The only weirdness I have seen with the HS210 is when I tried to use it in my garage which has a 4 way switch setup (and I didn't realize it when I put it in). It is almost identical to what you are seeing except that in the kasa app it turns off after a few seconds but I don't think it ever turns back on, but maybe I never waited long enough...going to test in a little bit.
Oh also, just in case, is the firmware on the device the latest?
Yes, firmware is the latest. The functionality works perfect - you turn it on via HA, the light comes on instantly. It is just the switch status in HA that doesn't represent the actual light status at the time. Going to do more digging into this - might be some type of status timer that changed in the later versions of HA. I have not added a new tplink entity for awhile, so that is the only thing different.
Fantastic news! I finally figured out how to fix that anomaly with the HS210. I had read a post about someone else with a similar issue - except it was happening in the KASA app. The solution was to delete the HS210 from KASA and then re-create it again. I gave it a shot and it started working normally right away after it was recreated in KASA. I have no idea why that would have any relation to how it functions in HA, but it apparently does.
Now the only question is why the light.py shows unavailable when using your changes. Will dig more into that now. The devices that I have that likely use the light.py are (2) HS220 (switch with dimmers), and (2) LB130 (smart lights). Is there a way to use the GitDesktop app to re-download your clone from 09-15-2020? I think that was what I originally was using and then I can trace from there.
@MarkHofmann11 are you on discord, can you hit me up there and we can try to troubleshoot this together quicker...my dimmer is still in the box :).
FYI - Dimmers working fine. Just the light bulbs - LB130 lights showing unavailable. No errors, just don't come up. Yes, I'm on Discord right now if you want to send me a chat. I'm Mark11#4938. This was working before on your update. I'm going to restore the old files and see what is different with the light.py.
Restored to your modded files from 9/14 - and the smart lights are working again. Lots of changes to review from then until now concerning the smart light (LB130). Still checking... Something after 9/14 is making it not become available.
Most helpful comment
Thank you so much @TheGardenMonkey ! This has helped and my HS300 is working much better, all of the outlets show up now and the on/off functionality is working consistent enough to be used for my intended purposes. Thanks again.