Skip to content

Commit b64265c

Browse files
refactor: consolidate shared utility functions into models module (#50)
* refactor: consolidate shared utility functions into models module Move convert_temp, temp_suffix, and display_name from their duplicated private definitions across cli.py, tui/widgets.py, and tui/temperature_screen.py into a single canonical location in models.py. These are now public API functions re-exported from the flameconnect package. - convert_temp: was _convert_temp in 3 files, now single definition - temp_suffix: was _temp_suffix with different signatures in cli.py (list[Parameter]) and widgets.py (TempUnitParam | None), unified to the cleaner TempUnitParam | None signature - display_name: was _display_name in widgets.py, used across TUI - Remove _find_temp_unit (replaced by _find_param with TempUnitParam) - Add TempUnitParam overload to _find_param for type safety - Update all source and test imports across 11 files - Add new tests for the three public functions in test_models.py Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: fix ruff formatting (extra blank lines) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
1 parent bd55172 commit b64265c

11 files changed

Lines changed: 198 additions & 165 deletions

‎src/flameconnect/__init__.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@
4343
TempUnitParam,
4444
TimerParam,
4545
TimerStatus,
46+
convert_temp,
47+
display_name,
48+
temp_suffix,
4649
)
4750

4851
__all__ = [
@@ -92,4 +95,8 @@
9295
"NAMED_COLORS",
9396
# Type aliases
9497
"Parameter",
98+
# Utilities
99+
"convert_temp",
100+
"display_name",
101+
"temp_suffix",
95102
]

‎src/flameconnect/cli.py‎

Lines changed: 12 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@
3636
TempUnitParam,
3737
TimerParam,
3838
TimerStatus,
39+
convert_temp,
40+
temp_suffix,
3941
)
4042

4143
# ---------------------------------------------------------------------------
@@ -164,6 +166,12 @@ def _find_param(
164166
) -> HeatParam | None: ...
165167

166168

169+
@overload
170+
def _find_param(
171+
parameters: list[Parameter], param_type: type[TempUnitParam]
172+
) -> TempUnitParam | None: ...
173+
174+
167175
def _find_param[T](parameters: list[Parameter], param_type: type[T]) -> T | None:
168176
"""Find the first parameter of a given type in a list."""
169177
for p in parameters:
@@ -177,43 +185,14 @@ def _find_param[T](parameters: list[Parameter], param_type: type[T]) -> T | None
177185
# ---------------------------------------------------------------------------
178186

179187

