Refactor: extract console settings into apply_console_settings(); add apply_config_other wrapper; update get_device_details to use wrapper. Docs: fix Configuration example to separate console and config_other; clarify console section usage. Add dead_functions_summary.md audit confirming no dead functions.

This commit is contained in:
Mike Geppert 2025-08-08 22:32:09 -05:00
parent 126cd39555
commit 5784a0b414
3 changed files with 394 additions and 322 deletions

View File

@ -63,7 +63,11 @@ Create a `network_configuration.json` file with the following structure:
"Password": "mqtt-password", "Password": "mqtt-password",
"Topic": "%hostname_base%", "Topic": "%hostname_base%",
"FullTopic": "%prefix%/%topic%/", "FullTopic": "%prefix%/%topic%/",
"NoRetain": false, "NoRetain": false
},
"config_other": {
"Example_Device_Template": "{\"NAME\":\"Example\",\"GPIO\":[0],\"FLAG\":0,\"BASE\":18}"
},
"console": { "console": {
"SwitchRetain": "Off", "SwitchRetain": "Off",
"ButtonRetain": "Off", "ButtonRetain": "Off",
@ -80,9 +84,13 @@ Create a `network_configuration.json` file with the following structure:
"rule1": "on button1#state=10 do power0 toggle endon" "rule1": "on button1#state=10 do power0 toggle endon"
} }
} }
}
``` ```
Note:
- In the mqtt section, the Topic supports the placeholder "%hostname_base%". The script will replace this with the base of the device's hostname (everything before the first dash). For example, for a device named "KitchenLamp-1234", the Topic will be set to "KitchenLamp".
- NoRetain controls Tasmota's SetOption62 (true = No Retain, false = Use Retain).
- FullTopic typically remains "%prefix%/%topic%/" and is applied according to Tasmota's command format.
## Usage ## Usage
Basic usage: Basic usage:
@ -180,7 +188,7 @@ This feature helps automate the setup of new Tasmota devices that haven't been p
## Console Parameters ## Console Parameters
The script supports setting Tasmota console parameters via the `console` section in the MQTT configuration. After verifying and updating MQTT settings, the script will apply all console parameters to each device. This allows you to: The script supports setting Tasmota console parameters via the `console` section in the configuration. After verifying and updating MQTT settings, the script will apply all console parameters to each device. This allows you to:
- Configure device behavior (PowerOnState, SetOptions, etc.) - Configure device behavior (PowerOnState, SetOptions, etc.)
- Set up rules for button actions - Set up rules for button actions

47
TasmotaManager.py Normal file → Executable file
View File

@ -1325,9 +1325,32 @@ class TasmotaDiscovery:
self.logger.error(f"{name}: Error updating {setting}: {str(e)}") self.logger.error(f"{name}: Error updating {setting}: {str(e)}")
# Apply console settings # Apply console settings
console_updated = self.apply_console_settings(ip, name, with_retry)
# Reboot the device if requested
if reboot:
save_url = f"http://{ip}/cm?cmnd=Restart%201"
response = requests.get(save_url, timeout=5)
if response.status_code == 200:
self.logger.info(f"Saved configuration and rebooted {name}")
else:
self.logger.error(f"Failed to save configuration for {name}")
return mqtt_updated or console_updated
except requests.exceptions.RequestException as e:
self.logger.error(f"Error configuring device at {ip}: {str(e)}")
return False
def apply_console_settings(self, ip, name, with_retry=False):
"""Apply console parameters from configuration to the device.
Returns True if any setting was updated, False otherwise.
"""
console_updated = False console_updated = False
console_params = self.config.get('console', {}) console_params = self.config.get('console', {})
if console_params: if not console_params:
return False
self.logger.info(f"{name}: Setting console parameters from configuration") self.logger.info(f"{name}: Setting console parameters from configuration")
# Special handling for Retain parameters - need to send opposite state first, then final state # Special handling for Retain parameters - need to send opposite state first, then final state
@ -1402,6 +1425,7 @@ class TasmotaDiscovery:
url = f"http://{ip}/cm?cmnd={param}%20{final_value}" url = f"http://{ip}/cm?cmnd={param}%20{final_value}"
success = False success = False
attempts = 0 attempts = 0
max_attempts = 3
last_error = None last_error = None
while not success and attempts < max_attempts: while not success and attempts < max_attempts:
@ -1629,20 +1653,11 @@ class TasmotaDiscovery:
else: else:
self.logger.error(f"{name}: Failed to auto-enable {rule_enable_param}") self.logger.error(f"{name}: Failed to auto-enable {rule_enable_param}")
# Reboot the device if requested return console_updated
if reboot:
save_url = f"http://{ip}/cm?cmnd=Restart%201"
response = requests.get(save_url, timeout=5)
if response.status_code == 200:
self.logger.info(f"Saved configuration and rebooted {name}")
else:
self.logger.error(f"Failed to save configuration for {name}")
return mqtt_updated or console_updated def apply_config_other(self, ip, name):
"""Wrapper for applying config_other (template) settings."""
except requests.exceptions.RequestException as e: return self.check_and_update_template(ip, name)
self.logger.error(f"Error configuring device at {ip}: {str(e)}")
return False
def configure_unknown_device(self, ip, hostname): def configure_unknown_device(self, ip, hostname):
"""Configure an unknown device with the given hostname and MQTT settings.""" """Configure an unknown device with the given hostname and MQTT settings."""
@ -2085,8 +2100,8 @@ class TasmotaDiscovery:
# Check and update MQTT settings if needed # Check and update MQTT settings if needed
mqtt_updated = check_mqtt_settings(ip, name, mqtt_data) mqtt_updated = check_mqtt_settings(ip, name, mqtt_data)
# Check and update template if needed # Check and update template (config_other) if needed
template_updated = self.check_and_update_template(ip, name) template_updated = self.apply_config_other(ip, name)
# Console settings are now applied in configure_mqtt_settings # Console settings are now applied in configure_mqtt_settings
console_updated = mqtt_updated console_updated = mqtt_updated

