Skip to content

Commit 4324eb9

Browse files
authored
Merge pull request #2272 from TCWORLD/remove-log-f-strings
Replace f-string usage in _LOGGER calls with printf style
2 parents fea8a3b + 89de5b2 commit 4324eb9

29 files changed

Lines changed: 911 additions & 629 deletions

custom_components/solax_modbus/__init__.py

Lines changed: 217 additions & 163 deletions
Large diffs are not rendered by default.

custom_components/solax_modbus/button.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
4747
if button_info.value_function:
4848
hub.computedEntities[button_info.key] = button_info
4949
elif button_info.command is None:
50-
_LOGGER.warning(f"button without command and without value_function found: {button_info.key}")
50+
_LOGGER.warning("button without command and without value_function found: %s", button_info.key)
5151

5252
# register dependency chain
5353
deplist = button_info.depends_on
@@ -60,13 +60,13 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
6060
tuple,
6161
),
6262
):
63-
_LOGGER.debug(f"{hub.name}: {button_info.key} depends on entities {deplist}")
63+
_LOGGER.debug("%s: %s depends on entities %s", hub.name, button_info.key, deplist)
6464
for dep_on in deplist: # register inter-sensor dependencies (e.g. for value functions)
6565
if dep_on != button_info.key:
6666
hub.entity_dependencies.setdefault(dep_on, []).append(button_info.key) # can be more than one
6767

6868
async_add_entities(entities)
69-
_LOGGER.info(f"hub.wakeuButton: {hub.wakeupButton}")
69+
_LOGGER.info("hub.wakeuButton: %s", hub.wakeupButton)
7070
return True
7171

7272

