jasonacox / tinytuya

Python API for Tuya WiFi smart devices using a direct local area network (LAN) connection or the cloud (TuyaCloud API).
MIT License
951 stars 172 forks source link

UnboundLocalError: cannot access local variable 'err' where it is not associated with a value , core.py line 948, in _get_socket #402

Closed simon-kuzin closed 1 year ago

simon-kuzin commented 1 year ago

If connection error occurs XenonDevice._get_socket fails with an exception UnboundLocalError: cannot access local variable 'err' where it is not associated with a value

Stacktrace: Exception has occurred: UnboundLocalError (note: full exception trace is shown but execution is paused at: _run_module_as_main) cannot access local variable 'err' where it is not associated with a value File "/Users/Simon/Projects/SmartHome/tinytuya/.venv/lib/python3.11/site-packages/tinytuya/core.py", line 948, in _get_socket return err ^^^ File "/Users/Simon/Projects/SmartHome/tinytuya/.venv/lib/python3.11/site-packages/tinytuya/core.py", line 1085, in _send_receive sock_result = self._get_socket(False) ^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/Simon/Projects/SmartHome/tinytuya/.venv/lib/python3.11/site-packages/tinytuya/core.py", line 1845, in set_value data = self._send_receive(payload, getresponse=(not nowait)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/Simon/Projects/SmartHome/tinytuya/.venv/lib/python3.11/site-packages/tinytuya/Contrib/IRRemoteControlDevice.py", line 237, in send_command self.set_value( IRRemoteControlDevice.DP_SEND_IR, json.dumps(command), nowait=True ) File "/Users/Simon/Projects/SmartHome/tinytuya/.venv/lib/python3.11/site-packages/tinytuya/Contrib/RFRemoteControlDevice.py", line 89, in send_command super(RFRemoteControlDevice, self).send_command( mode, data ) ...

Root cause: in _get_socket ` if self.socket is None:

Set up Socket

        retries = 0
        err = ERR_OFFLINE
       ...
       except socket.timeout as err:
          ...
          err = ERR_OFFLINE
       except Exception as err:
          ...
          err = ERR_OFFLINE

`

declaration of err in except statement overrides local err

solution rename exception variable in except statements . e.g. except Exception as e:

jasonacox commented 1 year ago

Good catch @simon-kuzin ! Thank you!

jasonacox commented 1 year ago

Updated in v1.12.11 (pip install --upgrade tinytuya)

Please let us know if this fixes your issue.

simon-kuzin commented 1 year ago

Issue fixed with 1.12.11. We can close it.