-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathconfig.py
More file actions
180 lines (142 loc) · 5.46 KB
/
Copy pathconfig.py
File metadata and controls
180 lines (142 loc) · 5.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#
# Copyright (c) 2023-2026 Project CHIP Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json
from enum import Enum
from pathlib import Path
from pydantic import BaseModel
from th_cli.exceptions import CLIError
def known_cli_path() -> Path:
"""Return the known CLI path from the home directory."""
return Path.home() / "certification-tool" / "cli"
def get_package_root() -> Path:
"""
Get the root directory of the package installation.
This works for both editable and non-editable installations.
"""
# Get the directory containing this config.py file
return Path(__file__).parent
def find_git_root() -> Path | None:
"""
Find the root directory containing the CLI's .git folder.
This is needed for git operations and will find the original source.
"""
# Start from the package root
current_path = get_package_root()
# Walk up the directory tree looking for .git
while current_path != current_path.parent:
if (current_path / ".git").exists():
return current_path
current_path = current_path.parent
# If not found in package location, try current working directory
current_path = known_cli_path()
while current_path != current_path.parent:
if (current_path / ".git").exists():
return current_path
current_path = current_path.parent
return None
def get_config_search_paths() -> list[Path]:
"""
Get a list of paths to search for configuration files.
"""
paths = []
# Always include current working directory
paths.append(Path.cwd())
# Include known CLI path in home directory
paths.append(known_cli_path())
# Include package installation directory
package_root = get_package_root()
paths.append(package_root)
return paths
class LogConfig(BaseModel):
output_log_path: str = "./run_logs"
format: str = (
"<level>{level: <8}</level> | <green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{message}</level>"
)
class Config(BaseModel):
hostname: str = "localhost"
log_config: LogConfig = LogConfig()
def get_default_config():
"""Return default configuration when no config file is found"""
return {
"hostname": "localhost",
"log_config": {
"output_log_path": "./run_logs",
"format": "<level>{level: <8}</level> | \
<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | \
<level>{message}</level>",
},
}
def load_config():
"""Load configuration with fallbacks"""
# Get dynamic search paths
search_paths = get_config_search_paths()
# Try different possible locations for config files
possible_locations: list[Path] = []
for path in search_paths:
possible_locations.append(path / "config.json")
for config_path in possible_locations:
if config_path.exists():
try:
return Config.model_validate_json(config_path.read_text(encoding="utf-8"))
except Exception as e:
CLIError(f"Could not load config from {config_path}: {e}")
continue
# Try to create config from example file
example_locations = []
for path in search_paths:
example_locations.append(path / "config.json.example")
for example_path in example_locations:
if example_path.exists():
try:
with open(example_path, "r", encoding="utf-8") as f:
lines = f.readlines()
json_content = "".join(line for line in lines if not line.lstrip().startswith("#")).strip()
config_data = json.loads(json_content)
return Config(**config_data)
except Exception as e:
print(f"Warning: Could not load example config from {example_path}: {e}")
continue
# Fall back to default configuration
print("Warning: Using default configuration")
default_config = get_default_config()
return Config(**default_config)
# Load the configuration
config = load_config()
class PairingMode(str, Enum):
BLE_WIFI = "ble-wifi"
BLE_THREAD = "ble-thread"
WIFIPAF_WIFI = "wifipaf-wifi"
NFC_THREAD = "nfc-thread"
NFC_ETHERNET = "nfc-ethernet"
ONNETWORK = "onnetwork"
VALID_PAIRING_MODES = {mode.value for mode in PairingMode}
ATTRIBUTE_MAPPING: dict[str, tuple[str, ...]] = {
# Thread dataset attributes
"channel": ("network", "thread", "dataset"),
"panid": ("network", "thread", "dataset"),
"extpanid": ("network", "thread", "dataset"),
"networkkey": ("network", "thread", "dataset"),
"networkname": ("network", "thread", "dataset"),
# Other thread attributes
"rcp_serial_path": ("network", "thread"),
"rcp_baudrate": ("network", "thread"),
"on_mesh_prefix": ("network", "thread"),
"network_interface": ("network", "thread"),
"operational_dataset_hex": ("network", "thread"),
# WiFi attributes
"ssid": ("network", "wifi"),
"password": ("network", "wifi"),
}