62 lines
2.6 KiB
Markdown
62 lines
2.6 KiB
Markdown
# Code Refactoring Summary
|
|
|
|
## Issue Description
|
|
|
|
The code between lines 484-498 in `TasmotaManager.py` was duplicating pattern matching logic that was already implemented in the `is_hostname_unknown` function. This duplication made the code harder to maintain and increased the risk of inconsistencies if one implementation was updated but not the other.
|
|
|
|
## Changes Made
|
|
|
|
### 1. Replaced Duplicated Pattern Matching Logic
|
|
|
|
The original code:
|
|
|
|
```python
|
|
# Check if device name or hostname matches unknown patterns
|
|
unifi_name_matches_unknown = False
|
|
for pattern in unknown_patterns:
|
|
pattern_lower = pattern.lower()
|
|
pattern_regex = pattern_lower.replace('.', r'\.').replace('*', '.*')
|
|
# Check if pattern already starts with ^
|
|
if pattern_regex.startswith('^'):
|
|
regex_pattern = pattern_regex
|
|
else:
|
|
regex_pattern = f"^{pattern_regex}"
|
|
if (re.match(regex_pattern, device_name.lower()) or
|
|
re.match(regex_pattern, device_hostname.lower())):
|
|
unifi_name_matches_unknown = True
|
|
self.logger.debug(f"Device {device_name} matches unknown device pattern: {pattern}")
|
|
break
|
|
```
|
|
|
|
Was replaced with:
|
|
|
|
```python
|
|
# Check if device name or hostname matches unknown patterns
|
|
unifi_name_matches_unknown = (
|
|
self.is_hostname_unknown(device_name, unknown_patterns) or
|
|
self.is_hostname_unknown(device_hostname, unknown_patterns)
|
|
)
|
|
if unifi_name_matches_unknown:
|
|
self.logger.debug(f"Device {device_name} matches unknown device pattern")
|
|
```
|
|
|
|
### 2. Benefits of the Change
|
|
|
|
1. **Code Reuse**: The change leverages the existing `is_hostname_unknown` function, which already handles pattern matching logic correctly.
|
|
2. **Maintainability**: By centralizing the pattern matching logic in one place, future changes only need to be made in one location.
|
|
3. **Consistency**: Ensures that pattern matching is performed consistently throughout the codebase.
|
|
4. **Readability**: The code is now more concise and easier to understand.
|
|
|
|
### 3. Testing
|
|
|
|
A comprehensive test script `test_get_tasmota_devices.py` was created to verify that the changes work correctly. The script includes tests for:
|
|
|
|
1. Devices that match unknown patterns
|
|
2. Devices affected by the Unifi hostname bug
|
|
3. Devices that match exclude patterns
|
|
|
|
All tests passed, confirming that the changes maintain the same behavior and functionality as the original code.
|
|
|
|
## Conclusion
|
|
|
|
This refactoring improves the codebase by reducing duplication and increasing maintainability without changing the behavior of the application. The pattern matching logic is now centralized in the `is_hostname_unknown` function, making it easier to maintain and update in the future. |