@@ -110,15 +110,15 @@ def unique_id(self) -> str | None:
110110
async def async_press(self) -> None:
111111
"""Write the button value."""
112112
if self._write_method == WRITE_MULTISINGLE_MODBUS:
113-
_LOGGER.info(f"writing {self._platform_name} button register {self._register} value {self._command}")
113+
_LOGGER.info("writing %s button register %s value %s", self._platform_name, self._register, self._command)
114114
await self._hub.async_write_registers_single(
115115
unit=self._modbus_addr,
116116
address=self._register,
117117
payload=self._command,
118118
register_data_type=getattr(self.button_info, "register_data_type", None),
119119
)
120120
elif self._write_method == WRITE_SINGLE_MODBUS:
121-
_LOGGER.info(f"writing {self._platform_name} button register {self._register} value {self._command}")
121+
_LOGGER.info("writing %s button register %s value %s", self._platform_name, self._register, self._command)
122122
await self._hub.async_write_register(
123123
unit=self._modbus_addr,
124124
address=self._register,
@@ -137,8 +137,8 @@ async def async_press(self) -> None:
137137
data = res.get("data", None)
138138
action = res.get("action")
139139
if not action:
140-
_LOGGER.error(f"autorepeat value function for {self._key} must return dict containing action")
141-
_LOGGER.info(f"writing {self._platform_name} button register {self._register} value {res}")
140+
_LOGGER.error("autorepeat value function for %s must return dict containing action", self._key)
141+
_LOGGER.info("writing %s button register %s value %s", self._platform_name, self._register, res)
142142
if action == WRITE_MULTI_MODBUS:
143143
await self._hub.async_write_registers_multi(unit=self._modbus_addr, address=reg, payload=data)
144144
else:

custom_components/solax_modbus/config_flow.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ def _configured_hub_names(handler: SchemaCommonFlowHandler) -> set[str]:
219219

220220

221221
async def _validate_base(handler: SchemaCommonFlowHandler, user_input: dict[str, Any]) -> dict[str, Any]:
222-
_LOGGER.info(f"validating base: {user_input}")
222+
_LOGGER.info("validating base: %s", user_input)
223223
"""Validate config."""
224224
user_input[CONF_INTERFACE]
225225
user_input[CONF_MODBUS_ADDR]
@@ -229,15 +229,15 @@ async def _validate_base(handler: SchemaCommonFlowHandler, user_input: dict[str,
229229
# convert old style to new style plugin name here - Remove later after a breaking upgrade
230230
if pluginconf_name.startswith("custom_components") or pluginconf_name.startswith("/config") or pluginconf_name.startswith("plugin_"):
231231
newpluginname = pluginconf_name.split("plugin_", 1)[1][:-3] # getPluginName(pluginconf_name)
232-
_LOGGER.warning(f"converting old style plugin name {pluginconf_name} to new style: {newpluginname} ")
232+
_LOGGER.warning("converting old style plugin name %s to new style: %s ", pluginconf_name, newpluginname)
233233
user_input[CONF_PLUGIN] = newpluginname
234234
pluginconf_name = newpluginname
235235
# end of conversion
236236

237-
_LOGGER.info(f"validating base config for {name}: pre: {user_input}")
237+
_LOGGER.info("validating base config for %s: pre: %s", name, user_input)
238238
# if getPlugin(name) or ((name == DEFAULT_NAME) and (pluginconf_name != DEFAULT_PLUGIN)):
239239
if (name == DEFAULT_NAME) and (pluginconf_name != DEFAULT_PLUGIN):
240-
_LOGGER.warning(f"instance name {name} already defined or default name for non-default inverter")
240+
_LOGGER.warning("instance name %s already defined or default name for non-default inverter", name)
241241
user_input[CONF_NAME] = user_input[CONF_PLUGIN] # getPluginName(user_input[CONF_PLUGIN])
242242
raise SchemaFlowError("name_already_used")
243243

@@ -261,7 +261,7 @@ async def _validate_host(handler: SchemaCommonFlowHandler, user_input: Any) -> A
261261
res = all(x and not disallowed.search(x) for x in host.split("."))
262262
if not res:
263263
raise SchemaFlowError("invalid_host") from e
264-
_LOGGER.info(f"validating host: returning data: {user_input}")
264+
_LOGGER.info("validating host: returning data: %s", user_input)
265265

266266
pluginconf_name = handler.options[CONF_PLUGIN]
267267
plugin = await handler.parent_handler.hass.async_add_executor_job(_load_plugin, pluginconf_name)
@@ -287,7 +287,7 @@ async def _next_step_modbus(user_input: Any) -> str:
287287

288288

289289
async def _next_step_battery(user_input: Any) -> str | None:
290-
_LOGGER.debug(f"_next_step_battery: returning data: {user_input}")
290+
_LOGGER.debug("_next_step_battery: returning data: %s", user_input)
291291
if user_input.get("support-battery", False):
292292
return "battery"
293293
return "duplicate_inverter"
@@ -329,7 +329,7 @@ def _load_plugin(plugin_name: str) -> ModuleType:
329329

330330

331331
if (MAJOR_VERSION >= 2023) or ((MAJOR_VERSION == 2022) and (MINOR_VERSION >= 12)): # type: ignore[comparison-overlap] # backward compat
332-
_LOGGER.info(f"detected HA core version {MAJOR_VERSION} {MINOR_VERSION}")
332+
_LOGGER.info("detected HA core version %s %s", MAJOR_VERSION, MINOR_VERSION)
333333
CONFIG_FLOW: dict[str, SchemaFlowFormStep | SchemaFlowMenuStep] = {
334334
"user": SchemaFlowFormStep(CONFIG_SCHEMA, validate_user_input=_validate_base, next_step=_next_step_modbus),
335335
"serial": SchemaFlowFormStep(SERIAL_SCHEMA, next_step=_next_step_battery),
@@ -348,7 +348,7 @@ def _load_plugin(plugin_name: str) -> ModuleType:
348348
}
349349

350350
else: # for older versions - REMOVE SOON
351-
_LOGGER.error(f"detected old HA core version {MAJOR_VERSION} {MINOR_VERSION}")
351+
_LOGGER.error("detected old HA core version %s %s", MAJOR_VERSION, MINOR_VERSION)
352352

353353

354354
class ConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN):
@@ -358,11 +358,11 @@ async def async_step_user(self, user_input: dict[str, Any] | None = None) -> Con
358358
"""Handle a flow initialized by the user."""
359359
return await super().async_step_user(user_input)
360360

361-
_LOGGER.info(f"starting configflow - domain = {DOMAIN}")
361+
_LOGGER.info("starting configflow - domain = %s", DOMAIN)
362362
config_flow = CONFIG_FLOW
363363
options_flow = OPTIONS_FLOW
364364

365365
def async_config_entry_title(self, options: Mapping[str, Any]) -> str:
366-
_LOGGER.info(f"title configflow {DOMAIN} {CONF_NAME}: {options}")
366+
_LOGGER.info("title configflow %s %s: %s", DOMAIN, CONF_NAME, options)
367367
# Return config entry title
368368
return cast(str, options[CONF_NAME]) if CONF_NAME in options else ""

custom_components/solax_modbus/debug.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def load_debug_settings(config: dict[str, Any] | None, hass: Any = None) -> dict
5252
list(yaml_debug_settings.keys()),
5353
)
5454
except Exception as e:
55-
_LOGGER.debug(f"Error reading debug settings from YAML configuration: {e}")
55+
_LOGGER.debug("Error reading debug settings from YAML configuration: %s", e)
5656

5757
return debug_settings
5858

@@ -115,7 +115,7 @@ def get_debug_setting(
115115
for key, settings in debug_settings.items():
116116
if key.lower() == inverter_name.lower():
117117
inverter_settings = settings
118-
_LOGGER.debug(f"get_debug_setting: Matched '{inverter_name}' to '{key}' (case-insensitive)")
118+
_LOGGER.debug("get_debug_setting: Matched '%s' to '%s' (case-insensitive)", inverter_name, key)
119119
break
120120

121121
if inverter_settings and setting_name in inverter_settings:

custom_components/solax_modbus/energy_dashboard.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ def get_source_key(self, datadict: dict[str, float]) -> str:
313313
# Prefer PM totals on Primary when available.
314314
# Validate PM sensor exists before using it
315315
if self.source_key_pm not in datadict:
316-
_LOGGER.warning(f"Parallel Master detected but PM sensor {self.source_key_pm} not found, falling back to {self.source_key}")
316+
_LOGGER.warning("Parallel Master detected but PM sensor %s not found, falling back to %s", self.source_key_pm, self.source_key)
317317
return self.source_key
318318
return self.source_key_pm # Use PM sensor on Master
319319

@@ -327,7 +327,7 @@ def get_value(self, datadict: dict[str, float]) -> float | None:
327327
# This avoids resetting total increasing sensors and unintentionally breaking energy statistics.
328328
value = datadict.get(source_key, None)
329329
if value is None:
330-
_LOGGER.debug(f"Source sensor {source_key} not found or has no value, marking unavailable")
330+
_LOGGER.debug("Source sensor %s not found or has no value, marking unavailable", source_key)
331331
return None
332332

333333
# Apply filter function first (universal - applies to all sensor types)
@@ -708,7 +708,7 @@ def _create_sensor_from_mapping(
708708
source_hub: Optional hub to read data from (if different from hub, e.g., for Slave sensors)
709709
name_prefix: Optional prefix to add to sensor name (e.g., "All ", "Solax 1 ")
710710
"""
711-
_LOGGER.debug(f"_create_sensor_from_mapping: name_prefix='{name_prefix}', target_key={sensor_mapping.target_key}")
711+
_LOGGER.debug("_create_sensor_from_mapping: name_prefix='%s', target_key=%s", name_prefix, sensor_mapping.target_key)
712712
sensors = []
713713

714714
# Use source_hub if provided, otherwise use hub
@@ -728,7 +728,7 @@ def value_function(initval: Any, descr: Any, datadict: dict[str, Any]) -> Any:
728728
return sensor_mapping.get_value(hub_data)
729729
except Exception as e:
730730
hub_name = getattr(captured_hub, "_name", "Unknown")
731-
_LOGGER.error(f"Error getting value for {sensor_mapping.target_key} from hub {hub_name}: {e}")
731+
_LOGGER.error("Error getting value for %s from hub %s: %s", sensor_mapping.target_key, hub_name, e)
732732
return None
733733

734734
return value_function
@@ -862,23 +862,23 @@ def value_function(initval: Any, descr: Any, datadict: dict[str, Any]) -> Any:
862862
master_value = sensor_mapping.get_value(master_data)
863863
total = master_value if master_value is not None else 0
864864
except Exception as e:
865-
_LOGGER.debug(f"{master_name}: Error getting Master value for aggregation: {e}")
865+
_LOGGER.debug("%s: Error getting Master value for aggregation: %s", master_name, e)
866866
total = 0
867867

868868
# Sum all Slave values
869869
for slave_name, slave_hub in slave_hubs:
870870
try:
871871
slave_data = getattr(slave_hub, "data", None) or getattr(slave_hub, "datadict", {})
872872
if not slave_data:
873-
_LOGGER.debug(f"{master_name}: Slave hub '{slave_name}' has no data, using 0 for aggregation")
873+
_LOGGER.debug("%s: Slave hub '%s' has no data, using 0 for aggregation", master_name, slave_name)
874874
continue
875875

876876
slave_value = sensor_mapping.get_value(slave_data)
877877
if slave_value is not None:
878878
total += slave_value
879879
# If slave_value is None, treat as 0 (already handled by not adding)
880880
except Exception as e:
881-
_LOGGER.debug(f"{master_name}: Error getting Slave '{slave_name}' value for aggregation: {e}, using 0")
881+
_LOGGER.debug("%s: Error getting Slave '%s' value for aggregation: %s, using 0", master_name, slave_name, e)
882882
# Continue with other Slaves (treat this Slave as 0)
883883

884884
return total
@@ -929,14 +929,14 @@ async def create_energy_dashboard_sensors(hub: Any, mapping: EnergyDashboardMapp
929929
default=False,
930930
)
931931
ed_is_master = is_master and not debug_standalone
932-
_LOGGER.info(f"{hub_name}: Energy Dashboard sensor creation - parallel_setting={parallel_setting}, is_master={is_master}")
932+
_LOGGER.info("%s: Energy Dashboard sensor creation - parallel_setting=%s, is_master=%s", hub_name, parallel_setting, is_master)
933933

934934
# Find Slave hubs if this is a Master
935935
slave_hubs = []
936936
if ed_is_master and hass:
937937
slave_hubs = _find_slave_hubs(hass, hub)
938938
if slave_hubs:
939-
_LOGGER.info(f"Found {len(slave_hubs)} registered Slave hub(s) for Energy Dashboard")
939+
_LOGGER.info("Found %s registered Slave hub(s) for Energy Dashboard", len(slave_hubs))
940940
else:
941941
_LOGGER.debug("No Slave hubs found for Energy Dashboard (Master mode but no Slaves)")
942942
elif ed_is_master and not hass:
@@ -1147,7 +1147,7 @@ def _detect_variants(hub_obj: Any, mapping: Any, base_key: str) -> list[int]:
11471147
# Create "Solax 1" sensor (Master individual)
11481148
# Check if individual sensors should be skipped
11491149
_LOGGER.debug(
1150-
f"Master individual check: target_key={sensor_mapping.target_key}, skip_pm_individuals={sensor_mapping.skip_pm_individuals}"
1150+
"Master individual check: target_key=%s, skip_pm_individuals=%s", sensor_mapping.target_key, sensor_mapping.skip_pm_individuals
11511151
)
11521152
if not sensor_mapping.skip_pm_individuals:
11531153
# For Master individual, force use of non-PM sensor by setting source_key_pm=None
@@ -1176,7 +1176,9 @@ def _detect_variants(hub_obj: Any, mapping: Any, base_key: str) -> list[int]:
11761176

11771177
# Create "Solax 2/3" sensors from Slave hubs
11781178
# Check if individual sensors should be skipped
1179-
_LOGGER.debug(f"Slave individual check: target_key={sensor_mapping.target_key}, skip_pm_individuals={sensor_mapping.skip_pm_individuals}")
1179+
_LOGGER.debug(
1180+
"Slave individual check: target_key=%s, skip_pm_individuals=%s", sensor_mapping.target_key, sensor_mapping.skip_pm_individuals
1181+
)
11801182
if not sensor_mapping.skip_pm_individuals:
11811183
for slave_name, slave_hub in slave_hubs:
11821184
sensors.extend(
@@ -1254,12 +1256,12 @@ def validate_mapping(mapping: EnergyDashboardMapping) -> bool:
12541256
bool: True if mapping is valid, False otherwise
12551257
"""
12561258
if not mapping.mappings:
1257-
_LOGGER.error(f"Plugin {mapping.plugin_name}: No mappings defined")
1259+
_LOGGER.error("Plugin %s: No mappings defined", mapping.plugin_name)
12581260
return False
12591261

12601262
for sensor_mapping in mapping.mappings:
12611263
if not sensor_mapping.source_key or not sensor_mapping.target_key:
1262-
_LOGGER.error(f"Invalid mapping: missing source_key or target_key for {mapping.plugin_name}")
1264+
_LOGGER.error("Invalid mapping: missing source_key or target_key for %s", mapping.plugin_name)
12631265
return False
12641266

12651267
return True

0 commit comments

Comments
 (0)