Add detailed reporting when no template match is found

This commit is contained in:
Mike Geppert 2025-08-06 20:52:15 -05:00
parent d585f0f284
commit 3e6001568f
3 changed files with 159 additions and 1 deletions

View File

@ -678,7 +678,14 @@ class TasmotaDiscovery:
else:
self.logger.error(f"{name}: Failed to update device name")
else:
self.logger.debug(f"{name}: No matches found in config_other for device name or template")
# No matches found, print detailed information about what's on the device
self.logger.info(f"{name}: No matches found in config_other for either Device Name or Template")
self.logger.info(f"{name}: Current Device Name on device: '{device_name}'")
self.logger.info(f"{name}: Current Template on device: '{current_template}'")
print(f"\nNo template match found for device {name} at {ip}")
print(f" Device Name on device: '{device_name}'")
print(f" Template on device: '{current_template}'")
print("Please add an appropriate entry to mqtt.config_other in your configuration file.")
return template_updated

View File

@ -0,0 +1,63 @@
# Template No Match Tracking and Reporting
## Issue Description
When the `check_and_update_template` method couldn't find a match for either the Device Name or Template in the `mqtt.config_other` configuration, it would silently continue without providing any information about what was set on the device. This made it difficult for users to understand why a template wasn't applied and what the current device configuration was.
## Changes Made
The `check_and_update_template` method has been enhanced to track and report detailed information when no match is found. Specifically:
1. Changed the log level from DEBUG to INFO for better visibility in logs
2. Added more detailed log messages that include:
- A clear message that no matches were found
- The current Device Name on the device
- The current Template on the device
3. Added user-friendly console output using `print()` statements that:
- Clearly indicates no template match was found
- Shows the device name and IP address
- Displays the current Device Name on the device
- Displays the current Template on the device
- Provides a suggestion to add an appropriate entry to the configuration file
## Code Changes
The following changes were made to the `check_and_update_template` method:
```python
# Before
else:
self.logger.debug(f"{name}: No matches found in config_other for device name or template")
# After
else:
# No matches found, print detailed information about what's on the device
self.logger.info(f"{name}: No matches found in config_other for either Device Name or Template")
self.logger.info(f"{name}: Current Device Name on device: '{device_name}'")
self.logger.info(f"{name}: Current Template on device: '{current_template}'")
print(f"\nNo template match found for device {name} at {ip}")
print(f" Device Name on device: '{device_name}'")
print(f" Template on device: '{current_template}'")
print("Please add an appropriate entry to mqtt.config_other in your configuration file.")
```
## Testing
A test script `test_template_no_match.py` was created to verify the changes. The script:
1. Gets a test device from current.json
2. Temporarily modifies the mqtt.config_other section to ensure no match will be found
3. Calls the check_and_update_template method
4. Verifies that appropriate messages are printed
The test confirmed that the method now correctly tracks and reports detailed information when no match is found.
## Benefits
These changes provide several benefits:
1. **Better Visibility**: Users can now see when a template match is not found, rather than the process silently continuing.
2. **Detailed Information**: The current Device Name and Template on the device are clearly displayed, making it easier to understand the current configuration.
3. **Actionable Guidance**: The message suggests adding an appropriate entry to the configuration file, guiding users on how to resolve the issue.
This enhancement improves the user experience by providing clear, actionable information when a template match is not found, helping users understand and resolve configuration issues more easily.

88
test_template_no_match.py Executable file
View File

@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""
Test script to verify that appropriate messages are printed when no template match is found.
This script:
1. Gets a test device from current.json
2. Temporarily modifies the mqtt.config_other section to ensure no match will be found
3. Calls the check_and_update_template method
4. Verifies that appropriate messages are printed
"""
import json
import logging
import sys
import os
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
# Import TasmotaManager class
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from TasmotaManager import TasmotaDiscovery
def get_test_device():
"""Get a test device from current.json"""
try:
with open('current.json', 'r') as f:
data = json.load(f)
devices = data.get('tasmota', {}).get('devices', [])
if devices:
return devices[0] # Use the first device
else:
logger.error("No devices found in current.json")
return None
except Exception as e:
logger.error(f"Error reading current.json: {e}")
return None
def main():
"""Main test function"""
# Get a test device
device = get_test_device()
if not device:
logger.error("No test device available. Run discovery first.")
return 1
device_name = device.get('name')
device_ip = device.get('ip')
logger.info(f"Testing with device: {device_name} (IP: {device_ip})")
# Create a TasmotaDiscovery instance
discovery = TasmotaDiscovery(debug=True)
# Load the configuration
discovery.load_config('network_configuration.json')
# Temporarily modify the mqtt.config_other section to ensure no match will be found
# Save the original config_other
original_config_other = discovery.config.get('mqtt', {}).get('config_other', {})
# Set an empty config_other to ensure no match
discovery.config['mqtt']['config_other'] = {
"NonExistentDevice": '{"NAME":"Test Device","GPIO":[0,0,0,0,0,0,0,0,0,0,0,0,0],"FLAG":0,"BASE":18}'
}
logger.info("Modified mqtt.config_other to ensure no match will be found")
# Call the check_and_update_template method
logger.info("Calling check_and_update_template method")
result = discovery.check_and_update_template(device_ip, device_name)
# Verify the result
logger.info(f"Result of check_and_update_template: {result}")
# Restore the original config_other
discovery.config['mqtt']['config_other'] = original_config_other
logger.info("Test completed. Check the output above to verify that appropriate messages were printed.")
return 0
if __name__ == "__main__":
sys.exit(main())