49
dead_functions_summary.md Normal file
View File

@ -0,0 +1,49 @@
# Dead Functions Audit for TasmotaManager.py
Date: 2025-08-08 22:07
Scope: /home/mgeppert/git_work/scripts/TasmotaManager/TasmotaManager.py
Summary: No dead (unused) functions were found in TasmotaManager.py. All class methods and the top-level main() function are referenced either by other methods, the CLI entry flow, or the test suite.
Method usage highlights (non-exhaustive references):
- UnifiClient
- __init__: Instantiated in main() via TasmotaDiscovery.setup_unifi_client()
- _login: Called by TasmotaDiscovery.setup_unifi_client() (line ~134)
- get_clients: Used in TasmotaDiscovery.get_tasmota_devices() and process_single_device()
- TasmotaDiscovery
- __init__: Instantiated in main()
- load_config: Used in tests and main()
- setup_unifi_client: Used in main() and process_single_device()
- is_tasmota_device: Used in get_tasmota_devices()
- _match_pattern: Used by is_hostname_unknown, is_device_excluded, and hostname bug handling logic
- get_device_hostname: Used in get_device_details() and unknown-device logic; exercised by tests
- is_hostname_unknown: Used in multiple flows; exercised by tests
- is_device_excluded: Used in get_tasmota_devices(), get_device_details(), process_single_device(); exercised by tests
- get_tasmota_devices: Used in main(); exercised by tests
- save_tasmota_config: Used in main()
- get_unknown_devices: Used by process_unknown_devices()
- process_unknown_devices: Invoked when --process-unknown is provided; referenced in main() and docs
- check_and_update_template: Called via apply_config_other() and directly by tests
- configure_mqtt_settings: Called in get_device_details() (via check_mqtt_settings) and configure_unknown_device()
- apply_console_settings: Called from configure_mqtt_settings()
- apply_config_other: Called from get_device_details()
- configure_unknown_device: Called from unknown device flows and process_single_device()
- is_ip_in_network_filter: Used by process_single_device()
- process_single_device: Used by main() and tests (unknown device flows)
- get_device_details: Used by main() and process_single_device()
- Module-level
- main(): Called by the if __name__ == '__main__' guard
Notes:
- Project-wide search across source and tests confirmed usage for each method. Example search hits include:
- is_hostname_unknown: test_pattern_matching.py, test_is_hostname_unknown.py, unifi_hostname_bug_* docs
- get_tasmota_devices: test_get_tasmota_devices.py and main()
- process_unknown_devices: main() and summary docs
- check_and_update_template: multiple tests including test_template_matching.py and test_blank_template_value.py
- get_device_hostname: test_get_device_hostname.py and internal flows
- is_device_excluded: test_is_device_excluded.py and internal flows
Conclusion: No dead functions identified; no removals performed.