asf02 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.
asf02/__init__.py ADDED
@@ -0,0 +1,45 @@
1
+ """ASF02 — Python client library for Lulumiao pet slow feeders (OEM model ASF02, sold as CWH01L-A1; BLE JSON-RPC).
2
+
3
+ Talks the JSON-RPC-over-GATT protocol used by the ASF02 pet feeder family:
4
+ connect, bind/unlock, schedule management, on-demand feeding, and status.
5
+
6
+ Requires `bleak` for BLE. No other runtime dependencies.
7
+ """
8
+ from asf02.client import ASF02Client, ASF02Error, ASF02ProtocolError, ASF02LockedError
9
+ from asf02.protocol import (
10
+ SERVICE_UUID,
11
+ WRITE_CHAR_UUID,
12
+ NOTIFY_CHAR_UUID,
13
+ decode_advertisement,
14
+ encode_plan_entry,
15
+ decode_plan_entry,
16
+ plan_entry_valid,
17
+ unlock_code_for,
18
+ generate_token,
19
+ decode_plan_slot,
20
+ is_clear_marker,
21
+ PlanEntry,
22
+ )
23
+ from asf02.discovery import discover_feeders
24
+
25
+ __version__ = "0.1.0"
26
+
27
+ __all__ = [
28
+ "ASF02Client",
29
+ "ASF02Error",
30
+ "ASF02ProtocolError",
31
+ "ASF02LockedError",
32
+ "SERVICE_UUID",
33
+ "WRITE_CHAR_UUID",
34
+ "NOTIFY_CHAR_UUID",
35
+ "decode_advertisement",
36
+ "encode_plan_entry",
37
+ "decode_plan_entry",
38
+ "decode_plan_slot",
39
+ "plan_entry_valid",
40
+ "is_clear_marker",
41
+ "unlock_code_for",
42
+ "generate_token",
43
+ "PlanEntry",
44
+ "discover_feeders",
45
+ ]
asf02/client.py ADDED
@@ -0,0 +1,311 @@
1
+ """ASF02 device client: connect, unlock, and the JSON-RPC command set.
2
+
3
+ Built on `bleak`. All command methods are transient-connection friendly:
4
+ connect, do the work, disconnect — the feeders run autonomously between
5
+ visits (mirrors the vendor app's usage pattern).
6
+
7
+ Key protocol behaviors (live-verified against a real unit):
8
+ - The device is locked across every (re)connect; only ``info`` works while
9
+ locked. ``connect_unlocked()`` performs the unlock dance.
10
+ - ``time.calibration`` takes epoch SECONDS and a tz offset in SECONDS
11
+ (e.g. -25200 for PDT, DST included).
12
+ - Plan writes must use the full 10-slot array form; the write *response* is
13
+ the authoritative confirmation (reads are unreliable on some firmware).
14
+ - ``feeder.plan`` reads require a ``p`` field (e.g. ``""``); omitting it
15
+ yields device silence.
16
+ - ``feeder.log`` may return no notification at all — callers get ``None``.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import contextlib
22
+ import json
23
+ import time
24
+ from typing import Any, Iterable, Sequence
25
+
26
+ from bleak import BleakClient
27
+
28
+ from .protocol import (
29
+ ASF02Error,
30
+ CCCD_UUID,
31
+ NOTIFY_CHAR_UUID,
32
+ SERVICE_UUID,
33
+ WRITE_CHAR_UUID,
34
+ decode_plan_slot,
35
+ encode_request,
36
+ generate_token,
37
+ parse_response,
38
+ unlock_code_for,
39
+ )
40
+
41
+
42
+ class ASF02ProtocolError(ASF02Error):
43
+ """Local protocol violation (bad frame shape, missing service, ...)."""
44
+
45
+
46
+ class ASF02LockedError(ASF02Error):
47
+ """The device refused a command because it is locked (code -31400)."""
48
+
49
+
50
+ def _wrap_errors(e: Exception) -> Exception:
51
+ if isinstance(e, ASF02Error):
52
+ if e.code == -31400:
53
+ return ASF02LockedError(e.code, e.message)
54
+ return e
55
+ return e
56
+
57
+
58
+ class ASF02Client:
59
+ """A single ASF02 feeder.
60
+
61
+ Example:
62
+ async with ASF02Client("<DEVICE_MAC>", token="<BIND_TOKEN>") as f:
63
+ info = await f.info()
64
+ await f.sync_time(tz_offset_seconds=-25200)
65
+ schedule = await f.get_schedule()
66
+ await f.set_schedule([(15, 30, 1), (16, 0, 1)])
67
+ await f.feed(1)
68
+ """
69
+
70
+ def __init__(self, address: str, token: str, *, response_timeout: float = 10.0,
71
+ post_connect_delay: float = 1.0):
72
+ self.address = address
73
+ self.token = token
74
+ self.response_timeout = response_timeout
75
+ self.post_connect_delay = post_connect_delay
76
+ self._client: BleakClient | None = None
77
+ self._req_id = 0
78
+ self._pending: dict[int, asyncio.Future] = {}
79
+ self._unlocked = False
80
+
81
+ # ------------------------------------------------------------------
82
+ # Connection lifecycle
83
+ # ------------------------------------------------------------------
84
+ async def __aenter__(self) -> "ASF02Client":
85
+ await self.connect()
86
+ return self
87
+
88
+ async def __aexit__(self, *exc) -> None:
89
+ await self.disconnect()
90
+
91
+ async def connect(self) -> None:
92
+ """Connect and enable notifications. Device is locked until unlock()."""
93
+ if self._client is not None:
94
+ return
95
+ client = BleakClient(self.address, timeout=20)
96
+ await client.connect()
97
+ await client.start_notify(NOTIFY_CHAR_UUID, self._on_notify)
98
+ # Give the controller a moment before the first command (matches the
99
+ # vendor app's connect-then-poll behavior and avoids early drops).
100
+ if self.post_connect_delay:
101
+ await asyncio.sleep(self.post_connect_delay)
102
+ self._client = client
103
+
104
+ async def disconnect(self) -> None:
105
+ client, self._client = self._client, None
106
+ self._unlocked = False
107
+ for fut in self._pending.values():
108
+ if not fut.done():
109
+ fut.cancel()
110
+ self._pending.clear()
111
+ if client is not None:
112
+ with contextlib.suppress(Exception):
113
+ await client.disconnect()
114
+
115
+ async def unlock(self) -> dict:
116
+ """Unlock the device using the configured token. Returns the device's
117
+ unlock result dict (contains device time ``t``, tz ``z``, ``l``, ``k``)."""
118
+ if self._client is None:
119
+ raise ASF02ProtocolError(0, "not connected")
120
+ result = await self._request("unlock", {"s": unlock_code_for(self.token)})
121
+ self._unlocked = True
122
+ return result
123
+
124
+ async def connect_unlocked(self) -> dict:
125
+ """connect() + unlock() in one step (the usual entry point)."""
126
+ await self.connect()
127
+ return await self.unlock()
128
+
129
+ @property
130
+ def connected(self) -> bool:
131
+ return self._client is not None
132
+
133
+ # ------------------------------------------------------------------
134
+ # Commands
135
+ # ------------------------------------------------------------------
136
+ async def info(self) -> dict:
137
+ """Device info (works even while locked): firmware ``f``, hw ``h``,
138
+ model ``m``, serial ``s``, timezone offset ``z`` (seconds)."""
139
+ return await self._request("info")
140
+
141
+ async def sync_time(self, tz_offset_seconds: int, *, epoch: int | None = None) -> dict:
142
+ """Calibrate the device clock.
143
+
144
+ ``tz_offset_seconds`` = total UTC offset **in seconds, including DST**
145
+ (e.g. -25200 for PDT, -28800 for PST — match the vendor app, which
146
+ sends ``(rawOffset + dstSavings) / 1000``). The device clock can drift
147
+ seconds a month, so sync as needed.
148
+ """
149
+ t = int(epoch if epoch is not None else time.time())
150
+ return await self._request("time.calibration", {"t": t, "z": tz_offset_seconds})
151
+
152
+ async def status(self) -> dict:
153
+ """Live status: ``s`` state, ``n``/``t`` total feed counter, ``b``
154
+ battery (units unconfirmed; <=410 = low per vendor app), ``u`` uptime-ish
155
+ counter, ``d`` (unknown, 0)."""
156
+ return await self._request("feeder.status")
157
+
158
+ async def feed(self, portions: int) -> Any:
159
+ """Dispense ``portions`` immediately (1-99, matching the vendor app's
160
+ picker). Returns ``True`` as a near-instant ACK — the dispense runs
161
+ ASYNCHRONOUSLY afterwards (s=1 while the motor runs; a single
162
+ feed(10) was observed to take ~50s). The device drops the GATT
163
+ connection during the feed, so do NOT poll status() while it runs:
164
+ disconnect, wait, reconnect, then read. The status ``n``/``t``
165
+ counters increment by ``portions`` (live-verified: feed(10) moved n
166
+ by +10, confirmed across three independent deltas)."""
167
+ if not isinstance(portions, int) or not 1 <= portions <= 99:
168
+ raise ValueError("portions must be an integer 1..99")
169
+ return await self._request("feeder.feed", {"n": portions})
170
+
171
+ async def stop(self) -> Any:
172
+ """Stop an in-progress feed (safe no-op when idle)."""
173
+ return await self._request("feeder.stop")
174
+
175
+ async def get_schedule(self) -> list:
176
+ """Read the schedule as a list of :class:`~asf02.protocol.PlanEntry`.
177
+
178
+ Returns the non-empty slots in device slot order. Returns an empty
179
+ list when the device stays silent (observed with an empty schedule on
180
+ some firmware) or reports only empty slots.
181
+ """
182
+ r = await self._request("feeder.plan", params_raw="", silent_ok=True)
183
+ slots = r.get("p") if isinstance(r, dict) else None
184
+ if not isinstance(slots, list):
185
+ return []
186
+ entries = [decode_plan_slot(s) for s in slots if isinstance(s, str)]
187
+ return [e for e in entries if e is not None]
188
+
189
+ async def set_schedule(self, entries: Iterable, *, clear: bool = False) -> list:
190
+ """Replace the entire schedule (device stores a fixed 10-slot array).
191
+
192
+ ``entries`` is an iterable of ``(hour, minute, portion)`` or
193
+ ``(hour, minute, portion, enabled)`` tuples, max 10. Use ``clear=True``
194
+ (or an empty iterable) to wipe the schedule.
195
+
196
+ Returns the full 10-slot array the device confirmed as stored —
197
+ this response is the authoritative confirmation.
198
+ """
199
+ entries = list(entries)
200
+ if clear:
201
+ payload = ["0000000000"] + [""] * 9
202
+ elif not entries:
203
+ payload = ["0000000000"] + [""] * 9
204
+ else:
205
+ if len(entries) > 10:
206
+ raise ValueError(f"too many schedule entries: {len(entries)} (max 10)")
207
+ from .protocol import encode_plan_entry
208
+
209
+ payload = [encode_plan_entry(h, m, w, on) for (h, m, w, *rest) in entries
210
+ for on in [bool(rest[0]) if rest else True]]
211
+ payload += [""] * (10 - len(payload))
212
+ r = await self._request("feeder.plan", params_raw=json.dumps(payload, separators=(",", ":")))
213
+ slots = r.get("p") if isinstance(r, dict) else None
214
+ return list(slots) if isinstance(slots, list) else []
215
+
216
+ async def get_log(self) -> list | None:
217
+ """Read feed history. Returns the device's ``d`` row list, or ``None``
218
+ when the device stays silent (common on some firmware/empty history)."""
219
+ r = await self._request("feeder.log", silent_ok=True)
220
+ if isinstance(r, dict) and "d" in r:
221
+ return r["d"]
222
+ return None
223
+
224
+ # ------------------------------------------------------------------
225
+ # Pairing
226
+ # ------------------------------------------------------------------
227
+ @staticmethod
228
+ def new_token() -> str:
229
+ """Generate a fresh bind token (10 chars, vendor charset)."""
230
+ return generate_token()
231
+
232
+ async def bind(self, token: str | None = None, *, home_id: str = "0",
233
+ tz_offset_seconds: int = 0) -> dict:
234
+ """(Re)bind the device to ``token`` — overwrites any previous token.
235
+ ``tz_offset_seconds`` = total UTC offset in seconds incl. DST (same
236
+ convention as :meth:`sync_time`). After this call the old token no
237
+ longer unlocks the device."""
238
+ tok = token if token is not None else self.token
239
+ return await self._request(
240
+ "bind", {"h": str(home_id), "d": "0000", "t": tok, "z": tz_offset_seconds}
241
+ )
242
+
243
+ # ------------------------------------------------------------------
244
+ # Core request/response machinery
245
+ # ------------------------------------------------------------------
246
+ async def _request(self, method: str, params: dict | None = None,
247
+ *, params_raw: str | None = None,
248
+ silent_ok: bool = False) -> Any:
249
+ """Send one command and await its response.
250
+
251
+ - ``params``: normal dict params (serialized compactly).
252
+ - ``params_raw``: raw JSON fragment for ``p`` (used for the plan
253
+ read/write quirks where the param shape matters exactly).
254
+ - ``silent_ok``: if True, a missing response returns ``None`` instead
255
+ of raising (used for feeder.log, which may stay silent).
256
+
257
+ Raises :class:`ASF02LockedError` / :class:`ASF02Error` on device
258
+ errors, ``asyncio.TimeoutError`
259
+ on silence (unless ``silent_ok``).
260
+ """
261
+ client = self._client
262
+ if client is None:
263
+ raise ASF02ProtocolError(0, "not connected")
264
+ self._req_id += 1
265
+ req_id = self._req_id
266
+ if params_raw is not None:
267
+ payload = f'{{"m":"{method}","i":{req_id},"p":{params_raw}}}'.encode("utf-8")
268
+ else:
269
+ payload = encode_request(method, req_id, params)
270
+
271
+ loop = asyncio.get_running_loop()
272
+ fut: asyncio.Future = loop.create_future()
273
+ self._pending[req_id] = fut
274
+ try:
275
+ # Register the future BEFORE writing: fast device replies (e.g.
276
+ # info) can arrive immediately and must not be dropped.
277
+ await client.write_gatt_char(WRITE_CHAR_UUID, payload, response=True)
278
+ try:
279
+ return await asyncio.wait_for(fut, self.response_timeout)
280
+ except asyncio.TimeoutError:
281
+ if silent_ok:
282
+ return None
283
+ raise
284
+ except ASF02Error as e:
285
+ raise _wrap_errors(e) from None
286
+
287
+ def _on_notify(self, _char: Any, data: bytearray) -> None:
288
+ raw = bytes(data)
289
+ try:
290
+ resp = parse_response(raw)
291
+ except ASF02Error as e:
292
+ fut = self._pending.pop(self._guess_id(raw), None)
293
+ if fut is not None and not fut.done():
294
+ fut.set_exception(_wrap_errors(e))
295
+ return
296
+ except ValueError:
297
+ return # non-JSON noise; ignore
298
+ fut = self._pending.pop(resp["i"], None)
299
+ if fut is None or fut.done():
300
+ return
301
+ if resp["ok"]:
302
+ fut.set_result(resp["r"])
303
+ else:
304
+ fut.set_exception(resp["error"])
305
+
306
+ @staticmethod
307
+ def _guess_id(raw: bytes) -> int:
308
+ """Best-effort id extraction from a malformed-error frame."""
309
+ with contextlib.suppress(Exception):
310
+ return int(json.loads(raw.decode("utf-8"))["i"])
311
+ return -1
asf02/discovery.py ADDED
@@ -0,0 +1,66 @@
1
+ """Discovery: scan for ASF02 feeders via bleak.
2
+
3
+ Uses the feeder's advertising record (name ``ASF02-<last6MAC>`` +
4
+ manufacturer data ``0203 ... <MAC>``). Company id 0xFFFF, type prefix 0203.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ from dataclasses import dataclass
10
+
11
+ from bleak import BleakScanner
12
+
13
+ from .protocol import ADV_COMPANY_ID, decode_advertisement
14
+
15
+
16
+ @dataclass
17
+ class DiscoveredFeeder:
18
+ address: str
19
+ name: str
20
+ model: str | None
21
+ mac: str
22
+ rssi: int
23
+ raw_manufacturer_data: str # hex
24
+
25
+
26
+ async def discover_feeders(timeout: float = 10.0, *, address_filter: str | None = None) -> list[DiscoveredFeeder]:
27
+ """Scan up to ``timeout`` seconds and return all feeders seen.
28
+
29
+ ``address_filter`` (a MAC like ``"AA:BB:CC:DD:EE:FF"``) limits results to
30
+ one device (useful when several feeders are nearby).
31
+ """
32
+ found: dict[str, DiscoveredFeeder] = {}
33
+
34
+ def on_adv(device, adv) -> None:
35
+ if address_filter and device.address != address_filter:
36
+ return
37
+ mfg = None
38
+ for cid, data in (adv.manufacturer_data or {}).items():
39
+ if cid == ADV_COMPANY_ID:
40
+ mfg = data
41
+ break
42
+ if mfg is None:
43
+ return
44
+ try:
45
+ decoded = decode_advertisement(mfg, local_name=adv.local_name or device.name)
46
+ except ValueError:
47
+ return
48
+ rec = found.setdefault(device.address, DiscoveredFeeder(
49
+ address=device.address,
50
+ name=device.name or "",
51
+ model=decoded.get("model"),
52
+ mac=decoded["mac"],
53
+ rssi=adv.rssi,
54
+ raw_manufacturer_data=mfg.hex(),
55
+ ))
56
+ rec.rssi = max(rec.rssi, adv.rssi)
57
+ if adv.local_name:
58
+ rec.name = adv.local_name
59
+
60
+ scanner = BleakScanner(on_adv)
61
+ await scanner.start()
62
+ try:
63
+ await asyncio.sleep(timeout)
64
+ finally:
65
+ await scanner.stop()
66
+ return sorted(found.values(), key=lambda f: f.rssi, reverse=True)
asf02/protocol.py ADDED
@@ -0,0 +1,221 @@
1
+ """ASF02 feeder wire protocol: constants, framing, and pure codecs.
2
+
3
+ Everything here is pure (no I/O, no asyncio) so it can be unit-tested against
4
+ captured wire traffic. Live-verified against a real ASF02 unit (firmware
5
+ 1.19.12).
6
+
7
+ Protocol summary
8
+ ----------------
9
+ JSON-RPC-ish messages over two GATT characteristics of service ``55535343-...``:
10
+
11
+ request (written, UTF-8): {"m":"<method>","i":<id>,"p":<params>}
12
+ response (notified, UTF-8): {"i":<id>,"r":<result>} or {"i":<id>,"e":{"c":<code>,"m":"<msg>"}}
13
+
14
+ Responses do NOT echo the method; matching is by ``i``. The device is locked
15
+ across every (re)connect; only ``info`` works while locked. ``feeder.log`` may
16
+ return no notification at all (treat timeout as empty).
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import secrets
22
+ import string
23
+ from dataclasses import dataclass
24
+
25
+ SERVICE_UUID = "55535343-fe7d-4ae5-8fa9-9fafd205e455"
26
+ WRITE_CHAR_UUID = "49535343-8841-43f4-a8d4-ecbe34729bb3"
27
+ NOTIFY_CHAR_UUID = "49535343-1e4d-4bd9-ba61-23c647249616"
28
+ CCCD_UUID = "00002902-0000-1000-8000-00805f9b34fb"
29
+
30
+ # Advertising: manufacturer data (company id 0xFFFF) layout:
31
+ # 0203 0010 aabbccddeeff
32
+ # ^^^^ ^^^^ ^^^^^^^^^^^^
33
+ # type flags MAC of the device (12 hex chars)
34
+ ADV_COMPANY_ID = 0xFFFF
35
+ ADV_TYPE_PREFIX = b"\x02\x03" # pet feeder
36
+ PLAN_SLOT_COUNT = 10 # device-side fixed schedule array
37
+ CLEAR_MARKER = "0000000000"
38
+
39
+ # Known error codes (live-captured)
40
+ ERR_DEVICE_LOCKED = -31400
41
+ ERR_INVALID_PARAMS = -32602
42
+ ERR_LOCK_STATE_2 = -31402 # app reacts; semantics unconfirmed
43
+ ERR_LOCK_STATE_4 = -31404 # app reacts; semantics unconfirmed
44
+
45
+ _TOKEN_ALPHABET = string.ascii_lowercase + string.ascii_uppercase + string.digits
46
+
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Errors
50
+ # ---------------------------------------------------------------------------
51
+ class ASF02Error(Exception):
52
+ """Base class for ASF02 protocol errors (carries the device error payload)."""
53
+
54
+ def __init__(self, code: int, message: str):
55
+ super().__init__(f"device error {code}: {message}")
56
+ self.code = code
57
+ self.message = message
58
+
59
+
60
+ # ---------------------------------------------------------------------------
61
+ # Token / unlock
62
+ # ---------------------------------------------------------------------------
63
+ def generate_token(n: int = 10) -> str:
64
+ """Generate a random bind token (same charset the vendor app uses)."""
65
+ return "".join(secrets.choice(_TOKEN_ALPHABET) for _ in range(n))
66
+
67
+
68
+ def unlock_code_for(token: str) -> str:
69
+ """Compute the unlock code for a bind token.
70
+
71
+ Mirrors the vendor app: ``BigInteger(1, md5("0000:" + token)).toString(16)``
72
+ — hex of the digest as an unsigned big-endian integer, so leading zero
73
+ nibbles are dropped. A plain ``hexdigest()`` will NOT match when the digest
74
+ starts with a 0x0x byte.
75
+
76
+ >>> unlock_code_for("ExampleTok1")
77
+ 'a587ea45721f8a612c0fcbf507d69adc'
78
+ """
79
+ digest = hashlib.md5(f"0000:{token}".encode("utf-8")).digest()
80
+ return format(int.from_bytes(digest, "big"), "x")
81
+
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # Plan strings
85
+ # ---------------------------------------------------------------------------
86
+ @dataclass(frozen=True)
87
+ class PlanEntry:
88
+ """One schedule slot: time (hour, minute), portion count, enabled flag.
89
+
90
+ ``portion`` = how many auger revolutions to dispense (one revolution
91
+ is one portion).
92
+ """
93
+
94
+ hour: int
95
+ minute: int
96
+ portion: int # 1..255 (vendor UI offers a small subset)
97
+ enabled: bool
98
+
99
+
100
+ def encode_plan_entry(hour: int, minute: int, portion: int, enabled: bool = True) -> str:
101
+ """Encode a schedule entry as the device's 10-char hex string.
102
+
103
+ Layout: ``"00" + HH + MM + PP + XX`` (HH/MM/PP hex, XX enable flag).
104
+ """
105
+ if not 0 <= hour <= 23:
106
+ raise ValueError(f"hour out of range: {hour}")
107
+ if not 0 <= minute <= 59:
108
+ raise ValueError(f"minute out of range: {minute}")
109
+ if not 0 <= portion <= 255:
110
+ raise ValueError(f"portion out of range: {portion}")
111
+ return f"00{hour:02x}{minute:02x}{portion:02x}{0x01 if enabled else 0x00:02x}"
112
+
113
+
114
+ def decode_plan_entry(entry: str) -> PlanEntry:
115
+ """Decode a 10-char hex plan string into a :class:`PlanEntry`."""
116
+ if not plan_entry_valid(entry):
117
+ raise ValueError(f"malformed plan entry: {entry!r}")
118
+ return PlanEntry(
119
+ hour=int(entry[2:4], 16),
120
+ minute=int(entry[4:6], 16),
121
+ portion=int(entry[6:8], 16),
122
+ enabled=entry[8:10] == "01",
123
+ )
124
+
125
+
126
+ def plan_entry_valid(entry: str) -> bool:
127
+ """True if *entry* is a well-formed 10-char plan string (any time/portion)."""
128
+ if len(entry) != 10 or entry[0:2] != "00":
129
+ return False
130
+ try:
131
+ int(entry, 16)
132
+ except ValueError:
133
+ return False
134
+ return not (0 <= int(entry[2:4], 16) > 23) and not (0 <= int(entry[4:6], 16) > 59)
135
+
136
+
137
+ def is_clear_marker(entry: str) -> bool:
138
+ """True for the all-zeros entry, which the device treats as 'clear schedule'."""
139
+ return entry == CLEAR_MARKER
140
+
141
+
142
+ def decode_plan_slot(slot: str) -> PlanEntry | None:
143
+ """Decode one slot of the 10-slot array.
144
+
145
+ The device returns ``""`` for unused slots and ``"0000000000"`` as a clear
146
+ marker; both map to ``None`` here.
147
+ """
148
+ if not slot or is_clear_marker(slot):
149
+ return None
150
+ return decode_plan_entry(slot)
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Advertising
155
+ # ---------------------------------------------------------------------------
156
+ def decode_advertisement(manufacturer_data: bytes, local_name: str | None = None) -> dict:
157
+ """Decode a feeder's advertising payload.
158
+
159
+ ``manufacturer_data`` is the *value* of the manufacturer-specific data
160
+ field (without the company-id prefix). Returns a dict with:
161
+
162
+ - ``product_type``: first 2 bytes (``b'\\x02\\x03'`` = pet feeder)
163
+ - ``mac``: the device MAC (last 6 bytes), e.g. ``"AA:BB:CC:DD:EE:FF"``
164
+ - ``model``: from the local name (``ASF02-DDEEFF`` -> ``"ASF02"``) or None
165
+
166
+ Raises ``ValueError`` if the payload doesn't look like a feeder ad.
167
+ """
168
+ if len(manufacturer_data) < 8 or not manufacturer_data.startswith(ADV_TYPE_PREFIX):
169
+ raise ValueError("not a feeder advertisement")
170
+ mac_bytes = manufacturer_data[-6:]
171
+ mac = ":".join(f"{b:02X}" for b in mac_bytes)
172
+ model = None
173
+ if local_name and "-" in local_name:
174
+ model = local_name.split("-", 1)[0]
175
+ return {
176
+ "product_type": manufacturer_data[:2],
177
+ "mac": mac,
178
+ "model": model,
179
+ }
180
+
181
+
182
+ # ---------------------------------------------------------------------------
183
+ # Message framing
184
+ # ---------------------------------------------------------------------------
185
+ def encode_request(method: str, req_id: int, params=None) -> bytes:
186
+ """Encode a request as the exact JSON the vendor app writes (compact, no spaces).
187
+
188
+ ``params`` is embedded as a raw JSON value; pass ``None`` to omit the field.
189
+ """
190
+ if params is None:
191
+ body = f'{{"m":"{method}","i":{req_id}}}'
192
+ else:
193
+ import json as _json
194
+
195
+ body = f'{{"m":"{method}","i":{req_id},"p":{_json.dumps(params, separators=(",", ":"))}}}'
196
+ return body.encode("utf-8")
197
+
198
+
199
+ def parse_response(data: bytes) -> dict:
200
+ """Parse a notification payload into a normalized response dict.
201
+
202
+ Returns one of:
203
+ ``{"ok": True, "i": <id>, "r": <result>}``
204
+ ``{"ok": False, "i": <id>, "error": ASF02Error}``
205
+
206
+ Raises ``ValueError`` for non-JSON or structurally invalid payloads.
207
+ """
208
+ import json as _json
209
+
210
+ try:
211
+ msg = _json.loads(data.decode("utf-8"))
212
+ except (UnicodeDecodeError, ValueError) as e:
213
+ raise ValueError(f"unparseable response: {data!r}") from e
214
+ if not isinstance(msg, dict) or "i" not in msg:
215
+ raise ValueError(f"malformed response (missing id): {data!r}")
216
+ if "r" in msg:
217
+ return {"ok": True, "i": msg["i"], "r": msg["r"]}
218
+ if "e" in msg:
219
+ e = msg["e"]
220
+ raise ASF02Error(int(e.get("c", 0)), str(e.get("m", "unknown")))
221
+ raise ValueError(f"response has neither r nor e: {data!r}")
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.4
2
+ Name: asf02
3
+ Version: 0.1.0
4
+ Summary: Python client for Lulumiao pet slow feeders (OEM ASF02 / CWH01L-A1, BLE JSON-RPC)
5
+ Author: cptskippy, AgentCarlBrutananadilewski
6
+ License-Expression: Apache-2.0
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Home Automation
11
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
12
+ Classifier: Topic :: System :: Hardware
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: bleak>=0.22
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8; extra == "dev"
19
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # asf02
23
+
24
+ Lulumiao pet slow feeders can only be managed via an App that has since been
25
+ delisted from the Google Play store. Without the App, owners cannot update
26
+ feed schedules or synchronize the feeder clock which is prone to drift. This
27
+ library allows you to once again manage your slow feeder and save it from
28
+ the landfill.
29
+
30
+ Python client library for managing **Lulumiao pet slow feeders** over BLE.
31
+ The protocol was reverse-engineered from the vendor Android app and
32
+ **verified to work with devices having v1.19.12 firmware**.
33
+
34
+ The feeder speaks a small JSON-RPC dialect over two GATT characteristics.
35
+ This library wraps the whole conversation — discovery, pairing, unlock,
36
+ schedule management, on-demand feeding, and status — behind a tiny async
37
+ API. Built on [`bleak`](https://github.com/hbldh/bleak); no other runtime
38
+ dependencies.
39
+
40
+ ## Product Details
41
+ | | |
42
+ |---|---|
43
+ | Brand | Lulumiao |
44
+ | Device | Pet slow feeder |
45
+ | Manufacturer | Hong Kong M Spacer Limited |
46
+ | Model | CWH01L-A1 (OEM model `ASF02`, per `info` and BLE advertising) |
47
+ | FCC ID | [2A9QN-CWH01L-A1](https://fccid.io/2A9QN-CWH01L-A1) |
48
+
49
+ ## Product Images
50
+ ![Lulumiao pet slow feeder](slowfeeder.png "Lulumiao pet slow feeder")
51
+
52
+ ## Install
53
+
54
+ ### From a local repo checkout
55
+ ```bash
56
+ pip install -e ".[dev]" # includes pytest
57
+ ```
58
+
59
+ ### From GitHub
60
+ ```bash
61
+ pip install git+https://github.com/cptskippy/asf02.git
62
+ ```
63
+
64
+ ### From PyPI
65
+ ```bash
66
+ pip install asf02
67
+ ```
68
+
69
+ ## Quick start
70
+
71
+ ```python
72
+ import asyncio
73
+ from asf02 import ASF02Client
74
+
75
+ async def main():
76
+ async with ASF02Client("<DEVICE_MAC>", token="<BIND_TOKEN>") as feeder:
77
+ await feeder.unlock() # required on every connect
78
+ await feeder.sync_time(-25200) # PDT w/DST in seconds
79
+ info = await feeder.info() # {'f': '1.19.12', 'm': 'ASF02', ...}
80
+ status = await feeder.status() # {'n': 1065, 'b': 458, ...}
81
+ await feeder.feed(1) # dispense 1 portion now
82
+ await feeder.set_schedule([(15, 30, 1), (16, 0, 1)])
83
+
84
+ asyncio.run(main())
85
+ ```
86
+
87
+ ## Discovery
88
+
89
+ ```python
90
+ from asf02 import discover_feeders
91
+
92
+ async def main():
93
+ for f in await discover_feeders(timeout=10):
94
+ print(f.address, f.model, f.rssi)
95
+ ```
96
+
97
+ Feeders advertise continuously: local name `ASF02-<last6 of MAC>` plus
98
+ manufacturer data (company `0xFFFF`) starting `02 03`, with the MAC embedded.
99
+
100
+
101
+ ## Pairing / tokens
102
+
103
+ - Generate a token: `ASF02Client.new_token()` (10 chars, same charset as the vendor app).
104
+ - Keep the token with your device config. The unlock code is always derived
105
+ from it (`md5("0000:"+token)` — see `unlock_code_for`).
106
+ - Store it in the device: `await feeder.bind(token)`. **Re-binding overwrites**
107
+ the previous token — the old one stops working.
108
+
109
+ ## Schedules
110
+
111
+ - The device stores a **fixed 10-slot array**; `set_schedule` replaces it.
112
+ - Entries are `(hour, minute, portion)` or `(hour, minute, portion, enabled)`.
113
+ - `set_schedule([])` (or `clear=True`) wipes the schedule.
114
+ - **Time fields are hex on the wire** — the library handles this, but know it:
115
+ `0012000200` is 18:00, not 12:00.
116
+ - The **write response** is the authoritative confirmation (some firmware
117
+ builds answer schedule *reads* with stale/empty data).
118
+
119
+ ## Behavior notes (learned from the hardware)
120
+
121
+ - The device **locks across every (re)connect** — call `unlock()` each time
122
+ (or use `connect_unlocked()`). Only `info` works while locked.
123
+ - `time.calibration` takes **epoch seconds** + tz offset in **seconds**
124
+ (incl. DST; e.g. −25200 for PDT — same convention the vendor app uses).
125
+ Always re-sync on connect; schedules run on the device clock.
126
+ - `feeder.log` may return **no notification at all** — `get_log()` returns
127
+ `None` in that case instead of erroring.
128
+ - No MTU negotiation needed for any documented command (the link carries the
129
+ full 79-byte responses fine).
130
+ - Transient connections are fine: connect → work → disconnect. The feeders
131
+ run autonomously between visits.
132
+ - The feeder clock drifts over time and freezes entirely while unpowered.
133
+ Sync it (`sync_time()`) semi-regularly — and on every reconnect if you
134
+ want schedules to stay on time — since the schedule runs on the device
135
+ clock, not yours.
136
+
137
+ ## API Status
138
+
139
+ | Method | Status |
140
+ |---|---|
141
+ | `info` | ✅ Working |
142
+ | `bind` | ✅ Working |
143
+ | `unlock` | ✅ Working |
144
+ | `time.calibration` | ✅ Working |
145
+ | `feeder.status` | ✅ Working |
146
+ | `feeder.feed` | ✅ Working |
147
+ | `feeder.stop` | ✅ Working |
148
+ | `feeder.plan` (read) | ⚠️ No result on v1.19.12 firmware |
149
+ | `feeder.plan` (write) | ✅ Working |
150
+ | `feeder.log` | ⚠️ No result on v1.19.12 firmware |
151
+
152
+ **IMPORTANT NOTE:** While `feeder.plan` (read) and `feeder.log` are defined, the
153
+ v1.19.12 firmware appears to have a bug and it will always return `null`. It
154
+ is advised to retain a copy of any plan sent the feeder as you may not be
155
+ able to retrieve it in the future.
156
+
157
+ ## Project layout
158
+
159
+ ```
160
+ asf02/
161
+ protocol.py pure codecs + constants (unit-testable, no I/O)
162
+ client.py async device client (bleak)
163
+ discovery.py scanner
164
+ examples/cli.py demo CLI (run on a machine with Bluetooth)
165
+ tests/ unit tests anchored to real captured wire traffic
166
+ ```
167
+
168
+ ## Publishing
169
+
170
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for how releases are cut and how
171
+ PyPI publishing is configured.
172
+
173
+ ## License
174
+
175
+ Apache-2.0
@@ -0,0 +1,9 @@
1
+ asf02/__init__.py,sha256=Fl92KfIUxUACdNIsTAWeH7xNjomk1TAHTFKEAt7QQ0E,1173
2
+ asf02/client.py,sha256=WdT-3f4D00NlYlZACnTlve0BUPxct85oB9XLeoXJaiM,12898
3
+ asf02/discovery.py,sha256=VHtGd2IatMIeDptjIioBp-2fLhvxVcHf_Px-H5sWhCk,2002
4
+ asf02/protocol.py,sha256=6Nowoa_LvEiACi05Gv18PZ6JmevhHdGYbUhWEKRpCJ4,8145
5
+ asf02-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
6
+ asf02-0.1.0.dist-info/METADATA,sha256=-DpTocHyZnhqLs8SLhyxtT5L-5sACOGKnfWVNyRapNE,6120
7
+ asf02-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
8
+ asf02-0.1.0.dist-info/top_level.txt,sha256=WHty8Y5Ba8n3RKG8OhB3lHgwhiDvHa5g7ltXpF0aoOU,6
9
+ asf02-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ asf02