GeezerVison is showing github.com — "Unclosed client session" Trying to set brightness on Tapo Bulb · Issue #828 · python-kasa/python-kasa
"Unclosed client session" Trying to set brightness on Tapo Bulb #828DescriptionI'm trying to get some basic bulb automation running but I'm running into an issue trying to set brightness (even though I can do it via terminal command). Before I call update() the bulbs show as not supporting dimming (which seems to be the expected behavior.
However, after calling update() on the bulb, calling set_brightness() results in a Unclosed client session error
Code:
async def main():
devices = await kasa.Discover.discover(credentials=kasa.Credentials(username=username, password=password))
print('Found '+str(len(devices))+' devices to manage')
print()
for key in devices:
await devices[key].update()
print("Device: "+str(key))
print(" Alias: "+str(devices[key].alias))
print(" Host: "+str(devices[key].host))
print(" Type: "+str(devices[key].device_type))
print(" Model: "+str(devices[key].model))
print(" Class: "+devices[key].__class__.__name__)
# print(" Owner: "+str(devices[key].sys_info['owner']))
# print(" ID: "+str(devices[key].sys_info['device_id']))
# print(" MAC: "+str(devices[key].sys_info['mac']))
print(" Info: "+str(devices[key].sys_info))
# await devices[key].disconnect()
if isinstance(devices[key], kasa.SmartBulb):
print(" Is a bulb!")
if devices[key].is_dimmable:
await devices[key].set_brightness(0)
#time.sleep(3)
#await devices[key].set_brightness(100)
else:
print(" But isn't dimmabled!")
else:
print(" Not a bulb!")
print()
if __name__ == "__main__":
asyncio.run(main())
Output:
Found 3 devices to manage
Device: 192.168.0.181
Alias: Garage Lamp
Host: 192.168.0.181
Type: DeviceType.Bulb
Model: L530
Class: TapoBulb
Info: {'device_id': '8023BE7226ADF677390B874C59029B981F94C9D6', 'fw_ver': '1.1.0 Build 230721 Rel.224802', 'hw_ver': '2.0', 'type': 'SMART.TAPOBULB', 'model': 'L530', 'mac': '14-EB-B6-D3-25-35', 'hw_id': 'FDE1C68674D1535B12A042682B192E4E', 'fw_id': '00000000000000000000000000000000', 'oem_id': '90171A8CAC7DBD1A9BE64C1449D24A6A', 'color_temp_range': [2500, 6500], 'overheated': False, 'ip': '192.168.0.181', 'time_diff': -480, 'ssid': 'QmlnR3VscA==', 'rssi': -57, 'signal_level': 2, 'latitude': 455073, 'longitude': -1226173, 'lang': 'en_US', 'avatar': 'hang_lamp_1', 'region': 'America/Los_Angeles', 'specs': '', 'nickname': 'R2FyYWdlIExhbXA=', 'has_set_location_info': True, 'device_on': True, 'brightness': 29, 'hue': 120, 'saturation': 100, 'color_temp': 0, 'dynamic_light_effect_enable': False, 'default_states': {'re_power_type': 'always_on', 'type': 'last_states', 'state': {'brightness': 29, 'hue': 120, 'saturation': 100, 'color_temp': 0}}}
Is a bulb!
Traceback (most recent call last):
File "/home/shkkmo/projects/tapo/test_tapo.py", line 37, in <module>
asyncio.run(main())
File "/usr/lib/python3.11/asyncio/runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "/home/shkkmo/projects/tapo/test_tapo.py", line 27, in main
await devices[key].set_brightness(0)
File "/home/shkkmo/projects/tapo/lib/python3.11/site-packages/kasa/tapo/tapobulb.py", line 202, in set_brightness
return await self.protocol.query(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/shkkmo/projects/tapo/lib/python3.11/site-packages/kasa/smartprotocol.py", line 63, in query
return await self._query(request, retry_count)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/shkkmo/projects/tapo/lib/python3.11/site-packages/kasa/smartprotocol.py", line 100, in _query
raise ex
File "/home/shkkmo/projects/tapo/lib/python3.11/site-packages/kasa/smartprotocol.py", line 68, in _query
return await self._execute_query(request, retry)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/shkkmo/projects/tapo/lib/python3.11/site-packages/kasa/smartprotocol.py", line 175, in _execute_query
self._handle_response_error_code(response_data)
File "/home/shkkmo/projects/tapo/lib/python3.11/site-packages/kasa/smartprotocol.py", line 197, in _handle_response_error_code
raise SmartDeviceException(msg, error_code=error_code)
kasa.exceptions.SmartDeviceException: Error querying device: 192.168.0.181: PARAMS_ERROR(-1008)
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0xffffba01f6d0>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0xffffb9fee0b0>, 44381.088592999)]']
connector: <aiohttp.connector.TCPConnector object at 0xffffba34ae50>
I was able to get the transport error to disappear by adding some error handling to make sure the transport gets closed after an error in my execution path.
try:
self._handle_response_error_code(response_data)
except TimeoutException as e:
raise e
except RetryableException as e:
raise e
except AuthenticationException as e:
_LOGGER.debug("Closing transport due to exception")
await self.close()
raise e
except SmartDeviceException as e:
_LOGGER.debug("Closing transport due to exception")
await self.close()
raise e
except Exception as e:
raise e
Something like this probably needs to be used to wrap every invocation of _handle_response_error_code, but there seem to be broader issues with making sure the transport gets closed as I ran into that error a lot in my testing.
The root cause of my -1008 error is because Tapo bulbs do not support setting brightness to 0 but we don't excluded 0 as a viable value in _raise_for_invalid_brightness Activitysdb9696 commented on May 1, 2024 Hi, the PR to limit the brightness range #829 is merged so the issue you were having should be fixed.
w.r.t to the unclosed client session this is only a warning emitted if a device aiohttp connection is not closed after the app has terminated. It may be that it doesn't get emitted if your program runs to completion without an error due to aiohttp recognising the loop has shut down gracefully and closing it for you. If you wrap your code in a try/finally and call await device.disconnect() in the finally these warnings should go away even under error conditions.
I'll close this for now but do please come back if this doesn't work for you.
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|