180-
def _temp_suffix(parameters: list[Parameter]) -> str:
181-
"""Return 'C' or 'F' based on TempUnitParam in *parameters*, or ''."""
182-
for p in parameters:
183-
if isinstance(p, TempUnitParam):
184-
return "C" if p.unit == TempUnit.CELSIUS else "F"
185-
return ""
186-
187-
188-
def _find_temp_unit(
189-
parameters: list[Parameter],
190-
) -> TempUnitParam | None:
191-
"""Return the TempUnitParam from *parameters*, or ``None``."""
192-
for p in parameters:
193-
if isinstance(p, TempUnitParam):
194-
return p
195-
return None
196-
197-
198-
def _convert_temp(celsius: float, unit: TempUnit) -> float:
199-
"""Convert a Celsius temperature for display.
200-
201-
Returns the value unchanged when *unit* is CELSIUS, or
202-
converts to Fahrenheit (rounded to 1 decimal) when FAHRENHEIT.
203-
"""
204-
if unit == TempUnit.CELSIUS:
205-
return celsius
206-
return round(celsius * 9 / 5 + 32, 1)
207-
208-
209188
def _display_mode(
210189
param: ModeParam,
211190
temp_unit: TempUnitParam | None = None,
212191
) -> None:
213192
"""Display Mode parameter."""
214193
unit = temp_unit.unit if temp_unit else TempUnit.CELSIUS
215194
unit_suffix = ("C" if unit == TempUnit.CELSIUS else "F") if temp_unit else ""
216-
display_temp = _convert_temp(param.target_temperature, unit)
195+
display_temp = convert_temp(param.target_temperature, unit)
217196
print("\n [321] Mode")
218197
print(f" {'─' * 40}")
219198
mode = _enum_name(_FIRE_MODE_NAMES, param.mode)
@@ -251,7 +230,7 @@ def _display_heat(
251230
"""Display HeatSettings parameter."""
252231
unit = temp_unit.unit if temp_unit else TempUnit.CELSIUS
253232
unit_suffix = ("C" if unit == TempUnit.CELSIUS else "F") if temp_unit else ""
254-
display_temp = _convert_temp(param.setpoint_temperature, unit)
233+
display_temp = convert_temp(param.setpoint_temperature, unit)
255234
print("\n [323] Heat Settings")
256235
print(f" {'─' * 40}")
257236
status = _enum_name(_HEAT_STATUS_NAMES, param.heat_status)
@@ -446,7 +425,7 @@ async def cmd_status(client: FlameConnectClient, fire_id: str) -> None:
446425
return
447426

448427
count = len(overview.parameters)
449-
temp_unit = _find_temp_unit(overview.parameters)
428+
temp_unit = _find_param(overview.parameters, TempUnitParam)
450429
print(f"\n{count} parameter(s) reported:")
451430
for param in overview.parameters:
452431
_display_parameter(param, temp_unit)
@@ -701,7 +680,7 @@ async def _set_heat_temp(client: FlameConnectClient, fire_id: str, value: str) -
701680
if current is None:
702681
print("Error: no HeatSettings parameter found.")
703682
sys.exit(1)
704-
unit_suffix = _temp_suffix(overview.parameters)
683+
unit_suffix = temp_suffix(_find_param(overview.parameters, TempUnitParam))
705684
new_param = replace(current, setpoint_temperature=temp)
706685
await client.write_parameters(fire_id, [new_param])
707686
print(f"Heat temperature set to {temp}\u00b0{unit_suffix}.")

‎src/flameconnect/models.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,34 @@ class TempUnitParam:
297297
unit: TempUnit
298298

299299

300+
# ---------------------------------------------------------------------------
301+
# Display / conversion utilities
302+
# ---------------------------------------------------------------------------
303+
304+
305+
def convert_temp(celsius: float, unit: TempUnit) -> float:
306+
"""Convert a Celsius temperature for display.
307+
308+
Returns the value unchanged when *unit* is CELSIUS, or
309+
converts to Fahrenheit (rounded to 1 decimal) when FAHRENHEIT.
310+
"""
311+
if unit == TempUnit.CELSIUS:
312+
return celsius
313+
return round(celsius * 9 / 5 + 32, 1)
314+
315+
316+
def temp_suffix(temp_unit: TempUnitParam | None) -> str:
317+
"""Return the temperature unit suffix (``'C'`` or ``'F'``), or empty."""
318+
if temp_unit is None:
319+
return ""
320+
return "C" if temp_unit.unit == TempUnit.CELSIUS else "F"
321+
322+
323+
def display_name(value: IntEnum) -> str:
324+
"""Convert an IntEnum member name to Title Case for display."""
325+
return value.name.replace("_", " ").title()
326+
327+
300328
@dataclass(frozen=True, slots=True)
301329
class SoundParam:
302330
"""Sound parameter (ParameterId 369)."""

‎src/flameconnect/tui/app.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717
from textual.widgets.option_list import Option
1818

1919
from flameconnect import __version__
20+
from flameconnect.models import display_name
2021
from flameconnect.tui.auth_screen import AuthScreen
2122
from flameconnect.tui.screens import DashboardScreen
22-
from flameconnect.tui.widgets import _display_name
2323

2424
if TYPE_CHECKING:
2525
import asyncio
@@ -216,7 +216,7 @@ async def _load_fires(self) -> None:
216216
loading.update("[bold]Select a fireplace:[/bold]")
217217
options = [
218218
Option(
219-
f"{fire.friendly_name} ({_display_name(fire.connection_state)})",
219+
f"{fire.friendly_name} ({display_name(fire.connection_state)})",
220220
id=fire.fire_id,
221221
)
222222
for fire in self.fires
@@ -598,7 +598,7 @@ def _apply_flame_color(self, color: FlameColor) -> None:
598598
if not isinstance(current, FlameEffectParam):
599599
return
600600
new_param = replace(current, flame_color=color)
601-
label = _display_name(color)
601+
label = display_name(color)
602602
self._run_command(
603603
self.client.write_parameters(self.fire_id, [new_param]),
604604
f"Setting flame color to {label}...",
@@ -650,7 +650,7 @@ def _apply_media_theme(self, theme: MediaTheme) -> None:
650650

651651
_LOGGER.debug("Media theme change: sending=%s", new_param)
652652

653-
label = _display_name(theme)
653+
label = display_name(theme)
654654
fire_id = self.fire_id
655655
self._write_in_progress = True
656656
screen.log_message(f"Setting media theme to {label}...")
@@ -842,7 +842,7 @@ def _apply_heat_mode(self, mode: HeatMode, boost_minutes: int | None) -> None:
842842
new_param = replace(current, heat_mode=mode, boost_duration=boost_minutes)
843843
else:
844844
new_param = replace(current, heat_mode=mode)
845-
mode_label = _display_name(mode)
845+
mode_label = display_name(mode)
846846
self._run_command(
847847
self.client.write_parameters(self.fire_id, [new_param]),
848848
f"Setting heat mode to {mode_label}...",

‎src/flameconnect/tui/fire_select_screen.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
from textual.screen import ModalScreen
99
from textual.widgets import Button, Static
1010

11-
from flameconnect.models import Fire
12-
from flameconnect.tui.widgets import _display_name
11+
from flameconnect.models import Fire, display_name
1312

1413
if TYPE_CHECKING:
1514
from textual.app import ComposeResult
@@ -79,7 +78,7 @@ def compose(self) -> ComposeResult:
7978
yield Static("Switch Fireplace", id="fire-select-title")
8079
with Vertical(id="fire-select-list"):
8180
for idx, fire in enumerate(self._fires):
82-
conn = _display_name(fire.connection_state)
81+
conn = display_name(fire.connection_state)
8382
label = (
8483
f"{idx + 1}. {fire.friendly_name}"
8584
f" \u2014 {fire.brand} {fire.product_model}"

‎src/flameconnect/tui/temperature_screen.py‎

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,13 @@
88
from textual.screen import ModalScreen
99
from textual.widgets import Button, Input, Static
1010

11-
from flameconnect.models import TempUnit
11+
from flameconnect.models import TempUnit, convert_temp
1212
from flameconnect.tui.widgets import ArrowNavMixin
1313

1414
if TYPE_CHECKING:
1515
from textual.app import ComposeResult
1616

1717

18-
def _convert_temp(celsius: float, unit: TempUnit) -> float:
19-
"""Convert a Celsius temperature for display.
20-
21-
Returns the value unchanged when *unit* is CELSIUS, or
22-
converts to Fahrenheit (rounded to 1 decimal) when FAHRENHEIT.
23-
"""
24-
if unit == TempUnit.CELSIUS:
25-
return celsius
26-
return round(celsius * 9 / 5 + 32, 1)
27-
28-
2918
def _convert_to_celsius(
3019
fahrenheit: float,
3120
) -> float:
@@ -98,7 +87,7 @@ def compose(self) -> ComposeResult:
9887
unit_str = "\u00b0C" if self._unit == TempUnit.CELSIUS else "\u00b0F"
9988
celsius = self._unit == TempUnit.CELSIUS
10089
range_str = "5.0 \u2013 35.0" if celsius else "40.0 \u2013 95.0"
101-
display_temp = _convert_temp(self._current_temp, self._unit)
90+
display_temp = convert_temp(self._current_temp, self._unit)
10291
with Vertical(id="temp-dialog"):
10392
yield Static(
10493
f"Set Temperature (current: {display_temp}{unit_str})",

0 commit comments

Comments
 (0)