aermatic 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.
aermatic/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """aermatic — an independent, unofficial Python library and CLI to control
2
+ Godrej Aer Smart Matic BLE air fresheners.
3
+
4
+ Not affiliated with or endorsed by Godrej. "Godrej" and "Aer" are trademarks of
5
+ their respective owners. Provided for interoperability; use at your own risk.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ __version__ = "0.1.0"
10
+
11
+ from . import protocol # noqa: E402,F401
12
+ from .client import AerDevice, ScanResult, scan, with_retry # noqa: E402,F401
13
+ from .protocol import Status # noqa: E402,F401
14
+
15
+ __all__ = ["AerDevice", "ScanResult", "scan", "with_retry", "Status", "protocol", "__version__"]
aermatic/cli.py ADDED
@@ -0,0 +1,155 @@
1
+ """Command-line interface: ``aermatic <command> [DEVICE] [args]``.
2
+
3
+ DEVICE is an alias from your config (see ``aermatic.config``), a raw BLE address,
4
+ or ``all``. If an alias/address isn't given (or is ``all`` with no config), the CLI
5
+ scans by name and targets whatever it finds.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import asyncio
11
+ import sys
12
+
13
+ from . import __version__
14
+ from . import protocol as P
15
+ from .client import AerDevice, ScanResult, local_time_fields, scan, with_retry
16
+ from .config import load_aliases
17
+
18
+
19
+ def _print_status(address: str, st: P.Status | None) -> None:
20
+ print(f"\n[{address}]")
21
+ if st is None:
22
+ print(" !! no reply (try again; weak-signal units can time out)")
23
+ return
24
+ bv = f"{st.battery_volts:.3f} V" if st.battery_volts is not None else "?"
25
+ print(f" firmware : {st.firmware}")
26
+ print(f" battery : {bv}")
27
+ print(f" state : {st.current_state} (0 = idle)")
28
+ print(f" spray-now : 0s/10s/20s/40s = {st.spray_now}")
29
+ print(f" scheduled : {st.scheduled}")
30
+ print(f" button-press : {st.button_press}")
31
+ print(f" total sprays : {st.total_sprays} -> refill ~{st.refill_percent}% left")
32
+
33
+
34
+ async def _resolve(device: str | None) -> list[str]:
35
+ aliases = load_aliases()
36
+ if device and device.lower() != "all":
37
+ if device in aliases:
38
+ return [aliases[device]]
39
+ return [device] # assume raw address
40
+ if aliases: # "all" (or unspecified) with configured devices
41
+ return list(aliases.values())
42
+ # fall back to scanning
43
+ print("No device given/configured; scanning...", file=sys.stderr)
44
+ return [r.address for r in await scan()]
45
+
46
+
47
+ async def _run(args: argparse.Namespace) -> int:
48
+ cmd = args.command
49
+
50
+ if cmd == "scan":
51
+ results: list[ScanResult] = await scan(timeout=args.timeout)
52
+ if not results:
53
+ print("No Aer devices found.")
54
+ for r in results:
55
+ print(f" {r.address} rssi={r.rssi} name={r.name!r}")
56
+ return 0
57
+
58
+ addresses = await _resolve(getattr(args, "device", None))
59
+ if not addresses:
60
+ print("No target devices.", file=sys.stderr)
61
+ return 1
62
+
63
+ if cmd == "status":
64
+ for ad in addresses:
65
+ st = await with_retry(ad, lambda d: d.status())
66
+ _print_status(ad, st)
67
+ return 0
68
+
69
+ # single-target commands act on the first resolved address
70
+ ad = addresses[0]
71
+
72
+ async def act(action, label):
73
+ print(f"\n[{ad}] {label}")
74
+ reply = await with_retry(ad, action)
75
+ print(" reply:", reply if reply else "none")
76
+
77
+ if cmd == "spray":
78
+ await act(lambda d: d.spray(args.interval), f"spray interval={args.interval}")
79
+ elif cmd == "stop":
80
+ await act(lambda d: d.stop(), "stop")
81
+ elif cmd == "led":
82
+ await act(lambda d: d.led(), "led blink")
83
+ elif cmd == "settime":
84
+ eP, tZ, tD = local_time_fields()
85
+ await act(lambda d: d.set_time(), f"set-time eP={eP} tZ={tZ} tD={tD}")
86
+ elif cmd == "get-time":
87
+ await act(lambda d: d.get_time(), "get-time")
88
+ elif cmd == "get-uid":
89
+ await act(lambda d: d.get_uid(), "get-uid")
90
+ elif cmd == "refill":
91
+ await act(lambda d: d.refill_complete(), "refill-complete")
92
+ elif cmd == "schedules":
93
+ await act(lambda d: d.get_schedules(), "retrieve schedules")
94
+ elif cmd == "schedule":
95
+ await act(
96
+ lambda d: d.add_schedule(args.days, args.start, args.end, args.interval),
97
+ f"schedule {args.days} {args.start}->{args.end} every {args.interval}m",
98
+ )
99
+ elif cmd == "remove-schedules":
100
+ await act(lambda d: d.remove_schedules(), "remove ALL schedules")
101
+ else: # pragma: no cover
102
+ print(f"unknown command {cmd!r}", file=sys.stderr)
103
+ return 2
104
+ return 0
105
+
106
+
107
+ def build_parser() -> argparse.ArgumentParser:
108
+ p = argparse.ArgumentParser(prog="aermatic", description="Control Godrej Aer Smart Matic devices over BLE.")
109
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
110
+ sub = p.add_subparsers(dest="command", required=True)
111
+
112
+ sc = sub.add_parser("scan", help="discover devices")
113
+ sc.add_argument("--timeout", type=float, default=10.0)
114
+
115
+ def dev_arg(sp):
116
+ sp.add_argument("device", nargs="?", help="alias, address, or 'all'")
117
+
118
+ dev_arg(sub.add_parser("status", help="read status of DEVICE/all"))
119
+
120
+ sp = sub.add_parser("spray", help="spray now, or set auto interval")
121
+ dev_arg(sp)
122
+ sp.add_argument("interval", nargs="?", type=int, default=0, choices=P.VALID_INTERVALS,
123
+ help="0 (single) / 10 / 20 / 40 minutes")
124
+
125
+ for name, help_ in [
126
+ ("stop", "stop active spray/schedule"),
127
+ ("led", "blink the LED (no product used)"),
128
+ ("settime", "push this host's clock/timezone"),
129
+ ("get-time", "read device clock"),
130
+ ("get-uid", "read device unique id"),
131
+ ("refill", "mark the refill replaced (reset counter)"),
132
+ ("schedules", "read stored schedules"),
133
+ ("remove-schedules", "delete ALL schedules"),
134
+ ]:
135
+ dev_arg(sub.add_parser(name, help=help_))
136
+
137
+ scd = sub.add_parser("schedule", help="create a schedule")
138
+ dev_arg(scd)
139
+ scd.add_argument("days", help="mon,tue,... | all | weekdays | weekend")
140
+ scd.add_argument("start", help="HH:MM (24h)")
141
+ scd.add_argument("end", help="HH:MM (24h)")
142
+ scd.add_argument("interval", type=int, choices=(10, 20, 40), help="minutes")
143
+ return p
144
+
145
+
146
+ def main(argv: list[str] | None = None) -> int:
147
+ args = build_parser().parse_args(argv)
148
+ try:
149
+ return asyncio.run(_run(args))
150
+ except KeyboardInterrupt: # pragma: no cover
151
+ return 130
152
+
153
+
154
+ if __name__ == "__main__": # pragma: no cover
155
+ raise SystemExit(main())
aermatic/client.py ADDED
@@ -0,0 +1,177 @@
1
+ """Async BLE client for the Godrej Aer Smart Matic, built on `bleak`.
2
+
3
+ Cross-platform (macOS CoreBluetooth, Linux/BlueZ, Windows). The device pushes all
4
+ replies on the RESPONSE characteristic (``6e400001``), which has no CCCD. On macOS
5
+ you must still *attempt* to subscribe to it (the call errors, but that attempt is
6
+ what makes CoreBluetooth deliver the notifications); on Linux/BlueZ it subscribes
7
+ normally. We therefore attempt RESPONSE first and swallow errors, and also subscribe
8
+ to the CCCD-bearing characteristics as a backup.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import time
14
+ from dataclasses import dataclass
15
+
16
+ from bleak import BleakClient, BleakScanner
17
+
18
+ from . import protocol as P
19
+
20
+ # Attempt RESPONSE first (see module docstring), then the CCCD-bearing chars.
21
+ _SUBSCRIBE_ORDER = [P.RESPONSE, P.ACTION, P.PROVISION, P.SCHED]
22
+
23
+
24
+ @dataclass
25
+ class ScanResult:
26
+ address: str
27
+ name: str
28
+ rssi: int
29
+
30
+
31
+ async def scan(timeout: float = 10.0) -> list[ScanResult]:
32
+ """Discover Aer devices (advertised name contains 'matic')."""
33
+ out: dict[str, ScanResult] = {}
34
+ found = await BleakScanner.discover(timeout=timeout, return_adv=True)
35
+ for dev, adv in found.values():
36
+ name = adv.local_name or dev.name or ""
37
+ if P.ADV_NAME_MATCH in name.lower() and dev.address not in out:
38
+ out[dev.address] = ScanResult(dev.address, name, adv.rssi)
39
+ return list(out.values())
40
+
41
+
42
+ def local_time_fields() -> tuple[int, int, int]:
43
+ """(epoch_seconds, tz_offset_minutes_app_convention, dst_savings_ms) for this host."""
44
+ lt = time.localtime()
45
+ utc_off_min = (-time.altzone if lt.tm_isdst and time.daylight else -time.timezone) // 60
46
+ dst_ms = abs(time.timezone - time.altzone) * 1000 if lt.tm_isdst else 0
47
+ return int(time.time()), -utc_off_min, dst_ms
48
+
49
+
50
+ class AerDevice:
51
+ """A connected session to one device. Use as an async context manager.
52
+
53
+ Example::
54
+
55
+ async with AerDevice(address) as dev:
56
+ status = await dev.status()
57
+ print(status.firmware, status.refill_percent)
58
+ """
59
+
60
+ def __init__(self, address: str, connect_timeout: float = 20.0):
61
+ self.address = address
62
+ self._client = BleakClient(address, timeout=connect_timeout)
63
+ self._queue: asyncio.Queue[bytes] = asyncio.Queue()
64
+ self._subscribed: list[str] = []
65
+
66
+ async def __aenter__(self) -> "AerDevice":
67
+ await self.connect()
68
+ return self
69
+
70
+ async def __aexit__(self, *exc) -> None:
71
+ await self.disconnect()
72
+
73
+ async def connect(self) -> None:
74
+ await self._client.connect()
75
+ for uuid in _SUBSCRIBE_ORDER:
76
+ try:
77
+ await self._client.start_notify(uuid, self._on_notify)
78
+ self._subscribed.append(uuid)
79
+ except Exception:
80
+ pass # RESPONSE has no CCCD; attempting it still primes delivery on macOS
81
+
82
+ async def disconnect(self, settle: float = 0.3, wait_timeout: float = 5.0) -> None:
83
+ for uuid in self._subscribed:
84
+ try:
85
+ await self._client.stop_notify(uuid)
86
+ except Exception:
87
+ pass
88
+ self._subscribed.clear()
89
+ try:
90
+ await self._client.disconnect()
91
+ except Exception:
92
+ pass
93
+ # Wait for the link to actually drop (CoreBluetooth caches connections),
94
+ # so the device sees the disconnect and returns to idle promptly.
95
+ deadline = time.monotonic() + wait_timeout
96
+ while time.monotonic() < deadline:
97
+ try:
98
+ if not self._client.is_connected:
99
+ break
100
+ except Exception:
101
+ break
102
+ await asyncio.sleep(0.2)
103
+ await asyncio.sleep(settle)
104
+
105
+ def _on_notify(self, _char, data: bytearray) -> None:
106
+ self._queue.put_nowait(bytes(data))
107
+
108
+ async def _request(self, payload: bytes, want_mt: int | None, timeout: float) -> dict | None:
109
+ await self._client.write_gatt_char(P.ACTION, payload, response=False)
110
+ deadline = time.monotonic() + timeout
111
+ while time.monotonic() < deadline:
112
+ try:
113
+ data = await asyncio.wait_for(self._queue.get(), deadline - time.monotonic())
114
+ except asyncio.TimeoutError:
115
+ return None
116
+ try:
117
+ reply = P.decode_response(data)
118
+ except Exception:
119
+ continue
120
+ if want_mt is None or (isinstance(reply, dict) and reply.get("mT") == want_mt):
121
+ return reply
122
+ return None
123
+
124
+ # -- high-level commands (each returns the decoded reply dict, or None) --
125
+ async def status(self, timeout: float = 8.0) -> P.Status | None:
126
+ reply = await self._request(P.build_status(), P.MT_STATUS + 50, timeout)
127
+ return P.parse_status(reply) if reply else None
128
+
129
+ async def spray(self, interval: int = 0, timeout: float = 8.0) -> dict | None:
130
+ return await self._request(P.build_spray(interval), P.MT_SPRAY + 50, timeout)
131
+
132
+ async def stop(self, timeout: float = 8.0) -> dict | None:
133
+ return await self._request(P.build_stop(), P.MT_STOP + 50, timeout)
134
+
135
+ async def led(self, timeout: float = 8.0) -> dict | None:
136
+ return await self._request(P.build_led(), P.MT_TEST_LED + 50, timeout)
137
+
138
+ async def set_time(self, timeout: float = 8.0) -> dict | None:
139
+ eP, tZ, tD = local_time_fields()
140
+ return await self._request(P.build_set_time(eP, tZ, tD), P.MT_SET_TIME + 50, timeout)
141
+
142
+ async def get_time(self, timeout: float = 8.0) -> dict | None:
143
+ return await self._request(P.build_get_time(), P.MT_GET_TIME + 50, timeout)
144
+
145
+ async def refill_complete(self, timeout: float = 8.0) -> dict | None:
146
+ return await self._request(P.build_refill(), P.MT_REFILL + 50, timeout)
147
+
148
+ async def get_uid(self, timeout: float = 8.0) -> dict | None:
149
+ return await self._request(P.build_get_uid(), P.MT_GET_UID + 50, timeout)
150
+
151
+ async def add_schedule(self, days: str, start: str, end: str, interval: int,
152
+ timeout: float = 8.0) -> dict | None:
153
+ payload = P.build_schedule(days, start, end, interval)
154
+ return await self._request(payload, P.MT_SCHEDULE + 50, timeout)
155
+
156
+ async def get_schedules(self, timeout: float = 10.0) -> dict | None:
157
+ return await self._request(P.build_retrieve_schedules(), P.MT_RETRIEVE_SCHED + 50, timeout)
158
+
159
+ async def remove_schedules(self, timeout: float = 8.0) -> dict | None:
160
+ return await self._request(P.build_remove_schedules(), P.MT_REMOVE_SCHED + 50, timeout)
161
+
162
+
163
+ async def with_retry(address: str, action, tries: int = 3, backoff: float = 1.0):
164
+ """Connect and run ``action(dev)`` with reconnect/retry; returns its result or None."""
165
+ last = None
166
+ for attempt in range(tries):
167
+ try:
168
+ async with AerDevice(address) as dev:
169
+ result = await action(dev)
170
+ if result is not None:
171
+ return result
172
+ except Exception as exc: # noqa: BLE001
173
+ last = exc
174
+ await asyncio.sleep(backoff)
175
+ if last:
176
+ raise last
177
+ return None
aermatic/config.py ADDED
@@ -0,0 +1,59 @@
1
+ """Optional, host-local device aliases so you can type ``1``/``2``/``all`` instead
2
+ of long addresses. Addresses are per-host (macOS uses CoreBluetooth UUIDs, Linux
3
+ uses MAC addresses), so this never ships with the package — it is read at runtime
4
+ from, in priority order:
5
+
6
+ 1. the ``AERMATIC_DEVICES`` env var, e.g. ``AERMATIC_DEVICES="1=AA:BB..,2=CC:DD.."``
7
+ 2. ``./aermatic-devices.toml`` in the current directory
8
+ 3. ``$XDG_CONFIG_HOME/aermatic/devices.toml`` (default ``~/.config/aermatic/devices.toml``)
9
+
10
+ TOML format::
11
+
12
+ [devices]
13
+ 1 = "AA:BB:CC:DD:EE:FF"
14
+ living-room = "11:22:33:44:55:66"
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from pathlib import Path
20
+
21
+ try: # Python 3.11+
22
+ import tomllib
23
+ except ModuleNotFoundError: # pragma: no cover
24
+ tomllib = None # type: ignore
25
+
26
+
27
+ def _from_env() -> dict[str, str]:
28
+ raw = os.environ.get("AERMATIC_DEVICES", "").strip()
29
+ out: dict[str, str] = {}
30
+ if raw:
31
+ for pair in raw.split(","):
32
+ if "=" in pair:
33
+ k, v = pair.split("=", 1)
34
+ out[k.strip()] = v.strip()
35
+ return out
36
+
37
+
38
+ def _from_toml(path: Path) -> dict[str, str]:
39
+ if tomllib is None or not path.is_file():
40
+ return {}
41
+ try:
42
+ data = tomllib.loads(path.read_text())
43
+ except Exception:
44
+ return {}
45
+ devices = data.get("devices", {})
46
+ return {str(k): str(v) for k, v in devices.items()}
47
+
48
+
49
+ def config_path() -> Path:
50
+ base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
51
+ return Path(base) / "aermatic" / "devices.toml"
52
+
53
+
54
+ def load_aliases() -> dict[str, str]:
55
+ """Merge alias sources (env wins, then CWD file, then user config)."""
56
+ aliases = _from_toml(config_path())
57
+ aliases.update(_from_toml(Path("aermatic-devices.toml")))
58
+ aliases.update(_from_env())
59
+ return aliases
aermatic/protocol.py ADDED
@@ -0,0 +1,245 @@
1
+ """Pure protocol layer for the Godrej Aer Smart Matic — no Bluetooth, no I/O.
2
+
3
+ Everything here is independently reimplemented from observed BLE behaviour for
4
+ interoperability. Commands are CBOR maps; the device echoes the message number
5
+ (``mN``) and adds ``ack: 200`` on success. See ``docs/PROTOCOL.md``.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import Iterable
11
+
12
+ import cbor2
13
+
14
+ # ---- GATT UUIDs ------------------------------------------------------------
15
+ SERVICE = "6e400000-b5a3-f393-e0a9-e50e24dcca9e"
16
+ RESPONSE = "6e400001-b5a3-f393-e0a9-e50e24dcca9e" # notify (no CCCD); device TX
17
+ PROVISION = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
18
+ ACTION = "6e400003-b5a3-f393-e0a9-e50e24dcca9e" # write commands here
19
+ SCHED = "6e400004-b5a3-f393-e0a9-e50e24dcca9e"
20
+
21
+ ADV_NAME_MATCH = "matic" # advertised name contains this
22
+ SPRAY_CAPACITY = 2200 # total sprays per full can (for refill %)
23
+ MAX_SCHEDULES = 10
24
+
25
+ # ---- message types (response = request + 50) -------------------------------
26
+ MT_SET_TIME = 102
27
+ MT_SCHEDULE = 103
28
+ MT_SPRAY = 104
29
+ MT_REFILL = 105
30
+ MT_STOP = 106
31
+ MT_STATUS = 107
32
+ MT_REMOVE_SCHED = 108
33
+ MT_RETRIEVE_SCHED = 109
34
+ MT_SET_UID = 110
35
+ MT_GET_UID = 111
36
+ MT_RESTART_SCHED = 112
37
+ MT_TEST_LED = 113
38
+ MT_GET_TIME = 114
39
+
40
+ DAY_BITS = {"sun": 1, "mon": 64, "tue": 32, "wed": 16, "thu": 8, "fri": 4, "sat": 2}
41
+ VALID_INTERVALS = (0, 10, 20, 40)
42
+
43
+ __all__ = [
44
+ "SERVICE", "RESPONSE", "PROVISION", "ACTION", "SCHED", "ADV_NAME_MATCH",
45
+ "SPRAY_CAPACITY", "MAX_SCHEDULES", "encode", "schedule_blob", "parse_days",
46
+ "Status", "decode_response", "refill_percent",
47
+ "build_status", "build_spray", "build_stop", "build_led", "build_set_time",
48
+ "build_get_time", "build_refill", "build_get_uid", "build_retrieve_schedules",
49
+ "build_schedule", "build_remove_schedules",
50
+ ]
51
+
52
+
53
+ # ---- minimal, deterministic CBOR encoder -----------------------------------
54
+ # Produces bytes identical to the official app, including the set-time quirk of
55
+ # forcing the epoch to an 8-byte (uint64) CBOR value.
56
+ def _uint(major: int, u: int) -> bytes:
57
+ if u < 24:
58
+ return bytes([major | u])
59
+ if u < 256:
60
+ return bytes([major | 24, u])
61
+ if u < 65536:
62
+ return bytes([major | 25]) + u.to_bytes(2, "big")
63
+ if u < 2**32:
64
+ return bytes([major | 26]) + u.to_bytes(4, "big")
65
+ return bytes([major | 27]) + u.to_bytes(8, "big")
66
+
67
+
68
+ def _int(v: int, force_u64: bool = False) -> bytes:
69
+ if force_u64:
70
+ return bytes([0x1B]) + int(v).to_bytes(8, "big")
71
+ if v >= 0:
72
+ return _uint(0x00, v)
73
+ return _uint(0x20, -1 - v)
74
+
75
+
76
+ def _value(v, force_u64: bool = False) -> bytes:
77
+ if isinstance(v, bool):
78
+ return b"\xf5" if v else b"\xf4"
79
+ if isinstance(v, int):
80
+ return _int(v, force_u64)
81
+ if isinstance(v, (bytes, bytearray)):
82
+ return _uint(0x40, len(v)) + bytes(v)
83
+ if isinstance(v, list):
84
+ out = _uint(0x80, len(v))
85
+ for e in v:
86
+ out += _value(e)
87
+ return out
88
+ if isinstance(v, dict):
89
+ out = _uint(0xA0, len(v))
90
+ for k, x in v.items():
91
+ out += _uint(0x60, len(k.encode())) + k.encode() + _value(x)
92
+ return out
93
+ raise TypeError(f"unsupported CBOR value: {type(v)!r}")
94
+
95
+
96
+ def encode(fields: dict, force_u64: Iterable[str] = ()) -> bytes:
97
+ """Encode an ordered mapping of ``{str: value}`` to a definite-length CBOR map."""
98
+ force = set(force_u64)
99
+ out = _uint(0xA0, len(fields))
100
+ for k, v in fields.items():
101
+ out += _uint(0x60, len(k.encode())) + k.encode() + _value(v, k in force)
102
+ return out
103
+
104
+
105
+ # ---- command builders ------------------------------------------------------
106
+ def build_status(mn: int = 157) -> bytes:
107
+ return encode({"mT": MT_STATUS, "mN": mn})
108
+
109
+
110
+ def build_spray(interval: int = 0, mn: int = 154) -> bytes:
111
+ if interval not in VALID_INTERVALS:
112
+ raise ValueError(f"interval must be one of {VALID_INTERVALS}")
113
+ return encode({"mT": MT_SPRAY, "mN": mn, "rI": interval})
114
+
115
+
116
+ def build_stop(mn: int = 156) -> bytes:
117
+ return encode({"mT": MT_STOP, "mN": mn, "sS": True})
118
+
119
+
120
+ def build_led(mn: int = 163) -> bytes:
121
+ return encode({"mT": MT_TEST_LED, "mN": mn})
122
+
123
+
124
+ def build_set_time(epoch: int, tz_offset_min: int, dst_ms: int = 0, mn: int = 152) -> bytes:
125
+ # eP must be an 8-byte uint64 (firmware reads a fixed-width field).
126
+ return encode(
127
+ {"mT": MT_SET_TIME, "mN": mn, "eP": int(epoch), "tZ": int(tz_offset_min), "tD": int(dst_ms)},
128
+ force_u64=("eP",),
129
+ )
130
+
131
+
132
+ def build_get_time(mn: int = 164) -> bytes:
133
+ return encode({"mT": MT_GET_TIME, "mN": mn})
134
+
135
+
136
+ def build_refill(mn: int = 155) -> bytes:
137
+ return encode({"mT": MT_REFILL, "mN": mn, "rR": True})
138
+
139
+
140
+ def build_get_uid(mn: int = 161) -> bytes:
141
+ return encode({"mT": MT_GET_UID, "mN": mn})
142
+
143
+
144
+ def build_retrieve_schedules(mn: int = 159) -> bytes:
145
+ return encode({"mT": MT_RETRIEVE_SCHED, "mN": mn})
146
+
147
+
148
+ def build_remove_schedules(mn: int = 158) -> bytes:
149
+ return encode({"mT": MT_REMOVE_SCHED, "mN": mn})
150
+
151
+
152
+ def parse_days(spec: str) -> tuple[int, list[str]]:
153
+ """Parse a day spec -> (weekday bitmask, normalised names).
154
+
155
+ Accepts ``all``/``daily``, ``weekdays``, ``weekend``, or comma names
156
+ (``mon,tue,...``).
157
+ """
158
+ s = spec.strip().lower()
159
+ if s in ("all", "everyday", "daily"):
160
+ names = list(DAY_BITS)
161
+ elif s in ("weekday", "weekdays", "week"):
162
+ names = ["mon", "tue", "wed", "thu", "fri"]
163
+ elif s in ("weekend", "weekends"):
164
+ names = ["sat", "sun"]
165
+ else:
166
+ names = [p.strip()[:3] for p in s.replace(" ", ",").split(",") if p.strip()]
167
+ bits = 0
168
+ for n in names:
169
+ if n not in DAY_BITS:
170
+ raise ValueError(f"bad day {n!r} (use mon..sun / all / weekdays / weekend)")
171
+ bits |= DAY_BITS[n]
172
+ return bits, names
173
+
174
+
175
+ def schedule_blob(days: str, start: str, end: str, interval: int) -> bytes:
176
+ """Build the 5-byte schedule descriptor: [weekdays, startH, startM, repeat, interval]."""
177
+ if interval not in (10, 20, 40):
178
+ raise ValueError("interval must be 10, 20 or 40 minutes")
179
+ bits, _ = parse_days(days)
180
+ sh, sm = (int(x) for x in start.split(":"))
181
+ eh, em = (int(x) for x in end.split(":"))
182
+ start_min, end_min = sh * 60 + sm, eh * 60 + em
183
+ if end_min <= start_min:
184
+ raise ValueError("end time must be after start time")
185
+ repeat = (end_min - start_min) // interval
186
+ if repeat <= 0:
187
+ raise ValueError("interval too large for the time window")
188
+ return bytes([bits & 0xFF, sh, sm, repeat & 0xFF, interval])
189
+
190
+
191
+ def build_schedule(days: str, start: str, end: str, interval: int, mn: int = 160) -> bytes:
192
+ blob = schedule_blob(days, start, end, interval)
193
+ return encode({"mT": MT_SCHEDULE, "mN": mn, "S": [{"s": blob}]})
194
+
195
+
196
+ # ---- response decoding -----------------------------------------------------
197
+ def refill_percent(total_sprays: int) -> int:
198
+ return round((SPRAY_CAPACITY - min(total_sprays, SPRAY_CAPACITY)) / SPRAY_CAPACITY * 100)
199
+
200
+
201
+ @dataclass
202
+ class Status:
203
+ raw: dict = field(repr=False)
204
+ message_type: int | None = None
205
+ ack: int | None = None
206
+ battery_mv: int | None = None
207
+ firmware: str | None = None
208
+ current_state: int | None = None
209
+ spray_now: list[int] = field(default_factory=list) # counts @ 0/10/20/40
210
+ scheduled: list[int] = field(default_factory=list) # counts @ 10/20/40
211
+ button_press: list[int] = field(default_factory=list) # counts @ 10/20/40
212
+ structure_version: str | None = None
213
+
214
+ @property
215
+ def battery_volts(self) -> float | None:
216
+ return None if self.battery_mv is None else self.battery_mv / 1000.0
217
+
218
+ @property
219
+ def total_sprays(self) -> int:
220
+ return sum(self.spray_now) + sum(self.scheduled) + sum(self.button_press)
221
+
222
+ @property
223
+ def refill_percent(self) -> int:
224
+ return refill_percent(self.total_sprays)
225
+
226
+
227
+ def decode_response(data: bytes) -> dict:
228
+ """Decode a raw notification payload into a plain dict (CBOR map)."""
229
+ return cbor2.loads(bytes(data))
230
+
231
+
232
+ def parse_status(reply: dict) -> Status:
233
+ sc = reply.get("sC", {}) or {}
234
+ return Status(
235
+ raw=reply,
236
+ message_type=reply.get("mT"),
237
+ ack=reply.get("ack"),
238
+ battery_mv=reply.get("bV"),
239
+ firmware=reply.get("fV"),
240
+ current_state=reply.get("cS"),
241
+ spray_now=list(sc.get("sn", [])),
242
+ scheduled=list(sc.get("sc", [])),
243
+ button_press=list(sc.get("bn", [])),
244
+ structure_version=reply.get("sV"),
245
+ )
@@ -0,0 +1,291 @@
1
+ Metadata-Version: 2.5
2
+ Name: aermatic
3
+ Version: 0.1.0
4
+ Summary: Independent Python library and CLI to control Godrej Aer Smart Matic BLE air fresheners
5
+ Project-URL: Homepage, https://github.com/stacknix/aermatic
6
+ Project-URL: Repository, https://github.com/stacknix/aermatic
7
+ Project-URL: Issues, https://github.com/stacknix/aermatic/issues
8
+ Project-URL: Documentation, https://github.com/stacknix/aermatic/blob/main/docs/PROTOCOL.md
9
+ Author: stacknix
10
+ License: MIT License
11
+
12
+ Copyright (c) 2026 stacknix
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ License-File: LICENSE
32
+ Keywords: aer,air-freshener,ble,bleak,bluetooth,godrej,home-automation,iot,smart-matic
33
+ Classifier: Development Status :: 4 - Beta
34
+ Classifier: Environment :: Console
35
+ Classifier: Intended Audience :: Developers
36
+ Classifier: License :: OSI Approved :: MIT License
37
+ Classifier: Operating System :: OS Independent
38
+ Classifier: Programming Language :: Python :: 3
39
+ Classifier: Programming Language :: Python :: 3 :: Only
40
+ Classifier: Topic :: Home Automation
41
+ Classifier: Topic :: System :: Hardware
42
+ Requires-Python: >=3.9
43
+ Requires-Dist: bleak>=0.21
44
+ Requires-Dist: cbor2>=5.4
45
+ Provides-Extra: dev
46
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
47
+ Requires-Dist: pytest>=7; extra == 'dev'
48
+ Description-Content-Type: text/markdown
49
+
50
+ # aermatic
51
+
52
+ An independent, open-source Python library and command-line tool to control
53
+ **Godrej Aer Smart Matic** Bluetooth Low Energy (BLE) air fresheners directly —
54
+ no phone app, no account, no cloud. Works on macOS, Linux (including Raspberry
55
+ Pi), and Windows.
56
+
57
+ > **Unofficial.** Not affiliated with or endorsed by Godrej. "Godrej" and "Aer"
58
+ > are trademarks of their respective owners. This project was built independently
59
+ > for interoperability with devices you own. Use at your own risk.
60
+
61
+ ---
62
+
63
+ ## What it can do
64
+
65
+ - **Discover** nearby Smart Matic devices
66
+ - **Read status** — firmware, battery voltage, spray counts, refill % remaining
67
+ - **Spray now**, or set an **auto-spray interval** (every 10 / 20 / 40 min)
68
+ - **Stop** an active spray/schedule
69
+ - **Create / read / delete schedules** (per-weekday, start/end time, interval)
70
+ - **Set the device clock**, blink the **LED**, mark a **refill** as replaced
71
+
72
+ Everything runs locally over BLE. No internet connection is used.
73
+
74
+ ---
75
+
76
+ ## Requirements
77
+
78
+ - Python **3.9+**
79
+ - A machine with **Bluetooth LE** (any modern laptop, or a Raspberry Pi 3/4/5 / Zero 2 W)
80
+ - The devices must be **in Bluetooth range**
81
+
82
+ Platform notes:
83
+
84
+ - **macOS** — grant your terminal app Bluetooth permission the first time
85
+ (System Settings → Privacy & Security → Bluetooth).
86
+ - **Linux / Raspberry Pi** — uses BlueZ (preinstalled on Raspberry Pi OS). If scanning
87
+ needs elevated privileges, either run with `sudo` or grant the Python binary the
88
+ capability: `sudo setcap 'cap_net_raw,cap_net_admin+eip' $(readlink -f $(which python3))`.
89
+
90
+ ---
91
+
92
+ ## Install
93
+
94
+ ```bash
95
+ pip install aermatic
96
+ ```
97
+
98
+ That's it — this pulls in `bleak` (cross-platform BLE) and `cbor2`. A console
99
+ command `aermatic` is installed.
100
+
101
+ <details>
102
+ <summary>Install from source (for development)</summary>
103
+
104
+ ```bash
105
+ git clone https://github.com/stacknix/aermatic
106
+ cd aermatic
107
+ python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
108
+ pip install -e ".[dev]"
109
+ ```
110
+ </details>
111
+
112
+ ---
113
+
114
+ ## Quick start
115
+
116
+ **1. Find your devices:**
117
+
118
+ ```bash
119
+ aermatic scan
120
+ ```
121
+
122
+ ```
123
+ AA:BB:CC:DD:EE:FF rssi=-65 name='Smart Matic'
124
+ 11:22:33:44:55:66 rssi=-70 name='Smart Matic'
125
+ ```
126
+
127
+ (On macOS the address is a CoreBluetooth UUID like `1A2B3C4D-...`; on Linux it's a
128
+ MAC address like `AA:BB:CC:DD:EE:FF`. Both work the same way below.)
129
+
130
+ **2. Read status** (pass the address you saw):
131
+
132
+ ```bash
133
+ aermatic status AA:BB:CC:DD:EE:FF
134
+ ```
135
+
136
+ ```
137
+ [AA:BB:CC:DD:EE:FF]
138
+ firmware : 3.0.8-IN
139
+ battery : 3.005 V
140
+ state : 0 (0 = idle)
141
+ spray-now : 0s/10s/20s/40s = [34, 126, 0, 0]
142
+ scheduled : [0, 0, 0]
143
+ button-press : [57, 31, 27]
144
+ total sprays : 275 -> refill ~88% left
145
+ ```
146
+
147
+ **3. Spray once:**
148
+
149
+ ```bash
150
+ aermatic spray AA:BB:CC:DD:EE:FF
151
+ ```
152
+
153
+ ---
154
+
155
+ ## Device aliases (type `1` / `2` / `all` instead of addresses)
156
+
157
+ Addresses are long and differ per computer. Define short aliases once and reuse them.
158
+
159
+ Create `~/.config/aermatic/devices.toml` (or `aermatic-devices.toml` in your working
160
+ directory):
161
+
162
+ ```toml
163
+ [devices]
164
+ 1 = "AA:BB:CC:DD:EE:FF"
165
+ 2 = "11:22:33:44:55:66"
166
+ bedroom = "22:33:44:55:66:77"
167
+ ```
168
+
169
+ Now:
170
+
171
+ ```bash
172
+ aermatic status all # every configured device
173
+ aermatic status 1 # just device 1
174
+ aermatic spray bedroom
175
+ ```
176
+
177
+ Or set them inline without a file:
178
+
179
+ ```bash
180
+ export AERMATIC_DEVICES="1=AA:BB:CC:DD:EE:FF,2=11:22:33:44:55:66"
181
+ aermatic status all
182
+ ```
183
+
184
+ If you run a command with no device and have none configured, `aermatic` scans and
185
+ targets whatever it finds.
186
+
187
+ ---
188
+
189
+ ## Command reference
190
+
191
+ | Command | Example | Description |
192
+ |---|---|---|
193
+ | `scan` | `aermatic scan` | List nearby devices |
194
+ | `status` | `aermatic status all` | Firmware, battery, counts, refill % |
195
+ | `spray` | `aermatic spray 1` / `aermatic spray 1 20` | Spray once, or auto every 10/20/40 min |
196
+ | `stop` | `aermatic stop 1` | Stop active spray/schedule |
197
+ | `led` | `aermatic led 1` | Blink the LED (handy to identify a unit) |
198
+ | `settime` | `aermatic settime all` | Push your computer's clock + timezone |
199
+ | `get-time` | `aermatic get-time 1` | Read the device clock |
200
+ | `refill` | `aermatic refill 1` | Mark the can replaced (reset counter) |
201
+ | `schedules` | `aermatic schedules 1` | Read stored schedules |
202
+ | `schedule` | `aermatic schedule 1 weekdays 08:00 22:00 20` | Create a schedule |
203
+ | `remove-schedules` | `aermatic remove-schedules 1` | Delete **all** schedules |
204
+
205
+ **Scheduling:** `aermatic schedule DEVICE DAYS START END INTERVAL`
206
+ - `DAYS` — `mon,tue,wed` or `all` / `weekdays` / `weekend`
207
+ - `START` / `END` — `HH:MM` (24-hour)
208
+ - `INTERVAL` — `10`, `20` or `40` minutes
209
+
210
+ Example — spray every 20 minutes, 8am–10pm, Monday to Friday:
211
+
212
+ ```bash
213
+ aermatic schedule 1 weekdays 08:00 22:00 20
214
+ ```
215
+
216
+ ---
217
+
218
+ ## Use it as a library
219
+
220
+ ```python
221
+ import asyncio
222
+ from aermatic import AerDevice, scan
223
+
224
+ async def main():
225
+ # discover
226
+ for d in await scan():
227
+ print(d.address, d.name, d.rssi)
228
+
229
+ # connect and control
230
+ async with AerDevice("AA:BB:CC:DD:EE:FF") as dev:
231
+ status = await dev.status()
232
+ print(status.firmware, status.battery_volts, f"{status.refill_percent}% left")
233
+
234
+ await dev.spray() # spray once
235
+ await dev.add_schedule("weekdays", "08:00", "22:00", 20)
236
+
237
+ asyncio.run(main())
238
+ ```
239
+
240
+ The reply objects are plain dicts (`{'mT': 154, 'mN': 154, 'ack': 200}`); `ack == 200`
241
+ means success. `status()` returns a typed `Status` with `.firmware`, `.battery_volts`,
242
+ `.total_sprays`, `.refill_percent`, etc.
243
+
244
+ ---
245
+
246
+ ## How it works / protocol
247
+
248
+ The device exposes a Nordic-UART-style GATT service. Commands are small CBOR maps
249
+ written to a characteristic; the device replies with a notification. The full
250
+ reverse-engineered protocol — UUIDs, message types, CBOR fields, status layout,
251
+ schedule format — is documented in **[docs/PROTOCOL.md](docs/PROTOCOL.md)**.
252
+
253
+ One portability detail handled for you: the device's reply characteristic has no
254
+ CCCD descriptor, so macOS CoreBluetooth needs a specific subscribe sequence to
255
+ receive notifications. `aermatic` does this automatically.
256
+
257
+ ---
258
+
259
+ ## Troubleshooting
260
+
261
+ - **No devices in `scan`** — make sure Bluetooth is on and a device is in range;
262
+ on macOS grant the terminal Bluetooth permission; on Linux check `bluetoothctl`
263
+ sees adapters.
264
+ - **Connects but no reply / times out** — weak signal units occasionally time out;
265
+ just retry (the CLI already retries 3×). Move closer if persistent.
266
+ - **`BleakError: ... attribute could not be found`** — harmless on macOS; it's the
267
+ expected error from the reply characteristic and is swallowed internally.
268
+
269
+ ---
270
+
271
+ ## Firmware updates (OTA)
272
+
273
+ The devices support Telink OTA, but this library deliberately does **not** flash
274
+ firmware: there is no public newer image, and a bad flash can brick the unit. See
275
+ `docs/PROTOCOL.md` for the OTA details if you want to build this yourself.
276
+
277
+ ---
278
+
279
+ ## Contributing
280
+
281
+ Issues and PRs welcome — especially test reports from different devices, firmware
282
+ versions, and platforms. Run the (hardware-free) tests with:
283
+
284
+ ```bash
285
+ pip install -e ".[dev]"
286
+ pytest
287
+ ```
288
+
289
+ ## License
290
+
291
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,10 @@
1
+ aermatic/__init__.py,sha256=bYuG5M_62J1hkdtkuUWp8umt57VaLJ4AxotVzH8_g2g,609
2
+ aermatic/cli.py,sha256=jlobxfAT9CiRrOsylp-PRJAolW8MPPWrQK95KUs-xSk,5782
3
+ aermatic/client.py,sha256=-KZDG1vImkMSqozrIOKiCY5qLqTMqirCX2gKtYyBW7I,7123
4
+ aermatic/config.py,sha256=n60bXwt24hYtvdMPWDU_uLWmRR-Act1BMxeV74NXuD0,1829
5
+ aermatic/protocol.py,sha256=TYVyGDhSeWUD-QhZlSsjRaMYNqjeZMI6e0JTDNocGEs,8476
6
+ aermatic-0.1.0.dist-info/METADATA,sha256=AbMwFRgYJD54gVGLm9nj4OTt2DlK7-omvSERmTIYWF8,9528
7
+ aermatic-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ aermatic-0.1.0.dist-info/entry_points.txt,sha256=_X9tKgLHQWtbUSxEOxiDA_GgN6cxNfg0t30Gfg-L14Y,47
9
+ aermatic-0.1.0.dist-info/licenses/LICENSE,sha256=K4rLv-Y8hktPOzYEUF0vS7MRwFzX0joShkj7NbjIedg,1065
10
+ aermatic-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ aermatic = aermatic.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 stacknix
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.