-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathgenerate_enums.py
More file actions
733 lines (601 loc) · 26.6 KB
/
generate_enums.py
File metadata and controls
733 lines (601 loc) · 26.6 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
"""Generate enum files from the Overkiz API reference data."""
# ruff: noqa: T201
from __future__ import annotations
import argparse
import ast
import asyncio
import json
import os
import re
import subprocess
from pathlib import Path
from typing import cast
from pyoverkiz.auth.credentials import UsernamePasswordCredentials
from pyoverkiz.client import OverkizClient
from pyoverkiz.enums import Server
from pyoverkiz.exceptions import OverkizError
from pyoverkiz.models import UIProfileDefinition, ValuePrototype
# Hardcoded protocols that may not be available on all servers
# Format: (name, prefix, id, label)
ADDITIONAL_PROTOCOLS: list[tuple[str, str, int | None, str | None]] = [
("HLRR_WIFI", "hlrrwifi", None, None),
("MODBUSLINK", "modbuslink", 44, "ModbusLink"), # via Atlantic Cozytouch
("RTN", "rtn", None, None),
]
# Hardcoded widgets that may not be available on all servers
# Enum names are derived automatically via to_enum_name()
ADDITIONAL_WIDGETS = [
"AlarmPanelController",
"CyclicGarageDoor",
"CyclicSwingingGateOpener",
"DiscreteGateWithPedestrianPosition",
"HLRRWifiBridge",
"Node",
"SwimmingPoolRollerShutter", # via atlantic_cozytouch
]
async def generate_protocol_enum(server: Server) -> None:
"""Generate the Protocol enum from the Overkiz API."""
username = os.environ["OVERKIZ_USERNAME"]
password = os.environ["OVERKIZ_PASSWORD"]
async with OverkizClient(
server=server,
credentials=UsernamePasswordCredentials(username, password),
) as client:
await client.login()
protocol_types = await client.get_reference_protocol_types()
# Build list of protocol entries (name, prefix, id, label)
protocols: list[tuple[str, str, int | None, str | None]] = [
(p.name, p.prefix, p.id, p.label) for p in protocol_types
]
# Add hardcoded protocols that may not be on all servers (avoid duplicates)
fetched_prefixes = {p.prefix for p in protocol_types}
for name, prefix, proto_id, proto_label in ADDITIONAL_PROTOCOLS:
if prefix not in fetched_prefixes:
protocols.append((name, prefix, proto_id, proto_label))
# Sort by name for consistent output
protocols.sort(key=lambda p: p[0])
# Generate the enum file content
lines = [
'"""Protocol enums describe device URL schemes used by Overkiz.',
"",
"THIS FILE IS AUTO-GENERATED. DO NOT EDIT MANUALLY.",
"Run `uv run utils/generate_enums.py` to regenerate.",
'"""',
"",
"from enum import StrEnum, unique",
"",
"from pyoverkiz.enums.base import UnknownEnumMixin",
"",
"",
"@unique",
"class Protocol(UnknownEnumMixin, StrEnum):",
' """Protocol used by Overkiz.',
"",
" Values have been retrieved from /reference/protocolTypes",
' """',
"",
' UNKNOWN = "unknown"',
"",
]
# Add each protocol as an enum value with label comment
for name, prefix, protocol_id, label in protocols:
if protocol_id is not None:
lines.append(f' {name} = "{prefix}" # {protocol_id}: {label}')
else:
lines.append(f' {name} = "{prefix}"')
lines.append("") # End with newline
# Write to the protocol.py file
output_path = (
Path(__file__).parent.parent / "pyoverkiz" / "enums" / "protocol.py"
)
output_path.write_text("\n".join(lines))
fetched_count = len(protocol_types)
additional_count = len(
[p for p in ADDITIONAL_PROTOCOLS if p[1] not in fetched_prefixes]
)
print(f"✓ Generated {output_path}")
print(f"✓ Added {fetched_count} protocols from API")
print(f"✓ Added {additional_count} additional hardcoded protocols")
print(f"✓ Total: {len(protocols)} protocols")
async def generate_ui_enums(server: Server) -> None:
"""Generate the UIClass and UIWidget enums from the Overkiz API."""
username = os.environ["OVERKIZ_USERNAME"]
password = os.environ["OVERKIZ_PASSWORD"]
async with OverkizClient(
server=server,
credentials=UsernamePasswordCredentials(username, password),
) as client:
await client.login()
ui_classes = cast(list[str], await client.get_reference_ui_classes())
ui_widgets = cast(list[str], await client.get_reference_ui_widgets())
# Convert camelCase to SCREAMING_SNAKE_CASE for enum names
def to_enum_name(value: str) -> str:
# Handle special cases first
name = value.replace("ZWave", "ZWAVE_")
name = name.replace("OTherm", "OTHERM_")
# Insert underscore before uppercase letters
name = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name)
name = re.sub(r"([a-z\d])([A-Z])", r"\1_\2", name)
# Fix specific cases after general conversion
name = name.replace("APCDHW", "APC_DHW")
# Clean up any double underscores and trailing underscores
name = re.sub(r"__+", "_", name)
name = name.rstrip("_")
return name.upper()
# Generate the enum file content
lines = [
'"""UI enums for classes and widgets used to interpret device UI metadata.',
"",
"THIS FILE IS AUTO-GENERATED. DO NOT EDIT MANUALLY.",
"Run `uv run utils/generate_enums.py` to regenerate.",
'"""',
"",
"# ruff: noqa: S105",
'# Enum values contain "PASS" in API names (e.g. PassAPC), not passwords',
"",
"from enum import StrEnum, unique",
"",
"from pyoverkiz.enums.base import UnknownEnumMixin",
"",
"",
"@unique",
"class UIClass(UnknownEnumMixin, StrEnum):",
' """Enumeration of UI classes used to describe device categories and behaviors."""',
"",
' UNKNOWN = "Unknown"',
"",
]
# Add UI classes
sorted_classes = sorted(ui_classes)
for ui_class in sorted_classes:
enum_name = to_enum_name(ui_class)
lines.append(f' {enum_name} = "{ui_class}"')
lines.append("")
lines.append("")
lines.append("@unique")
lines.append("class UIWidget(UnknownEnumMixin, StrEnum):")
lines.append(
' """Enumeration of UI widgets used by Overkiz for device presentation."""'
)
lines.append("")
lines.append(' UNKNOWN = "Unknown"')
lines.append("")
# Add UI widgets
sorted_widgets = sorted(ui_widgets)
# Add hardcoded widgets that may not be on all servers (avoid duplicates)
fetched_widget_values = set(ui_widgets)
for widget_value in ADDITIONAL_WIDGETS:
if widget_value not in fetched_widget_values:
sorted_widgets.append(widget_value)
sorted_widgets = sorted(sorted_widgets)
for ui_widget in sorted_widgets:
enum_name = to_enum_name(ui_widget)
lines.append(f' {enum_name} = "{ui_widget}"')
lines.append("") # End with newline
# Fetch and add UI classifiers
ui_classifiers = cast(list[str], await client.get_reference_ui_classifiers())
lines.append("")
lines.append("@unique")
lines.append("class UIClassifier(UnknownEnumMixin, StrEnum):")
lines.append(
' """Enumeration of UI classifiers used to categorize device types."""'
)
lines.append("")
lines.append(' UNKNOWN = "unknown"')
lines.append("")
# Add UI classifiers
sorted_classifiers = sorted(ui_classifiers)
for ui_classifier in sorted_classifiers:
enum_name = to_enum_name(ui_classifier)
lines.append(f' {enum_name} = "{ui_classifier}"')
lines.append("") # End with newline
# Write to the ui.py file
output_path = Path(__file__).parent.parent / "pyoverkiz" / "enums" / "ui.py"
output_path.write_text("\n".join(lines))
additional_widget_count = len(
[
widget
for widget in ADDITIONAL_WIDGETS
if widget not in fetched_widget_values
]
)
print(f"✓ Generated {output_path}")
print(f"✓ Added {len(ui_classes)} UI classes")
print(f"✓ Added {len(ui_widgets)} UI widgets from API")
print(f"✓ Added {additional_widget_count} additional hardcoded UI widgets")
print(f"✓ Total: {len(sorted_widgets)} UI widgets")
print(f"✓ Added {len(sorted_classifiers)} UI classifiers")
async def generate_ui_profiles(server: Server) -> None:
"""Generate the UIProfile enum from the Overkiz API."""
username = os.environ["OVERKIZ_USERNAME"]
password = os.environ["OVERKIZ_PASSWORD"]
async with OverkizClient(
server=server,
credentials=UsernamePasswordCredentials(username, password),
) as client:
await client.login()
ui_profile_names = await client.get_reference_ui_profile_names()
# Fetch details for all profiles
profiles_with_details: list[tuple[str, UIProfileDefinition | None]] = []
for profile_name in ui_profile_names:
print(f"Fetching {profile_name}...")
try:
details = await client.get_reference_ui_profile(profile_name)
profiles_with_details.append((profile_name, details))
except OverkizError:
print(f" ! Could not fetch details for {profile_name}")
profiles_with_details.append((profile_name, None))
# Convert camelCase to SCREAMING_SNAKE_CASE for enum names
def to_enum_name(value: str) -> str:
# Insert underscore before uppercase letters
name = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", value)
name = re.sub(r"([a-z\d])([A-Z])", r"\1_\2", name)
# Clean up any double underscores
name = re.sub(r"__+", "_", name)
return name.upper()
def format_value_prototype(vp: ValuePrototype) -> str:
"""Format a value prototype into a readable string."""
type_str = vp.type.lower()
parts = [type_str]
if vp.min_value is not None and vp.max_value is not None:
parts.append(f"{vp.min_value}-{vp.max_value}")
elif vp.min_value is not None:
parts.append(f">= {vp.min_value}")
elif vp.max_value is not None:
parts.append(f"<= {vp.max_value}")
if vp.enum_values:
enum_vals = ", ".join(f"'{v}'" for v in vp.enum_values)
parts.append(f"values: {enum_vals}")
return " ".join(parts)
def clean_description(desc: str) -> str:
"""Clean description text to fit in a single-line comment."""
# Remove newlines and excessive whitespace
cleaned = " ".join(desc.split())
return cleaned.strip()
# Generate the enum file content
lines = [
'"""UI Profile enums describe device capabilities through commands and states.',
"",
"THIS FILE IS AUTO-GENERATED. DO NOT EDIT MANUALLY.",
"Run `uv run utils/generate_enums.py` to regenerate.",
'"""',
"",
"from enum import StrEnum, unique",
"",
"from pyoverkiz.enums.base import UnknownEnumMixin",
"",
"",
"@unique",
"class UIProfile(UnknownEnumMixin, StrEnum):",
' """',
" UI Profiles define device capabilities through commands and states.",
" ",
" Each profile describes what a device can do (commands) and what information",
" it provides (states). Form factor indicates if the profile is tied to a",
" specific physical device type.",
' """',
"",
' UNKNOWN = "Unknown"',
"",
]
# Sort profiles by name for consistent output
profiles_with_details.sort(key=lambda p: p[0])
# Add each profile with detailed comments
for profile_name, details_obj in profiles_with_details:
enum_name = to_enum_name(profile_name)
if details_obj is None:
# No details available
lines.append(f" # {profile_name} (details unavailable)")
lines.append(f' {enum_name} = "{profile_name}"')
lines.append("")
continue
# Build multi-line comment
comment_lines = []
# Add commands if present
if details_obj.commands:
comment_lines.append("Commands:")
for cmd in details_obj.commands:
cmd_name = cmd.name
desc = clean_description(cmd.description or "")
# Get parameter info
if cmd.prototype and cmd.prototype.parameters:
param_strs = [
format_value_prototype(param.value_prototypes[0])
for param in cmd.prototype.parameters
if param.value_prototypes
]
param_info = (
f"({', '.join(param_strs)})" if param_strs else "()"
)
else:
param_info = "()"
if desc:
comment_lines.append(f" - {cmd_name}{param_info}: {desc}")
else:
comment_lines.append(f" - {cmd_name}{param_info}")
# Add states if present
if details_obj.states:
if comment_lines:
comment_lines.append("")
comment_lines.append("States:")
for state in details_obj.states:
state_name = state.name
desc = clean_description(state.description or "")
# Get value prototype info
if state.prototype and state.prototype.value_prototypes:
type_info = f" ({format_value_prototype(state.prototype.value_prototypes[0])})"
else:
type_info = ""
if desc:
comment_lines.append(f" - {state_name}{type_info}: {desc}")
else:
comment_lines.append(f" - {state_name}{type_info}")
# Add form factor info
if details_obj.form_factor:
if comment_lines:
comment_lines.append("")
comment_lines.append("Form factor specific: Yes")
# If we have any details, add the comment block
if comment_lines:
lines.append(" #")
lines.append(f" # {profile_name}")
lines.append(" #")
for comment_line in comment_lines:
if comment_line:
lines.append(f" # {comment_line}")
else:
lines.append(" #")
else:
# Simple single-line comment
lines.append(f" # {profile_name}")
lines.append(f' {enum_name} = "{profile_name}"')
lines.append("")
# Write to the ui_profile.py file
output_path = (
Path(__file__).parent.parent / "pyoverkiz" / "enums" / "ui_profile.py"
)
output_path.write_text("\n".join(lines))
print(f"\n✓ Generated {output_path}")
print(f"✓ Added {len(profiles_with_details)} UI profiles")
print(
f"✓ Profiles with details: {sum(1 for _, d in profiles_with_details if d is not None)}"
)
print(
f"✓ Profiles without details: {sum(1 for _, d in profiles_with_details if d is None)}"
)
def extract_commands_from_fixtures(fixtures_dir: Path) -> set[str]:
"""Extract all commands from fixture files in the given directory.
Reads all JSON fixture files and collects unique command names from device
definitions. Commands are returned as camelCase values.
"""
commands: set[str] = set()
for fixture_file in fixtures_dir.glob("*.json"):
try:
data = json.loads(fixture_file.read_text())
if "devices" not in data:
continue
for device in data["devices"]:
if "definition" not in device:
continue
definition = device["definition"]
if "commands" not in definition:
continue
for command in definition["commands"]:
if "commandName" in command:
commands.add(command["commandName"])
except (json.JSONDecodeError, KeyError, TypeError):
# Skip files that can't be parsed or have unexpected structure
continue
return commands
def extract_state_values_from_fixtures(fixtures_dir: Path) -> set[str]:
"""Extract all state values from fixture files in the given directory.
Reads all JSON fixture files and collects unique state values from device
definitions. Values are extracted from DiscreteState types.
"""
values: set[str] = set()
for fixture_file in fixtures_dir.glob("*.json"):
try:
data = json.loads(fixture_file.read_text())
if "devices" not in data:
continue
for device in data["devices"]:
if "definition" not in device:
continue
definition = device["definition"]
if "states" not in definition:
continue
for state in definition["states"]:
# Extract values from DiscreteState
if state.get("type") == "DiscreteState" and "values" in state:
for value in state["values"]:
if isinstance(value, str):
values.add(value)
except (json.JSONDecodeError, KeyError, TypeError):
# Skip files that can't be parsed or have unexpected structure
continue
return values
def command_to_enum_name(command_name: str) -> str:
"""Convert a command name (camelCase) to an ENUM_NAME (SCREAMING_SNAKE_CASE).
Example: "setTargetTemperature" -> "SET_TARGET_TEMPERATURE"
Spaces are converted to underscores: "long peak" -> "LONG_PEAK"
"""
# First, replace spaces with underscores
name = command_name.replace(" ", "_")
# Insert underscore before uppercase letters
name = re.sub(r"([a-z\d])([A-Z])", r"\1_\2", name)
return name.upper()
def extract_enum_members(content: str, class_name: str) -> dict[str, str]:
"""Extract enum member names keyed by their string value from a class definition."""
module = ast.parse(content)
for node in module.body:
if not isinstance(node, ast.ClassDef) or node.name != class_name:
continue
members: dict[str, str] = {}
for statement in node.body:
if not isinstance(statement, ast.Assign):
continue
if len(statement.targets) != 1:
continue
target = statement.targets[0]
if not isinstance(target, ast.Name):
continue
if not isinstance(statement.value, ast.Constant):
continue
if not isinstance(statement.value.value, str):
continue
members[statement.value.value] = target.id
return members
raise ValueError(f"Could not find enum class {class_name}")
def find_class_start(content: str, class_name: str) -> int:
"""Return the start index of a generated enum class declaration."""
class_start = content.find(f"@unique\nclass {class_name}")
if class_start == -1:
raise ValueError(f"Could not find class {class_name}")
return class_start
async def generate_command_enums() -> None:
"""Generate the OverkizCommand enum and update OverkizCommandParam from fixture files."""
fixtures_dir = Path(__file__).parent.parent / "tests" / "fixtures" / "setup"
# Extract commands and state values from fixtures
fixture_commands = extract_commands_from_fixtures(fixtures_dir)
fixture_state_values = extract_state_values_from_fixtures(fixtures_dir)
# Read existing commands from the command.py file
command_file = Path(__file__).parent.parent / "pyoverkiz" / "enums" / "command.py"
content = command_file.read_text()
find_class_start(content, "ExecutionMode")
existing_commands = extract_enum_members(content, "OverkizCommand")
existing_params = extract_enum_members(content, "OverkizCommandParam")
# Merge: keep existing commands and add new ones from fixtures
all_command_values = set(existing_commands.keys()) | fixture_commands
# Convert to list of tuples for commands: (enum_name, command_value)
# Track enum names to detect duplicates
command_enum_names: set[str] = set()
command_tuples: list[tuple[str, str]] = []
for cmd_value in sorted(all_command_values):
if cmd_value in existing_commands:
enum_name = existing_commands[cmd_value]
else:
enum_name = command_to_enum_name(cmd_value)
# Skip if this enum_name already exists (avoid duplicates)
if enum_name not in command_enum_names:
command_tuples.append((enum_name, cmd_value))
command_enum_names.add(enum_name)
# Sort alphabetically by enum name
command_tuples.sort(key=lambda x: x[0])
# Merge: keep existing params and add new ones from fixture state values
all_param_values = set(existing_params.keys()) | fixture_state_values
# Convert to list of tuples for params: (enum_name, param_value)
# Track enum names to detect duplicates
param_enum_names: set[str] = set()
param_tuples: list[tuple[str, str]] = []
for param_value in sorted(all_param_values):
if param_value in existing_params:
enum_name = existing_params[param_value]
else:
enum_name = command_to_enum_name(param_value)
# Skip if this enum_name already exists (avoid duplicates)
if enum_name not in param_enum_names:
param_tuples.append((enum_name, param_value))
param_enum_names.add(enum_name)
# Sort alphabetically by enum name
param_tuples.sort(key=lambda x: x[0])
# Generate the enum file content
lines = [
'"""Command-related enums and parameters used by device commands."""',
"",
"# ruff: noqa: S105",
'# Enum values contain "PASS" in API names (e.g. PassAPC), not passwords',
"",
"from enum import StrEnum, unique",
"",
"",
"@unique",
"class OverkizCommand(StrEnum):",
' """Device commands used by Overkiz."""',
"",
]
# Add each command
for enum_name, cmd_value in command_tuples:
if " " in cmd_value:
lines.append(f' {enum_name} = "{cmd_value}" # value with space')
else:
lines.append(f' {enum_name} = "{cmd_value}"')
lines.append("")
lines.append("")
lines.append("@unique")
lines.append("class OverkizCommandParam(StrEnum):")
lines.append(' """Parameter used by Overkiz commands and/or states."""')
lines.append("")
# Add each param
for enum_name, param_value in param_tuples:
if " " in param_value:
lines.append(f' {enum_name} = "{param_value}" # value with space')
else:
lines.append(f' {enum_name} = "{param_value}"')
lines.append("")
lines.append("")
# Append ExecutionMode class
execution_mode_start = content.find("@unique\nclass ExecutionMode")
if execution_mode_start != -1:
lines.append(content[execution_mode_start:].rstrip())
lines.append("")
# Write to the command.py file
command_file.write_text("\n".join(lines))
print(f"✓ Generated {command_file}")
print(f"✓ Added {len(existing_commands)} existing commands")
print(f"✓ Found {len(fixture_commands)} total commands in fixtures")
new_commands_count = len(fixture_commands - set(existing_commands.keys()))
print(f"✓ Added {new_commands_count} new commands from fixtures")
print(f"✓ Total: {len(all_command_values)} commands")
print()
print(f"✓ Added {len(existing_params)} existing parameters")
print(f"✓ Found {len(fixture_state_values)} total state values in fixtures")
new_params_count = len(fixture_state_values - set(existing_params.keys()))
print(f"✓ Added {new_params_count} new parameters from fixtures")
print(f"✓ Total: {len(all_param_values)} parameters")
def format_generated_files() -> None:
"""Run ruff fixes and formatting on all generated enum files."""
enums_dir = Path(__file__).parent.parent / "pyoverkiz" / "enums"
generated_files = [
str(enums_dir / "protocol.py"),
str(enums_dir / "ui.py"),
str(enums_dir / "ui_profile.py"),
str(enums_dir / "command.py"),
]
subprocess.run( # noqa: S603
["uv", "run", "ruff", "check", "--fix", *generated_files], # noqa: S607
check=True,
)
subprocess.run( # noqa: S603
["uv", "run", "ruff", "format", *generated_files], # noqa: S607
check=True,
)
print("✓ Formatted generated files with ruff")
async def generate_all(server: Server) -> None:
"""Generate all enums from the Overkiz API."""
print(f"Using server: {server.name} ({server.value})")
print()
await generate_protocol_enum(server)
print()
await generate_ui_enums(server)
print()
await generate_ui_profiles(server)
print()
await generate_command_enums()
print()
format_generated_files()
def parse_args() -> argparse.Namespace:
"""Parse command-line arguments."""
server_choices = [s.value for s in Server]
parser = argparse.ArgumentParser(
description="Generate enum files from the Overkiz API."
)
parser.add_argument(
"--server",
choices=server_choices,
default=Server.SOMFY_EUROPE.value,
help=f"Server to connect to (default: {Server.SOMFY_EUROPE.value})",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
asyncio.run(generate_all(Server(args.server)))