aioescea 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
aioescea/__init__.py ADDED
@@ -0,0 +1,71 @@
1
+ """Async client for Escea gas fireplaces on the local network."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .discovery import MAC_PREFIX, DiscoveredFireplace, async_discover, async_find
6
+ from .exceptions import (
7
+ EsceaAuthError,
8
+ EsceaBusyError,
9
+ EsceaConnectionError,
10
+ EsceaError,
11
+ EsceaPortInUseError,
12
+ EsceaProtocolError,
13
+ EsceaStateError,
14
+ )
15
+ from .fireplace import (
16
+ POWER_CHANGE_BUSY_SECONDS,
17
+ EsceaFireplace,
18
+ FireMode,
19
+ FireplaceState,
20
+ mode_from_status,
21
+ )
22
+ from .ncapi import (
23
+ NCAPI_MAX_TEMPERATURE,
24
+ NCAPI_MIN_TEMPERATURE,
25
+ EsceaNcapiClient,
26
+ EsceaNcapiError,
27
+ FireState,
28
+ NcapiStatus,
29
+ async_probe,
30
+ )
31
+ from .protocol import MAX_TEMPERATURE, MIN_TEMPERATURE, Status
32
+ from .transport import UDP_PORT, EsceaTransport
33
+ from .web import Diagnostics, EsceaWebClient, HomePage, Timer
34
+
35
+ __version__ = "0.1.0"
36
+
37
+ __all__ = [
38
+ "MAC_PREFIX",
39
+ "MAX_TEMPERATURE",
40
+ "MIN_TEMPERATURE",
41
+ "NCAPI_MAX_TEMPERATURE",
42
+ "NCAPI_MIN_TEMPERATURE",
43
+ "POWER_CHANGE_BUSY_SECONDS",
44
+ "UDP_PORT",
45
+ "Diagnostics",
46
+ "DiscoveredFireplace",
47
+ "EsceaAuthError",
48
+ "EsceaBusyError",
49
+ "EsceaConnectionError",
50
+ "EsceaError",
51
+ "EsceaFireplace",
52
+ "EsceaNcapiClient",
53
+ "EsceaNcapiError",
54
+ "EsceaPortInUseError",
55
+ "EsceaProtocolError",
56
+ "EsceaStateError",
57
+ "EsceaTransport",
58
+ "EsceaWebClient",
59
+ "FireMode",
60
+ "FireState",
61
+ "FireplaceState",
62
+ "HomePage",
63
+ "NcapiStatus",
64
+ "Status",
65
+ "Timer",
66
+ "__version__",
67
+ "async_discover",
68
+ "async_find",
69
+ "async_probe",
70
+ "mode_from_status",
71
+ ]
aioescea/__main__.py ADDED
@@ -0,0 +1,151 @@
1
+ """Command-line tool: ``python -m aioescea`` or ``aioescea``.
2
+
3
+ Examples::
4
+
5
+ aioescea discover
6
+ aioescea status 192.168.1.50
7
+ aioescea on 192.168.1.50
8
+ aioescea temp 192.168.1.50 22
9
+ aioescea mode 192.168.1.50 boost
10
+ aioescea timers 192.168.1.50
11
+ aioescea diagnostics 192.168.1.50 --username 123456 --password 1234
12
+ aioescea g3-status 192.168.1.60
13
+ aioescea g3-set 192.168.1.60 --on --mode flame_effect --temp 22.5
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import asyncio
20
+ from dataclasses import asdict
21
+ import json
22
+ import logging
23
+ import sys
24
+ from typing import Any
25
+
26
+ import aiohttp
27
+
28
+ from . import (
29
+ EsceaError,
30
+ EsceaFireplace,
31
+ EsceaNcapiClient,
32
+ EsceaTransport,
33
+ EsceaWebClient,
34
+ FireMode,
35
+ async_discover,
36
+ )
37
+
38
+
39
+ def _print(value: Any) -> None:
40
+ print(json.dumps(value, indent=2, default=str))
41
+
42
+
43
+ async def _run_g3(args: argparse.Namespace) -> None:
44
+ async with aiohttp.ClientSession() as session:
45
+ fire = EsceaNcapiClient(session, args.host)
46
+ if args.command == "g3-set":
47
+ mode = FireMode(args.mode) if args.mode else None
48
+ await fire.async_set(
49
+ on=args.on,
50
+ fan_boost=None if mode is None else mode is FireMode.BOOST,
51
+ flame_effect=None if mode is None else mode is FireMode.FLAME_EFFECT,
52
+ target_temperature=args.temp,
53
+ )
54
+ _print(asdict(await fire.async_get_status()))
55
+
56
+
57
+ async def _run(args: argparse.Namespace) -> None:
58
+ if args.command.startswith("g3-"):
59
+ await _run_g3(args)
60
+ return
61
+ if args.command in ("timers", "diagnostics"):
62
+ async with aiohttp.ClientSession() as session:
63
+ web = EsceaWebClient(
64
+ session, args.host, username=args.username, password=args.password
65
+ )
66
+ if args.command == "timers":
67
+ _print(asdict(await web.async_get_home_page()))
68
+ else:
69
+ _print(asdict(await web.async_get_diagnostics()))
70
+ return
71
+
72
+ async with EsceaTransport() as transport:
73
+ if args.command == "discover":
74
+ fires = await async_discover(
75
+ transport, args.broadcast or ["255.255.255.255"], timeout=args.timeout
76
+ )
77
+ _print([asdict(fire) for fire in fires])
78
+ return
79
+ fire = EsceaFireplace(args.host, transport)
80
+ if args.command == "on":
81
+ await fire.async_turn_on()
82
+ elif args.command == "off":
83
+ await fire.async_turn_off()
84
+ elif args.command == "temp":
85
+ await fire.async_set_temperature(args.temperature)
86
+ elif args.command == "mode":
87
+ await fire.async_set_mode(
88
+ FireMode(args.mode), allow_ignite=args.allow_ignite
89
+ )
90
+ _print(asdict(await fire.async_get_status()))
91
+
92
+
93
+ def main() -> None:
94
+ """Run the command-line tool."""
95
+ parser = argparse.ArgumentParser(
96
+ prog="aioescea", description=__doc__.splitlines()[0]
97
+ )
98
+ parser.add_argument("-v", "--verbose", action="store_true", help="debug logging")
99
+ sub = parser.add_subparsers(dest="command", required=True)
100
+
101
+ discover = sub.add_parser("discover", help="find fireplaces by broadcast")
102
+ discover.add_argument("--broadcast", action="append", help="broadcast address")
103
+ discover.add_argument("--timeout", type=float, default=5.0)
104
+
105
+ for name, text in (
106
+ ("status", "read the live status"),
107
+ ("on", "light the fire"),
108
+ ("off", "turn the fire off"),
109
+ ):
110
+ sub.add_parser(name, help=text).add_argument("host")
111
+
112
+ temp = sub.add_parser("temp", help="set the target temperature")
113
+ temp.add_argument("host")
114
+ temp.add_argument("temperature", type=int)
115
+
116
+ mode = sub.add_parser("mode", help="set normal, boost or flame_effect")
117
+ mode.add_argument("host")
118
+ mode.add_argument("mode", choices=[m.value for m in FireMode])
119
+ mode.add_argument("--allow-ignite", action="store_true")
120
+
121
+ for name, text in (
122
+ ("timers", "read clock, temperatures and timers from the web page"),
123
+ ("diagnostics", "read the diagnostics web page"),
124
+ ):
125
+ web = sub.add_parser(name, help=text)
126
+ web.add_argument("host")
127
+ web.add_argument("--username")
128
+ web.add_argument("--password")
129
+
130
+ sub.add_parser("g3-status", help="read a Generation 3 (Wi-Fi) fire").add_argument(
131
+ "host"
132
+ )
133
+ g3 = sub.add_parser("g3-set", help="change a Generation 3 (Wi-Fi) fire")
134
+ g3.add_argument("host")
135
+ power = g3.add_mutually_exclusive_group()
136
+ power.add_argument("--on", dest="on", action="store_true", default=None)
137
+ power.add_argument("--off", dest="on", action="store_false")
138
+ g3.add_argument("--mode", choices=[m.value for m in FireMode])
139
+ g3.add_argument("--temp", type=float)
140
+
141
+ args = parser.parse_args()
142
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.WARNING)
143
+ try:
144
+ asyncio.run(_run(args))
145
+ except EsceaError as err:
146
+ print(f"error: {err}", file=sys.stderr)
147
+ sys.exit(1)
148
+
149
+
150
+ if __name__ == "__main__":
151
+ main()
aioescea/discovery.py ADDED
@@ -0,0 +1,66 @@
1
+ """Find fireplaces on the LAN by broadcast."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass
7
+ import logging
8
+
9
+ from .exceptions import EsceaProtocolError
10
+ from .protocol import Command, decode_identity
11
+ from .transport import BROADCAST_ADDRESS, EsceaTransport
12
+
13
+ _LOGGER = logging.getLogger(__name__)
14
+
15
+ #: First three bytes of every Escea controller's MAC address. The last three
16
+ #: come from the fire's RF remote address. (Escea network summary, 2016.)
17
+ MAC_PREFIX = "AC:DE:48"
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class DiscoveredFireplace:
22
+ """A fireplace that answered SEARCH_FOR_FIRES."""
23
+
24
+ host: str
25
+ serial: int
26
+ pin: int
27
+
28
+
29
+ async def async_discover(
30
+ transport: EsceaTransport,
31
+ broadcast_addresses: Iterable[str] = (BROADCAST_ADDRESS,),
32
+ *,
33
+ timeout: float = 5.0,
34
+ ) -> list[DiscoveredFireplace]:
35
+ """Broadcast SEARCH_FOR_FIRES and return every fireplace that answers.
36
+
37
+ Pass the broadcast address of each network interface (for example
38
+ ``192.168.1.255``) to search more than the default route's network.
39
+ """
40
+ found: dict[int, DiscoveredFireplace] = {}
41
+ for host, frame in await transport.broadcast(
42
+ Command.SEARCH_FOR_FIRES, broadcast_addresses, timeout=timeout
43
+ ):
44
+ try:
45
+ identity = decode_identity(frame)
46
+ except EsceaProtocolError as err:
47
+ _LOGGER.debug("Bad discovery reply from %s: %s", host, err)
48
+ continue
49
+ found[identity.serial] = DiscoveredFireplace(
50
+ host=host, serial=identity.serial, pin=identity.pin
51
+ )
52
+ return list(found.values())
53
+
54
+
55
+ async def async_find(
56
+ transport: EsceaTransport,
57
+ serial: int,
58
+ broadcast_addresses: Iterable[str] = (BROADCAST_ADDRESS,),
59
+ *,
60
+ timeout: float = 5.0,
61
+ ) -> DiscoveredFireplace | None:
62
+ """Find one fireplace by serial number, for example after its IP changed."""
63
+ for fire in await async_discover(transport, broadcast_addresses, timeout=timeout):
64
+ if fire.serial == serial:
65
+ return fire
66
+ return None
aioescea/exceptions.py ADDED
@@ -0,0 +1,41 @@
1
+ """Exceptions raised by aioescea."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class EsceaError(Exception):
7
+ """Base class for every aioescea error."""
8
+
9
+
10
+ class EsceaProtocolError(EsceaError, ValueError):
11
+ """A frame did not match the wire format, or a value is out of range."""
12
+
13
+
14
+ class EsceaConnectionError(EsceaError):
15
+ """The fireplace could not be reached or did not answer in time."""
16
+
17
+
18
+ class EsceaPortInUseError(EsceaConnectionError):
19
+ """UDP port 3300 is already taken by another program on this host.
20
+
21
+ Fireplaces always reply to port 3300, so only one program per host can
22
+ talk to them reliably.
23
+ """
24
+
25
+
26
+ class EsceaBusyError(EsceaError):
27
+ """The fire is lighting or shutting down and ignores commands for now."""
28
+
29
+ def __init__(self, remaining: float) -> None:
30
+ super().__init__(
31
+ f"the fire is lighting or shutting down; try again in {remaining:.0f} s"
32
+ )
33
+ self.remaining = remaining
34
+
35
+
36
+ class EsceaStateError(EsceaError):
37
+ """The command does not make sense in the fire's current state."""
38
+
39
+
40
+ class EsceaAuthError(EsceaError):
41
+ """The fireplace's web page rejected the login."""
aioescea/fireplace.py ADDED
@@ -0,0 +1,187 @@
1
+ """High-level control of one Escea fireplace over UDP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import StrEnum
7
+ import logging
8
+ import time
9
+
10
+ from .exceptions import EsceaBusyError, EsceaStateError
11
+ from .protocol import (
12
+ MAX_TEMPERATURE,
13
+ MIN_TEMPERATURE,
14
+ Command,
15
+ Status,
16
+ decode_status,
17
+ encode_set_temperature,
18
+ )
19
+ from .transport import EsceaTransport
20
+
21
+ _LOGGER = logging.getLogger(__name__)
22
+
23
+ #: After POWER_ON or POWER_OFF the fire ignores commands while it lights or
24
+ #: purges. Measured from the Escea remote by the pescea author.
25
+ POWER_CHANGE_BUSY_SECONDS = 66.0
26
+
27
+
28
+ class FireMode(StrEnum):
29
+ """How the fire runs while it is on.
30
+
31
+ The fire has two independent switches, flame effect and fan boost. Only
32
+ three combinations are useful, so they are offered as one choice.
33
+ """
34
+
35
+ #: Normal heating: both switches off.
36
+ NORMAL = "normal"
37
+ #: Fan boost on: maximum heat output.
38
+ BOOST = "boost"
39
+ #: Flame effect on: flames for looks, very little heat.
40
+ FLAME_EFFECT = "flame_effect"
41
+
42
+
43
+ def mode_from_status(status: Status) -> FireMode:
44
+ """Return the mode a status describes. Fan boost wins if both are on."""
45
+ if status.fan_boost:
46
+ return FireMode.BOOST
47
+ if status.flame_effect:
48
+ return FireMode.FLAME_EFFECT
49
+ return FireMode.NORMAL
50
+
51
+
52
+ @dataclass(frozen=True, slots=True)
53
+ class FireplaceState:
54
+ """A status reading plus what the library knows about the busy window."""
55
+
56
+ status: Status
57
+ busy_remaining: float
58
+
59
+ @property
60
+ def mode(self) -> FireMode:
61
+ """Return the running mode."""
62
+ return mode_from_status(self.status)
63
+
64
+
65
+ class EsceaFireplace:
66
+ """One fireplace on the LAN.
67
+
68
+ Every method sends exactly the commands it needs, when it is called, and
69
+ nothing else. There is no background loop and no buffered state, so a
70
+ missed reply can never cause an old command to be replayed later.
71
+ """
72
+
73
+ def __init__(
74
+ self,
75
+ host: str,
76
+ transport: EsceaTransport,
77
+ *,
78
+ serial: int | None = None,
79
+ ) -> None:
80
+ self._host = host
81
+ self._transport = transport
82
+ self.serial = serial
83
+ self._busy_until = 0.0
84
+ self._last_status: Status | None = None
85
+
86
+ @property
87
+ def host(self) -> str:
88
+ """Return the fireplace's IP address."""
89
+ return self._host
90
+
91
+ @host.setter
92
+ def host(self, host: str) -> None:
93
+ self._host = host
94
+
95
+ @property
96
+ def transport(self) -> EsceaTransport:
97
+ """Return the shared UDP transport."""
98
+ return self._transport
99
+
100
+ @property
101
+ def last_status(self) -> Status | None:
102
+ """Return the most recent status read, if any."""
103
+ return self._last_status
104
+
105
+ @property
106
+ def busy_remaining(self) -> float:
107
+ """Seconds left before the fire accepts commands after a power change."""
108
+ return max(0.0, self._busy_until - time.monotonic())
109
+
110
+ async def async_get_status(self) -> Status:
111
+ """Read the fire's live status."""
112
+ frame = await self._transport.request(self._host, Command.STATUS_PLEASE)
113
+ self._last_status = decode_status(frame)
114
+ return self._last_status
115
+
116
+ async def async_get_state(self) -> FireplaceState:
117
+ """Read the status and return it with the busy countdown."""
118
+ status = await self.async_get_status()
119
+ return FireplaceState(status=status, busy_remaining=self.busy_remaining)
120
+
121
+ def _check_ready(self) -> None:
122
+ remaining = self.busy_remaining
123
+ if remaining > 0:
124
+ raise EsceaBusyError(remaining)
125
+
126
+ async def _send(self, command: Command, frame: bytes | None = None) -> None:
127
+ _LOGGER.debug("Sending %s to %s", command.name, self._host)
128
+ await self._transport.request(self._host, command, frame)
129
+
130
+ async def async_turn_on(self) -> None:
131
+ """Light the fire. Does nothing if it is already on."""
132
+ self._check_ready()
133
+ status = await self.async_get_status()
134
+ if status.is_on:
135
+ return
136
+ await self._send(Command.POWER_ON)
137
+ self._busy_until = time.monotonic() + POWER_CHANGE_BUSY_SECONDS
138
+
139
+ async def async_turn_off(self) -> None:
140
+ """Turn the fire off.
141
+
142
+ Never refused, even while the fire is busy lighting: turning a gas
143
+ fire off must always be possible. If the fire is mid-ignition it may
144
+ only act on this once it is ready, so callers should read the status
145
+ again afterwards.
146
+ """
147
+ await self._send(Command.POWER_OFF)
148
+ self._busy_until = time.monotonic() + POWER_CHANGE_BUSY_SECONDS
149
+
150
+ async def async_set_temperature(self, temperature: float) -> None:
151
+ """Set the target room temperature (whole °C, 4 to 30)."""
152
+ self._check_ready()
153
+ degrees = round(temperature)
154
+ if not MIN_TEMPERATURE <= degrees <= MAX_TEMPERATURE:
155
+ raise EsceaStateError(
156
+ f"{temperature} °C is outside {MIN_TEMPERATURE}-{MAX_TEMPERATURE} °C"
157
+ )
158
+ await self._send(Command.NEW_SET_TEMP, encode_set_temperature(degrees))
159
+
160
+ async def async_set_mode(
161
+ self, mode: FireMode, *, allow_ignite: bool = False
162
+ ) -> None:
163
+ """Set normal, boost or flame effect.
164
+
165
+ On Escea fires, turning flame effect or fan boost on while the fire is
166
+ off also lights it. That is refused unless ``allow_ignite`` is True.
167
+ Only the switches that need to change are sent.
168
+ """
169
+ self._check_ready()
170
+ status = await self.async_get_status()
171
+ want_boost = mode is FireMode.BOOST
172
+ want_flame = mode is FireMode.FLAME_EFFECT
173
+ if not status.is_on and (want_boost or want_flame) and not allow_ignite:
174
+ raise EsceaStateError(
175
+ "the fire is off; turning on boost or flame effect would light it"
176
+ )
177
+ # Turn the unwanted switch off first so both are never on at once.
178
+ if status.fan_boost and not want_boost:
179
+ await self._send(Command.FAN_BOOST_OFF)
180
+ if status.flame_effect and not want_flame:
181
+ await self._send(Command.FLAME_EFFECT_OFF)
182
+ if want_boost and not status.fan_boost:
183
+ await self._send(Command.FAN_BOOST_ON)
184
+ if want_flame and not status.flame_effect:
185
+ await self._send(Command.FLAME_EFFECT_ON)
186
+ if not status.is_on and (want_boost or want_flame):
187
+ self._busy_until = time.monotonic() + POWER_CHANGE_BUSY_SECONDS