فهرست منبع

config_flow: update logging per HA recommendations.

- to avoid evaluating args when logging is disabled, use old style formatting.
- side effect: output dps as json, not python object.
  This will make it easier to copy/paste into config_match script from
  future error reports.
Jason Rumney 3 سال پیش
والد
کامیت
8734134dcb
3فایلهای تغییر یافته به همراه43 افزوده شده و 20 حذف شده
  1. 20 7
      custom_components/tuya_local/config_flow.py
  2. 8 13
      custom_components/tuya_local/device.py
  3. 15 0
      custom_components/tuya_local/helpers/log.py

+ 20 - 7
custom_components/tuya_local/config_flow.py

@@ -1,7 +1,7 @@
 import logging
 
 import voluptuous as vol
-from homeassistant import config_entries, data_entry_flow
+from homeassistant import config_entries
 from homeassistant.const import CONF_HOST, CONF_NAME
 from homeassistant.core import HomeAssistant, callback
 
@@ -16,6 +16,7 @@ from .const import (
     CONF_TYPE,
 )
 from .helpers.device_config import get_config
+from .helpers.log import log_json
 
 _LOGGER = logging.getLogger(__name__)
 
@@ -87,16 +88,24 @@ class ConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
             best_match = int(best_match)
             dps = self.device._get_cached_state()
             _LOGGER.warning(
-                f"Device matches {best_matching_type} with quality of {best_match}%. DPS: {dps}"
+                "Device matches %s with quality of %d%%. DPS: %s",
+                best_matching_type,
+                best_match,
+                log_json(dps),
             )
             _LOGGER.warning(
-                f"Report this to https://github.com/make-all/tuya-local/issues/"
+                "Report this to https://github.com/make-all/tuya-local/issues/"
             )
         if types:
             return self.async_show_form(
                 step_id="select_type",
                 data_schema=vol.Schema(
-                    {vol.Required(CONF_TYPE, default=best_matching_type): vol.In(types)}
+                    {
+                        vol.Required(
+                            CONF_TYPE,
+                            default=best_matching_type,
+                        ): vol.In(types),
+                    }
                 ),
             )
         else:
@@ -146,10 +155,14 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
                 errors["base"] = "connection"
 
         schema = {
-            vol.Required(CONF_LOCAL_KEY, default=config.get(CONF_LOCAL_KEY, "")): str,
+            vol.Required(
+                CONF_LOCAL_KEY,
+                default=config.get(CONF_LOCAL_KEY, ""),
+            ): str,
             vol.Required(CONF_HOST, default=config.get(CONF_HOST, "")): str,
             vol.Required(
-                CONF_PROTOCOL_VERSION, default=config.get(CONF_PROTOCOL_VERSION, "auto")
+                CONF_PROTOCOL_VERSION,
+                default=config.get(CONF_PROTOCOL_VERSION, "auto"),
             ): vol.In(["auto"] + API_PROTOCOL_VERSIONS),
             vol.Required(
                 CONF_POLL_ONLY, default=config.get(CONF_POLL_ONLY, False)
@@ -185,7 +198,7 @@ async def async_test_connection(config: dict, hass: HomeAssistant):
         await device.async_refresh()
         retval = device if device.has_returned_state else None
     except Exception as e:
-        _LOGGER.warning(e)
+        _LOGGER.warning("Connection test failed with %s %s", type(e), e)
         retval = None
 
     if existing:

+ 8 - 13
custom_components/tuya_local/device.py

@@ -3,7 +3,6 @@ API for Tuya Local devices.
 """
 
 import asyncio
-import json
 import logging
 import tinytuya
 from threading import Lock
@@ -27,16 +26,12 @@ from .const import (
     DOMAIN,
 )
 from .helpers.device_config import possible_matches
+from .helpers.log import log_json
 
 
 _LOGGER = logging.getLogger(__name__)
 
 
-def non_json(input):
-    """Handler for json_dumps when used for debugging."""
-    return f"Non-JSON: ({input})"
-
-
 class TuyaLocalDevice(object):
     def __init__(
         self,
@@ -181,7 +176,7 @@ class TuyaLocalDevice(object):
                     _LOGGER.debug(
                         "%s received %s",
                         self.name,
-                        json.dumps(poll, default=non_json),
+                        log_json(poll),
                     )
                     self._cached_state = self._cached_state | poll
                     self._cached_state["updated_at"] = time()
@@ -191,7 +186,7 @@ class TuyaLocalDevice(object):
                     _LOGGER.debug(
                         "%s received non data %s",
                         self.name,
-                        json.dumps(poll, default=non_json),
+                        log_json(poll),
                     )
             _LOGGER.warning("%s receive loop has terminated", self.name)
 
@@ -322,7 +317,7 @@ class TuyaLocalDevice(object):
             _LOGGER.warning(
                 "Detection for %s with dps %s failed",
                 self.name,
-                json.dumps(cached_state, default=non_json),
+                log_json(cached_state),
             )
             return None
 
@@ -368,11 +363,11 @@ class TuyaLocalDevice(object):
         _LOGGER.debug(
             "%s refreshed device state: %s",
             self.name,
-            json.dumps(new_state, default=non_json),
+            log_json(new_state),
         )
         _LOGGER.debug(
             "new state (incl pending): %s",
-            json.dumps(self._get_cached_state(), default=non_json),
+            log_json(self._get_cached_state()),
         )
 
     async def async_set_properties(self, properties):
@@ -396,7 +391,7 @@ class TuyaLocalDevice(object):
         _LOGGER.debug(
             "%s new pending updates: %s",
             self.name,
-            json.dumps(pending_updates, default=non_json),
+            log_json(pending_updates),
         )
 
     async def _debounce_sending_updates(self):
@@ -419,7 +414,7 @@ class TuyaLocalDevice(object):
         _LOGGER.debug(
             "%s sending dps update: %s",
             self.name,
-            json.dumps(pending_properties, default=non_json),
+            log_json(pending_properties),
         )
 
         await self._retry_on_failed_connection(

+ 15 - 0
custom_components/tuya_local/helpers/log.py

@@ -0,0 +1,15 @@
+"""
+Functions for logging
+"""
+
+import json
+
+
+def non_json(input):
+    """Handler for json_dumps when used for debugging."""
+    return f"Non-JSON: ({input})"
+
+
+def log_json(data):
+    """Function for logging data as json."""
+    return json.dumps(data, default=non_json)