From 8eba7fa24c3fc71c909cfeb7cb61d2cc5298e661 Mon Sep 17 00:00:00 2001 From: Dejvino Date: Tue, 1 Dec 2026 19:15:05 +0100 Subject: [PATCH] Add MeshCore Agent HACS integration: todo module with reminders Custom HA integration (domain meshcore_agent) that lets MeshCore nodes manage a todo list over mesh messages: - todo / todo list, todo add, todo done, todo uncheck, todo remove - remind / remind off (relative, clock, weekday, absolute) - replies via meshcore.send_message / send_channel_message - reminders scheduled with async_track_point_in_time and delivered to the sender who set them - todo list also exposed as a HA todo entity - config flow with sender allowlist, allow-all toggle, reply length cap - pure-Python core (core/) covered by pytest; adapter flow tested with stubbed hass --- .gitignore | 4 + LICENSE | 21 ++ README.md | 117 +++++++ custom_components/meshcore_agent/__init__.py | 310 ++++++++++++++++++ .../meshcore_agent/config_flow.py | 100 ++++++ custom_components/meshcore_agent/const.py | 30 ++ .../meshcore_agent/core/__init__.py | 1 + .../meshcore_agent/core/commands.py | 238 ++++++++++++++ .../meshcore_agent/core/store.py | 174 ++++++++++ .../meshcore_agent/core/timeparse.py | 123 +++++++ .../meshcore_agent/manifest.json | 13 + custom_components/meshcore_agent/store.py | 26 ++ custom_components/meshcore_agent/strings.json | 42 +++ custom_components/meshcore_agent/todo.py | 115 +++++++ .../meshcore_agent/translations/en.json | 42 +++ hacs.json | 5 + pyproject.toml | 9 + tests/conftest.py | 6 + tests/test_adapter.py | 38 +++ tests/test_agent_flow.py | 251 ++++++++++++++ tests/test_commands.py | 191 +++++++++++ tests/test_store.py | 102 ++++++ tests/test_timeparse.py | 77 +++++ 23 files changed, 2035 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 custom_components/meshcore_agent/__init__.py create mode 100644 custom_components/meshcore_agent/config_flow.py create mode 100644 custom_components/meshcore_agent/const.py create mode 100644 custom_components/meshcore_agent/core/__init__.py create mode 100644 custom_components/meshcore_agent/core/commands.py create mode 100644 custom_components/meshcore_agent/core/store.py create mode 100644 custom_components/meshcore_agent/core/timeparse.py create mode 100644 custom_components/meshcore_agent/manifest.json create mode 100644 custom_components/meshcore_agent/store.py create mode 100644 custom_components/meshcore_agent/strings.json create mode 100644 custom_components/meshcore_agent/todo.py create mode 100644 custom_components/meshcore_agent/translations/en.json create mode 100644 hacs.json create mode 100644 pyproject.toml create mode 100644 tests/conftest.py create mode 100644 tests/test_adapter.py create mode 100644 tests/test_agent_flow.py create mode 100644 tests/test_commands.py create mode 100644 tests/test_store.py create mode 100644 tests/test_timeparse.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..17cd2fc --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.venv/ +__pycache__/ +*.pyc +.pytest_cache/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f29302f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 dejvino + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index e69de29..5a97266 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,117 @@ +# MeshCore Agent for Home Assistant + +A HACS custom integration that lets MeshCore nodes talk to Home Assistant over +the mesh. The first module is a **todo list with reminders**: any allowlisted +node can list, add, complete, remove todos and set per-todo reminders — +entirely from text messages. + +Built on top of [meshcore-dev/meshcore-ha](https://github.com/meshcore-dev/meshcore-ha): +it listens for `meshcore_message` events and replies via the +`meshcore.send_message` / `meshcore.send_channel_message` services. + +## Requirements + +- Home Assistant 2025.6.0 or later +- The [MeshCore integration](https://github.com/meshcore-dev/meshcore-ha) + installed and configured (USB, BLE or TCP companion) + +## Installation + +1. In HACS → ⋮ → *Custom repositories*, add this repository with category + **Integration**. +2. Install **MeshCore Agent**. +3. Restart Home Assistant. +4. Settings → Devices & services → *Add Integration* → **MeshCore Agent**. +5. Fill in the allowlist of senders who may command the agent (public key + prefixes or contact names, comma separated). Leave "Allow all senders" + unchecked; anyone on the mesh could otherwise command your todo list. + +## Mesh commands + +Send a direct message to your companion (or a message to a channel, if that +channel's senders are allowlisted): + +| Command | Example | Result | +| --- | --- | --- | +| `todo` | `todo` | List all todos (open first, then done) | +| `todo add ` | `todo add Buy milk` | Add a todo | +| `todo done ` | `todo done 2` | Check a todo off | +| `todo uncheck ` | `todo uncheck 2` | Reopen a todo | +| `todo remove ` | `todo remove 2` (alias `rm`) | Delete a todo | +| `remind ` | `remind 1 in 30m` | Set a reminder for a todo | +| `remind off ` | `remind off 1` | Clear a todo's reminder | +| `help` | `help` | Command overview | + +`` is the number shown by `todo`, or a unique text prefix of the item +(`todo done buy m`). Messages may optionally start with a wake word: +`agent todo`, `bot done 2`. + +### Reminder times + +| Syntax | Example | Meaning | +| --- | --- | --- | +| `in ` | `in 30m`, `in 1h30m`, `in 1d` | Relative offset (`s`/`m`/`h`/`d`) | +| `HH:MM` | `14:30` | Today at that time, or tomorrow if it passed | +| `today/tomorrow HH:MM` | `tomorrow 09:00` | Explicit day | +| ` HH:MM` | `monday 08:00` | Next occurrence of that weekday | +| `YYYY-MM-DD [HH:MM]` | `2026-12-24 14:30` | Absolute date | + +Reminders are sent over the mesh ("Reminder: Buy milk") to the sender who set +them, using the same time zone as Home Assistant. They also show up as the +item's due date on the Home Assistant side. + +### Reply flow + +- Direct messages are answered as direct messages to the sender's + `pubkey_prefix`. +- Channel messages are answered back into the same channel; reminders set from + a channel are delivered back into that channel. +- Replies are truncated to the configured maximum length (default 200 chars). + +## Home Assistant side + +The todo list appears as a `todo` entity (`todo._todos`), so the +same items can also be added, completed and deleted from the Home Assistant UI +— and changes made in the UI are visible to mesh users on the next `todo`. + +## Security notes + +- Only allowlisted senders' commands are executed; everything else is ignored. +- The allowlist matches direct-message senders on their 12-hex `pubkey_prefix` + and channel senders on their advertised name. Names on channels are + self-reported — prefer key prefixes when allowlisting channel users. + +## Architecture + +``` +custom_components/meshcore_agent/ +├── core/ # pure Python, no HA imports, fully unit-tested +│ ├── store.py # todo store: items, reminders, reference resolution +│ ├── timeparse.py # reminder time parser +│ └── commands.py # command registry + handlers +├── __init__.py # HA adapter: event listener, reply sender, reminder scheduler +├── config_flow.py # UI config: allowlist, allow-all, reply length cap +├── todo.py # todo platform entity +└── store.py # HA storage wrapper (JSON under .storage) +``` + +The core does all parsing/permission-sensitive work and is covered by pytest +(`tests/`); the HA layer is a thin event adapter. A crash in message handling +is caught and logged, and never takes down the event loop. + +## Development + +```bash +uv venv .venv +uv pip install pytest pytest-asyncio homeassistant +.venv/pytest +``` + +To run against a live instance, symlink or copy the integration into your HA +config directory: + +```bash +ln -s "$(pwd)/custom_components/meshcore_agent" /path/to/config/custom_components/meshcore_agent +``` + +then restart Home Assistant or reload the integration. diff --git a/custom_components/meshcore_agent/__init__.py b/custom_components/meshcore_agent/__init__.py new file mode 100644 index 0000000..a4c4e88 --- /dev/null +++ b/custom_components/meshcore_agent/__init__.py @@ -0,0 +1,310 @@ +"""MeshCore Agent: a todo/reminder agent answering MeshCore mesh messages. + +The adapter is deliberately thin: + +- listen for ``meshcore_message`` events from the MeshCore integration +- check the sender against an allowlist +- hand the text to the pure-Python core (``core.commands``) +- send the reply back over the mesh via ``meshcore.send_message`` / + ``meshcore.send_channel_message`` +- schedule per-todo reminders and deliver them the same way +""" + +from __future__ import annotations + +import logging +from collections.abc import Callable + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import Platform +from homeassistant.core import Event, HomeAssistant, callback +from homeassistant.helpers import config_validation as cv +from homeassistant.helpers import device_registry as dr +from homeassistant.helpers.dispatcher import ( + async_dispatcher_send, +) +from homeassistant.helpers.event import async_track_point_in_time +from homeassistant.util import dt as dt_util + +from . import store as storage +from .const import ( + ATTR_CHANNEL_IDX, + ATTR_MESSAGE, + ATTR_MESSAGE_TYPE, + ATTR_OUTGOING, + ATTR_PUBKEY_PREFIX, + ATTR_SENDER_NAME, + CONF_ALLOWLIST, + CONF_ALLOW_ALL, + CONF_MAX_REPLY, + DEFAULT_ALLOW_ALL, + DEFAULT_ALLOWLIST, + DEFAULT_MAX_REPLY, + DOMAIN, + EVENT_MESHCORE_MESSAGE, + MESH_CORE_DOMAIN, + SERVICE_MESHCORE_SEND_CHANNEL_MESSAGE, + SERVICE_MESHCORE_SEND_MESSAGE, + SIGNAL_STORE_UPDATED, +) +from .core.commands import Context, handle_message +from .core.store import Reminder + +_LOGGER = logging.getLogger(__name__) + +PLATFORMS: list[Platform] = [Platform.TODO] + +VALID_MESSAGE_TYPES = ("direct", "channel") + + +def target_from_event(event_data: dict) -> Reminder | None: + """Build the reply target of the message sender.""" + if event_data.get(ATTR_MESSAGE_TYPE) == "channel": + channel_idx = event_data.get(ATTR_CHANNEL_IDX) + if channel_idx is None: + return None + return Reminder(at="", kind="channel", target=str(channel_idx)) + prefix = event_data.get(ATTR_PUBKEY_PREFIX) + if not prefix: + return None + return Reminder(at="", kind="direct", target=prefix) + + +def truncate(text: str, limit: int) -> str: + """Clamp a reply to the mesh-friendly length limit.""" + if len(text) <= limit: + return text + cut = text[: limit - 3] + newline = cut.rfind("\n") + if newline > 0: + cut = cut[:newline] + return cut.rstrip() + "..." + + +class MeshCoreAgent: + """Event-driven adapter between the mesh and the pure core.""" + + def __init__( + self, + hass: HomeAssistant, + entry: ConfigEntry, + agent_store: storage.AgentStore, + ) -> None: + self.hass = hass + self.entry = entry + self.agent_store = agent_store + + options = {**entry.data, **entry.options} + self._allow_all: bool = options.get(CONF_ALLOW_ALL, DEFAULT_ALLOW_ALL) + self._allowlist: set[str] = { + part.strip().lower() + for part in options.get(CONF_ALLOWLIST, DEFAULT_ALLOWLIST) + .replace("\n", ",") + .split(",") + if part.strip() + } + self._max_reply: int = cv.positive_int(options.get(CONF_MAX_REPLY, DEFAULT_MAX_REPLY)) + + self._unsub_event = None + self._reminder_unsubs: dict[str, callable] = {} + + # -- lifecycle --------------------------------------------------------- + + @callback + def async_start(self) -> None: + self._unsub_event = self.hass.bus.async_listen( + EVENT_MESHCORE_MESSAGE, self._handle_event + ) + self.async_reschedule_reminders() + + async def async_stop(self) -> None: + if self._unsub_event is not None: + self._unsub_event() + self._unsub_event = None + self._cancel_reminder_jobs() + + # -- access ------------------------------------------------------------ + + @property + def todo_store(self): + return self.agent_store.todo_store + + async def async_persist(self) -> None: + """Save the store and notify listeners (todo entity).""" + await self.agent_store.async_save() + async_dispatcher_send( + self.hass, SIGNAL_STORE_UPDATED.format(entry_id=self.entry.entry_id) + ) + + # -- allowlist ----------------------------------------------------------- + + def is_allowed(self, event_data: dict) -> bool: + if self._allow_all: + return True + if not self._allowlist: + return False + prefix = (event_data.get(ATTR_PUBKEY_PREFIX) or "").lower() + name = (event_data.get(ATTR_SENDER_NAME) or "").lower() + return ( + bool(prefix) and prefix in self._allowlist + ) or (bool(name) and name in self._allowlist) + + # -- message handling ------------------------------------------------------ + + async def _handle_event(self, event: Event) -> None: + data = event.data + if data.get(ATTR_OUTGOING): + return + if data.get(ATTR_MESSAGE_TYPE) not in VALID_MESSAGE_TYPES: + return + if not self.is_allowed(data): + _LOGGER.debug( + "Ignoring message from non-allowlisted sender %s", + data.get(ATTR_PUBKEY_PREFIX) or data.get(ATTR_SENDER_NAME), + ) + return + + text = data.get(ATTR_MESSAGE) or "" + target = target_from_event(data) + ctx = Context(store=self.todo_store, now=dt_util.now(), target=target) + try: + reply = handle_message(text, ctx) + except Exception: # noqa: BLE001 - a bad message must never crash HA + _LOGGER.exception("Error handling message: %s", text) + reply = "Oops, that failed. Try: help" + + if reply: + await self._send_reply(data, truncate(reply, self._max_reply)) + await self.async_persist() + self.async_reschedule_reminders() + + async def _send_reply(self, incoming: dict, reply: str) -> None: + if ( + incoming.get(ATTR_MESSAGE_TYPE) == "channel" + and incoming.get(ATTR_CHANNEL_IDX) is not None + ): + await self.hass.services.async_call( + MESH_CORE_DOMAIN, + SERVICE_MESHCORE_SEND_CHANNEL_MESSAGE, + { + "channel_idx": int(incoming[ATTR_CHANNEL_IDX]), + ATTR_MESSAGE: reply, + }, + blocking=False, + ) + return + prefix = incoming.get(ATTR_PUBKEY_PREFIX) + if not prefix: + _LOGGER.warning("No pubkey_prefix on incoming message; cannot reply") + return + await self.hass.services.async_call( + MESH_CORE_DOMAIN, + SERVICE_MESHCORE_SEND_MESSAGE, + {"pubkey_prefix": prefix, ATTR_MESSAGE: reply}, + blocking=False, + ) + + # -- reminders --------------------------------------------------------------- + + @callback + def async_reschedule_reminders(self) -> None: + """Sync scheduled jobs with the reminders currently in the store.""" + self._cancel_reminder_jobs() + now = dt_util.now() + for item, reminder in self.todo_store.pending_reminders(): + at = dt_util.parse_datetime(reminder.at) + if at is None: + self.todo_store.clear_reminder(item) + continue + if at <= now: + self.hass.async_create_task(self._fire_reminder(item.id)) + continue + self._reminder_unsubs[item.id] = async_track_point_in_time( + self.hass, + self._reminder_fired(item.id), + at, + ) + + def _cancel_reminder_jobs(self) -> None: + for unsub in self._reminder_unsubs.values(): + unsub() + self._reminder_unsubs.clear() + + @callback + def _reminder_fired(self, item_id: str): + @callback + def _listener(*_args) -> None: + self.hass.async_create_task(self._fire_reminder(item_id)) + + return _listener + + async def _fire_reminder(self, item_id: str) -> None: + item = self.todo_store.get(item_id) + if item is None or item.reminder is None: + return + reminder = item.reminder + self.todo_store.clear_reminder(item) + await self.async_persist() + + message = truncate(f"Reminder: {item.text}", self._max_reply) + if reminder.kind == "channel": + try: + channel_idx = int(reminder.target) + except ValueError: + _LOGGER.warning("Invalid reminder channel target: %s", reminder.target) + return + await self.hass.services.async_call( + MESH_CORE_DOMAIN, + SERVICE_MESHCORE_SEND_CHANNEL_MESSAGE, + {"channel_idx": channel_idx, ATTR_MESSAGE: message}, + blocking=False, + ) + return + if not reminder.target: + _LOGGER.warning("Reminder for %r has no target; dropped", item.text) + return + await self.hass.services.async_call( + MESH_CORE_DOMAIN, + SERVICE_MESHCORE_SEND_MESSAGE, + {"pubkey_prefix": reminder.target, ATTR_MESSAGE: message}, + blocking=False, + ) + + +# -- config entry setup --------------------------------------------------- + + +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + hass.data.setdefault(DOMAIN, {}) + + device_registry = dr.async_get(hass) + device_registry.async_get_or_create( + config_entry_id=entry.entry_id, + identifiers={(DOMAIN, entry.entry_id)}, + name=entry.title, + manufacturer="meshcore-ha-agent", + model="MeshCore Agent", + ) + + agent_store = storage.AgentStore(hass, entry.entry_id) + await agent_store.async_load() + + agent = MeshCoreAgent(hass, entry, agent_store) + hass.data[DOMAIN][entry.entry_id] = agent + entry.runtime_data = agent + agent.async_start() + + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + return True + + +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + agent: MeshCoreAgent | None = hass.data.get(DOMAIN, {}).pop(entry.entry_id, None) + if agent is not None: + await agent.async_stop() + return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + + +async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + store = storage.Store(hass, storage.STORAGE_VERSION, f"{DOMAIN}.{entry.entry_id}.todos") + await store.async_remove() diff --git a/custom_components/meshcore_agent/config_flow.py b/custom_components/meshcore_agent/config_flow.py new file mode 100644 index 0000000..69c59d7 --- /dev/null +++ b/custom_components/meshcore_agent/config_flow.py @@ -0,0 +1,100 @@ +"""Config flow for the MeshCore Agent integration.""" + +from __future__ import annotations + +from typing import Any + +import voluptuous as vol +from homeassistant import config_entries +from homeassistant.core import callback +from homeassistant.data_entry_flow import FlowResult + +from .const import ( + CONF_ALLOWLIST, + CONF_ALLOW_ALL, + CONF_MAX_REPLY, + DEFAULT_ALLOW_ALL, + DEFAULT_ALLOWLIST, + DEFAULT_MAX_REPLY, + DOMAIN, +) + +STEP_SCHEMA = vol.Schema( + { + vol.Required(CONF_ALLOWLIST, default=DEFAULT_ALLOWLIST): str, + vol.Required(CONF_ALLOW_ALL, default=DEFAULT_ALLOW_ALL): bool, + vol.Required(CONF_MAX_REPLY, default=DEFAULT_MAX_REPLY): vol.All( + vol.Coerce(int), vol.Range(min=20, max=500) + ), + } +) + + +def _validate(user_input: dict[str, Any]) -> str | None: + """Return an error key, or None when the input is valid.""" + try: + int(user_input[CONF_MAX_REPLY]) + except (KeyError, TypeError, ValueError): + return "invalid_max_reply" + return None + + +class ConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): + """Handle the initial setup of the integration.""" + + VERSION = 1 + + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: + errors: dict[str, str] = {} + if user_input is not None: + if error := _validate(user_input): + errors["base"] = error + else: + await self.async_set_unique_id(DOMAIN) + self._abort_if_unique_id_configured() + return self.async_create_entry(title="MeshCore Agent", data=user_input) + + return self.async_show_form(step_id="user", data_schema=STEP_SCHEMA, errors=errors) + + @staticmethod + @callback + def async_get_options_flow( + config_entry: config_entries.ConfigEntry, + ) -> OptionsFlowHandler: + return OptionsFlowHandler() + + +class OptionsFlowHandler(config_entries.OptionsFlow): + """Handle editing the options of an existing entry.""" + + async def async_step_init( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: + errors: dict[str, str] = {} + if user_input is not None: + if error := _validate(user_input): + errors["base"] = error + else: + return self.async_create_entry(title="", data=user_input) + + entry = self.config_entry + current = {**entry.data, **entry.options} + schema = STEP_SCHEMA.extend( + { + vol.Required( + CONF_ALLOWLIST, + default=current.get(CONF_ALLOWLIST, DEFAULT_ALLOWLIST), + ): str, + vol.Required( + CONF_ALLOW_ALL, + default=current.get(CONF_ALLOW_ALL, DEFAULT_ALLOW_ALL), + ): bool, + vol.Required( + CONF_MAX_REPLY, + default=current.get(CONF_MAX_REPLY, DEFAULT_MAX_REPLY), + ): vol.All(vol.Coerce(int), vol.Range(min=20, max=500)), + } + ) + return self.async_show_form(step_id="init", data_schema=schema, errors=errors) diff --git a/custom_components/meshcore_agent/const.py b/custom_components/meshcore_agent/const.py new file mode 100644 index 0000000..21109d3 --- /dev/null +++ b/custom_components/meshcore_agent/const.py @@ -0,0 +1,30 @@ +"""Constants for the MeshCore Agent integration.""" + +DOMAIN = "meshcore_agent" +MESH_CORE_DOMAIN = "meshcore" # domain of the meshcore-dev/meshcore-ha integration + +# MeshCore integration (meshcore-dev/meshcore-ha) event and service names. +EVENT_MESHCORE_MESSAGE = "meshcore_message" +SERVICE_MESHCORE_SEND_MESSAGE = "send_message" +SERVICE_MESHCORE_SEND_CHANNEL_MESSAGE = "send_channel_message" + +# Config entry / options keys. +CONF_ALLOWLIST = "allowlist" # comma/newline separated pubkey prefixes or names +CONF_ALLOW_ALL = "allow_all" +CONF_MAX_REPLY = "max_reply" + +DEFAULT_ALLOWLIST = "" +DEFAULT_ALLOW_ALL = False +DEFAULT_MAX_REPLY = 200 + +# Signal fired after the store changes so the todo entity can refresh. +SIGNAL_STORE_UPDATED = "meshcore_agent_store_updated_{entry_id}" + +# Event data keys of meshcore_message used by the adapter. +ATTR_MESSAGE = "message" +ATTR_OUTGOING = "outgoing" +ATTR_MESSAGE_TYPE = "message_type" +ATTR_SENDER_NAME = "sender_name" +ATTR_PUBKEY_PREFIX = "pubkey_prefix" +ATTR_CHANNEL_IDX = "channel_idx" +ATTR_ENTRY_ID = "entry_id" diff --git a/custom_components/meshcore_agent/core/__init__.py b/custom_components/meshcore_agent/core/__init__.py new file mode 100644 index 0000000..7ba8293 --- /dev/null +++ b/custom_components/meshcore_agent/core/__init__.py @@ -0,0 +1 @@ +"""Pure-Python core of the MeshCore Agent (no Home Assistant imports).""" diff --git a/custom_components/meshcore_agent/core/commands.py b/custom_components/meshcore_agent/core/commands.py new file mode 100644 index 0000000..bb023e5 --- /dev/null +++ b/custom_components/meshcore_agent/core/commands.py @@ -0,0 +1,238 @@ +"""Pure-Python command registry for the MeshCore Agent. + +Each command is a handler receiving the parsed arguments plus shared +context (the todo store, "now", reply target) and returning a reply +string, or None when the message is not addressed to the agent (no +reply is sent). + +This module implements the "todo" feature over mesh text messages: + +- ``todo`` / ``todo list`` list todos +- ``todo add `` add a todo +- ``todo done `` check a todo off +- ``todo uncheck `` reopen a todo +- ``todo remove `` remove a todo +- ``remind `` set a reminder for a todo +- ``remind off `` clear a todo's reminder +- ``help`` command overview + +```` is the 1-based number shown by ``todo``, or a unique text prefix +of the item. ```` syntax is documented in ``timeparse.py``. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime +from typing import Callable + +from .store import Reminder, TodoItem, TodoStore +from .timeparse import TimeParseError, parse_when + +WAKE_WORDS = ("agent", "bot") + +HELP_TEXT = ( + "Commands: todo | todo add | todo done | " + "todo uncheck | todo remove | remind | " + "remind off | help. : 14:30, in 30m, tomorrow 09:00, " + "monday 08:00, 2026-12-24 14:30" +) + + +@dataclass +class Context: + """Shared context passed to every command handler.""" + + store: TodoStore + now: datetime # aware datetime, used for reminders and timestamps + target: Reminder | None = None # reply target of the current sender + + +@dataclass +class Command: + name: str + handler: Callable[[list[str], Context], str] + usage: str + + +# --- helpers ------------------------------------------------------------ + + +def _format_list(ctx: Context) -> str: + ordered = ctx.store.ordered() + if not ordered: + return "No todos. Add one: todo add " + lines = [] + for pos, item in enumerate(ordered, start=1): + mark = "x" if item.is_completed else " " + line = f"{pos}. [{mark}] {item.text}" + if item.reminder is not None: + try: + at = datetime.fromisoformat(item.reminder.at) + line += f" - {at.strftime('%a %d %b %H:%M')}" + except ValueError: + pass + lines.append(line) + return "\n".join(lines) + + +def _number(ctx: Context, item: TodoItem) -> int: + for pos, candidate in enumerate(ctx.store.ordered(), start=1): + if candidate is item: + return pos + return 0 + + +def _resolve_or_reply(ctx: Context, args: list[str]): + """Resolve the first argument into an item, or return a reply string.""" + if not args: + return "Missing todo number. Use: todo" + item = ctx.store.resolve(args[0]) + if item is None: + return f"No todo matches: {args[0]}" + return item + + +# --- handlers ------------------------------------------------------------ + + +def handle_help(args: list[str], ctx: Context) -> str: + return HELP_TEXT + + +def handle_todo_root(args: list[str], ctx: Context) -> str: + if not args or args[0].lower() in ("list", "ls"): + return _format_list(ctx) + handler = TODO_SUBCOMMANDS.get(args[0].lower()) + if handler is not None: + return handler(args[1:], ctx) + return "Unknown todo command. Try: help" + + +def handle_todo_add(args: list[str], ctx: Context) -> str: + text = " ".join(args).strip() + if not text: + return "Usage: todo add " + item = ctx.store.add(text, created=ctx.now.timestamp()) + return f"Added #{_number(ctx, item)}: {text}" + + +def handle_todo_done(args: list[str], ctx: Context) -> str: + item = _resolve_or_reply(ctx, args) + if isinstance(item, str): + return item + if item.is_completed: + return f"Already done: {item.text}" + ctx.store.complete(item) + return f"Done: {item.text}" + + +def handle_todo_uncheck(args: list[str], ctx: Context) -> str: + item = _resolve_or_reply(ctx, args) + if isinstance(item, str): + return item + if not item.is_completed: + return f"Not done yet: {item.text}" + ctx.store.reopen(item) + return f"Reopened: {item.text}" + + +def handle_todo_remove(args: list[str], ctx: Context) -> str: + item = _resolve_or_reply(ctx, args) + if isinstance(item, str): + return item + ctx.store.remove(item) + return f"Removed: {item.text}" + + +def handle_remind(args: list[str], ctx: Context) -> str: + if not args: + return "Usage: remind (e.g. remind 1 in 30m)" + + if args[0].lower() in ("off", "clear", "remove", "none"): + item = _resolve_or_reply(ctx, args[1:]) + if isinstance(item, str): + return item + if item.reminder is None: + return f"No reminder set: {item.text}" + ctx.store.clear_reminder(item) + return f"Reminder cleared: {item.text}" + + ref, when_text = _split_ref_and_when(args, ctx.now) + if ref is None or not when_text: + return "Usage: remind (e.g. remind 1 in 30m)" + item = ctx.store.resolve(ref) + if item is None: + return f"No todo matches: {ref}" + try: + at = parse_when(when_text, ctx.now) + except (TimeParseError, ValueError) as err: + return f"Bad time: {err}" + + target = ctx.target or Reminder(at="", kind="direct", target="") + reminder = Reminder(at=at.isoformat(), kind=target.kind, target=target.target) + ctx.store.set_reminder(item, reminder) + return ( + f"Reminder set for #{_number(ctx, item)} ({item.text}): " + f"{at.strftime('%a %d %b %H:%M')}" + ) + + +TODO_SUBCOMMANDS = { + "add": handle_todo_add, + "done": handle_todo_done, + "uncheck": handle_todo_uncheck, + "remove": handle_todo_remove, + "rm": handle_todo_remove, +} + + +def _split_ref_and_when(args: list[str], now: datetime): + """Split ``remind`` args into (item reference words, when text). + + The time description is the longest suffix that parses as a time; the + words before it reference the item. For a numeric reference this is + simply (args[0], rest). Returns (None, "") when no time parses. + """ + if args[0].isdigit(): + return " ".join([args[0]]), " ".join(args[1:]) + for start in range(1, len(args)): + tail = " ".join(args[start:]) + try: + parse_when(tail, now) + except (TimeParseError, ValueError): + continue + return " ".join(args[:start]), tail + return None, "" + + +COMMANDS: dict[str, Command] = { + "help": Command("help", handle_help, "help"), + "todo": Command("todo", handle_todo_root, "todo [list]"), + "todos": Command("todos", handle_todo_root, "todos"), + "add": Command("add", handle_todo_add, "add "), + "done": Command("done", handle_todo_done, "done "), + "uncheck": Command("uncheck", handle_todo_uncheck, "uncheck "), + "remove": Command("remove", handle_todo_remove, "remove "), + "rm": Command("rm", handle_todo_remove, "rm "), + "remind": Command("remind", handle_remind, "remind "), +} + + +def handle_message(text: str, ctx: Context) -> str | None: + """Dispatch a raw incoming message; returns the reply or None. + + Messages not starting with a known command word are ignored (None). + An optional wake word ("agent", "bot") may precede the command. + """ + if not text or not text.strip(): + return None + words = text.strip().split() + if words and words[0].lower().rstrip(",.!") in WAKE_WORDS: + words = words[1:] + if not words: + return HELP_TEXT + command = COMMANDS.get(words[0].lower().rstrip(",.!")) + if command is None: + return None + return command.handler(words[1:], ctx) diff --git a/custom_components/meshcore_agent/core/store.py b/custom_components/meshcore_agent/core/store.py new file mode 100644 index 0000000..54ac011 --- /dev/null +++ b/custom_components/meshcore_agent/core/store.py @@ -0,0 +1,174 @@ +"""Pure-Python todo store for the MeshCore Agent. + +No Home Assistant imports: everything here is plain Python so it can be +unit-tested in milliseconds and reused outside Home Assistant if needed. +""" + +from __future__ import annotations + +import uuid +from dataclasses import dataclass, field +from datetime import datetime + +STATUS_NEEDS_ACTION = "needs_action" +STATUS_COMPLETED = "completed" + + +def _new_id() -> str: + return uuid.uuid4().hex[:8] + + +@dataclass +class Reminder: + """A reminder attached to a todo item.""" + + at: str # ISO-8601, timezone-aware + kind: str # "direct" or "channel" + target: str # pubkey prefix (direct) or channel index as string (channel) + + def to_dict(self) -> dict: + return {"at": self.at, "kind": self.kind, "target": self.target} + + @classmethod + def from_dict(cls, data: dict) -> Reminder: + return cls( + at=data["at"], + kind=data.get("kind", "direct"), + target=data.get("target", ""), + ) + + +@dataclass +class TodoItem: + """A single todo item.""" + + id: str + text: str + status: str = STATUS_NEEDS_ACTION + created: float = 0.0 + reminder: Reminder | None = None + + def to_dict(self) -> dict: + data = { + "id": self.id, + "text": self.text, + "status": self.status, + "created": self.created, + } + if self.reminder is not None: + data["reminder"] = self.reminder.to_dict() + return data + + @classmethod + def from_dict(cls, data: dict) -> TodoItem: + reminder = data.get("reminder") + return cls( + id=data.get("id") or _new_id(), + text=data["text"], + status=data.get("status", STATUS_NEEDS_ACTION), + created=data.get("created", 0.0), + reminder=Reminder.from_dict(reminder) if reminder else None, + ) + + @property + def is_completed(self) -> bool: + return self.status == STATUS_COMPLETED + + +class TodoStore: + """In-memory todo list with persistent-friendly dict serialization. + + Items keep insertion order. "Display order" (used by the `todo` command + and by positional references) is open items first, then completed ones. + """ + + def __init__(self, items: list[TodoItem] | None = None) -> None: + self._items: list[TodoItem] = list(items or []) + + # -- serialization --------------------------------------------------- + + def to_dict(self) -> dict: + return {"version": 1, "items": [i.to_dict() for i in self._items]} + + @classmethod + def from_dict(cls, data: dict | None) -> TodoStore: + if not data: + return cls() + items = [] + for raw in data.get("items", []): + if not isinstance(raw, dict): + continue + try: + items.append(TodoItem.from_dict(raw)) + except (KeyError, TypeError): + continue + return cls(items) + + # -- queries ---------------------------------------------------------- + + @property + def items(self) -> list[TodoItem]: + """All items in stored order.""" + return list(self._items) + + def ordered(self) -> list[TodoItem]: + """Display order: open items first, then completed ones.""" + return [i for i in self._items if not i.is_completed] + [ + i for i in self._items if i.is_completed + ] + + def get(self, item_id: str) -> TodoItem | None: + return next((i for i in self._items if i.id == item_id), None) + + def pending_reminders(self) -> list[tuple[TodoItem, Reminder]]: + """All items with a reminder set (fired reminders are cleared).""" + return [ + (i, i.reminder) for i in self._items if i.reminder is not None + ] + + # -- mutations ---------------------------------------------------------- + + def add(self, text: str, created: float = 0.0) -> TodoItem: + item = TodoItem(id=_new_id(), text=text, created=created) + self._items.append(item) + return item + + def remove(self, item: TodoItem) -> None: + self._items.remove(item) + + def complete(self, item: TodoItem) -> None: + item.status = STATUS_COMPLETED + + def reopen(self, item: TodoItem) -> None: + item.status = STATUS_NEEDS_ACTION + + def set_reminder(self, item: TodoItem, reminder: Reminder) -> None: + item.reminder = reminder + + def clear_reminder(self, item: TodoItem) -> None: + item.reminder = None + + # -- reference resolution ---------------------------------------------- + + def resolve(self, ref: str) -> TodoItem | None: + """Resolve a user reference: a 1-based display number or text prefix. + + Text matching is case-insensitive and matches on unique prefix. + Returns None when ambiguous or not found. + """ + ref = ref.strip() + if not ref: + return None + if ref.isdigit(): + ordered = self.ordered() + pos = int(ref) + if 1 <= pos <= len(ordered): + return ordered[pos - 1] + return None + needle = ref.lower() + matches = [ + i for i in self._items if i.text.lower().startswith(needle) + ] + if len(matches) == 1: + return matches[0] + return None diff --git a/custom_components/meshcore_agent/core/timeparse.py b/custom_components/meshcore_agent/core/timeparse.py new file mode 100644 index 0000000..bb78b40 --- /dev/null +++ b/custom_components/meshcore_agent/core/timeparse.py @@ -0,0 +1,123 @@ +"""Pure-Python reminder time parsing. + +`parse_when` understands: + +- ``in 30m``, ``in 2h``, ``in 1h30m``, ``in 1d12h`` (relative offsets) +- ``14:30`` (next occurrence of a clock time, today or tomorrow) +- ``today 14:30`` / ``tomorrow 09:00`` +- ``monday 08:00`` ... ``sunday 22:00`` (next occurrence of a weekday) +- ``2026-12-24`` / ``2026-12-24 14:30`` (absolute date, optional time) + +All inputs use an aware ``now`` datetime (the Home Assistant local time); +the returned datetime is aware and always strictly in the future. +""" + +from __future__ import annotations + +import re +from datetime import datetime, timedelta + +_WEEKDAYS = { + "monday": 0, + "tuesday": 1, + "wednesday": 2, + "thursday": 3, + "friday": 4, + "saturday": 5, + "sunday": 6, +} + +_UNITS = {"s": "seconds", "m": "minutes", "h": "hours", "d": "days"} + +_IN_RE = re.compile( + r"^in\s+((?:\d+\s*[smhd]\s*)+)$", re.IGNORECASE +) +_CLOCK_RE = re.compile( + r"^(?:today\s+|tomorrow\s+)?(\d{1,2}):(\d{2})$", re.IGNORECASE +) +_ABSOLUTE_RE = re.compile( + r"^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{1,2}):(\d{2}))?$" +) +_WEEKDAY_RE = re.compile( + r"^(" + "|".join(_WEEKDAYS) + r")\s+(\d{1,2}):(\d{2})$", + re.IGNORECASE, +) + + +class TimeParseError(ValueError): + """Raised when a reminder time cannot be parsed.""" + + +def _clock_time(now: datetime, hour: int, minute: int, *, day_offset: int = 0) -> datetime: + candidate = (now + timedelta(days=day_offset)).replace( + hour=hour, minute=minute, second=0, microsecond=0 + ) + return candidate + + +def parse_when(text: str, now: datetime) -> datetime: + """Parse a reminder time description into a future aware datetime.""" + if not now.tzinfo: + raise ValueError("now must be timezone-aware") + text = text.strip().lower() + if not text: + raise TimeParseError("empty time") + + match = _IN_RE.match(text) + if match: + seconds = 0 + for value, unit in re.findall(r"(\d+)\s*([smhd])", match.group(1)): + seconds += int(value) * timedelta( + **{_UNITS[unit]: 1} + ).total_seconds() + delta = timedelta(seconds=int(seconds)) + if delta <= timedelta(0): + raise TimeParseError("offset must be positive") + return now + delta + + match = _CLOCK_RE.match(text) + if match: + hour, minute = int(match.group(1)), int(match.group(2)) + if not (0 <= hour < 24 and 0 <= minute < 60): + raise TimeParseError(f"invalid time {hour:02d}:{minute:02d}") + if "tomorrow" in text: + return _clock_time(now, hour, minute, day_offset=1) + if "today" in text: + candidate = _clock_time(now, hour, minute) + if candidate <= now: + raise TimeParseError("today HH:MM has already passed") + return candidate + candidate = _clock_time(now, hour, minute) + if candidate <= now: + candidate = _clock_time(now, hour, minute, day_offset=1) + return candidate + + match = _WEEKDAY_RE.match(text) + if match: + weekday = _WEEKDAYS[match.group(1)] + hour, minute = int(match.group(2)), int(match.group(3)) + if not (0 <= hour < 24 and 0 <= minute < 60): + raise TimeParseError(f"invalid time {hour:02d}:{minute:02d}") + days_ahead = (weekday - now.weekday()) % 7 + candidate = _clock_time(now, hour, minute, day_offset=days_ahead) + if candidate <= now: + candidate = _clock_time(now, hour, minute, day_offset=7) + return candidate + + match = _ABSOLUTE_RE.match(text) + if match: + year, month, day = (int(match.group(i)) for i in (1, 2, 3)) + hour = int(match.group(4) or 9) + minute = int(match.group(5) or 0) + if not (0 <= hour < 24 and 0 <= minute < 60): + raise TimeParseError(f"invalid time {hour:02d}:{minute:02d}") + try: + candidate = now.replace( + year=year, month=month, day=day, + hour=hour, minute=minute, second=0, microsecond=0, + ) + except ValueError as err: + raise TimeParseError(f"invalid date: {err}") from err + return candidate + + raise TimeParseError(f"could not understand time: {text!r}") diff --git a/custom_components/meshcore_agent/manifest.json b/custom_components/meshcore_agent/manifest.json new file mode 100644 index 0000000..7e8026b --- /dev/null +++ b/custom_components/meshcore_agent/manifest.json @@ -0,0 +1,13 @@ +{ + "domain": "meshcore_agent", + "name": "MeshCore Agent", + "codeowners": ["@dejvino"], + "config_flow": true, + "dependencies": ["meshcore", "todo"], + "documentation": "https://github.com/dejvino/meshcore-ha-agent", + "integration_type": "hub", + "iot_class": "local_push", + "issue_tracker": "https://github.com/dejvino/meshcore-ha-agent/issues", + "requirements": [], + "version": "0.1.0" +} diff --git a/custom_components/meshcore_agent/store.py b/custom_components/meshcore_agent/store.py new file mode 100644 index 0000000..0090473 --- /dev/null +++ b/custom_components/meshcore_agent/store.py @@ -0,0 +1,26 @@ +"""Persistence for the MeshCore Agent todo store (Home Assistant layer).""" + +from __future__ import annotations + +from homeassistant.core import HomeAssistant +from homeassistant.helpers.storage import Store + +from .const import DOMAIN +from .core.store import TodoStore + +STORAGE_VERSION = 1 + + +class AgentStore: + """Wraps the pure TodoStore in a Home Assistant storage backend.""" + + def __init__(self, hass: HomeAssistant, entry_id: str) -> None: + self._store = Store(hass, STORAGE_VERSION, f"{DOMAIN}.{entry_id}.todos") + self.todo_store = TodoStore() + + async def async_load(self) -> None: + data = await self._store.async_load() + self.todo_store = TodoStore.from_dict(data) + + async def async_save(self) -> None: + await self._store.async_save(self.todo_store.to_dict()) diff --git a/custom_components/meshcore_agent/strings.json b/custom_components/meshcore_agent/strings.json new file mode 100644 index 0000000..55c2815 --- /dev/null +++ b/custom_components/meshcore_agent/strings.json @@ -0,0 +1,42 @@ +{ + "title": "MeshCore Agent", + "config": { + "step": { + "user": { + "title": "MeshCore Agent", + "description": "Allow MeshCore nodes to talk to the agent. The allowlist accepts public key prefixes or contact names, separated by commas.", + "data": { + "allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", + "allow_all": "Allow all senders (not recommended)", + "max_reply": "Maximum reply length (characters)" + } + } + }, + "error": { + "invalid_max_reply": "Maximum reply length must be a number between 20 and 500." + } + }, + "options": { + "step": { + "init": { + "title": "MeshCore Agent options", + "description": "Allow MeshCore nodes to talk to the agent. The allowlist accepts public key prefixes or contact names, separated by commas.", + "data": { + "allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", + "allow_all": "Allow all senders (not recommended)", + "max_reply": "Maximum reply length (characters)" + } + } + }, + "error": { + "invalid_max_reply": "Maximum reply length must be a number between 20 and 500." + } + }, + "entity": { + "todo": { + "todos": { + "name": "MeshCore todos" + } + } + } +} diff --git a/custom_components/meshcore_agent/todo.py b/custom_components/meshcore_agent/todo.py new file mode 100644 index 0000000..4bb5405 --- /dev/null +++ b/custom_components/meshcore_agent/todo.py @@ -0,0 +1,115 @@ +"""Todo platform: exposes the mesh todo list as a Home Assistant todo list. + +The same items reachable over the mesh (`todo add`, `todo done`, ...) +appear in the Home Assistant UI and can be edited from there too. +""" + +from __future__ import annotations + +from homeassistant.components.todo import ( + TodoItem, + TodoItemStatus, + TodoListEntity, + TodoListEntityFeature, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.dispatcher import ( + async_dispatcher_connect, +) +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.util import dt as dt_util + +from . import MeshCoreAgent +from .const import DOMAIN, SIGNAL_STORE_UPDATED +from .core.store import TodoItem as CoreTodoItem + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + agent: MeshCoreAgent = hass.data[DOMAIN][entry.entry_id] + async_add_entities([MeshCoreTodoList(agent, entry)]) + + +def _to_ha_item(core_item: CoreTodoItem) -> TodoItem: + due = None + if core_item.reminder is not None: + due = dt_util.parse_datetime(core_item.reminder.at) + return TodoItem( + uid=core_item.id, + item=core_item.text, + status=( + TodoItemStatus.COMPLETED + if core_item.is_completed + else TodoItemStatus.NEEDS_ACTION + ), + due=due, + ) + + +class MeshCoreTodoList(TodoListEntity): + """A todo list backed by the mesh agent's store.""" + + _attr_has_entity_name = True + _attr_translation_key = "todos" + _attr_supported_features = ( + TodoListEntityFeature.CREATE_TODO_ITEM + | TodoListEntityFeature.UPDATE_TODO_ITEM + | TodoListEntityFeature.DELETE_TODO_ITEM + ) + + def __init__(self, agent: MeshCoreAgent, entry: ConfigEntry) -> None: + self._agent = agent + self._entry = entry + self._attr_unique_id = entry.entry_id + self._attr_device_info = DeviceInfo( + identifiers={(DOMAIN, entry.entry_id)}, + name=entry.title, + ) + + async def async_added_to_hass(self) -> None: + self.async_on_remove( + async_dispatcher_connect( + self.hass, + SIGNAL_STORE_UPDATED.format(entry_id=self._entry.entry_id), + self._store_updated, + ) + ) + + @callback + def _store_updated(self) -> None: + self.async_write_ha_state() + + @property + def todo_items(self) -> list[TodoItem]: + return [_to_ha_item(i) for i in self._agent.todo_store.ordered()] + + async def async_create_item(self, item: TodoItem) -> None: + self._agent.todo_store.add(item.item) + await self._agent.async_persist() + + async def async_update_item(self, item: TodoItem) -> None: + if item.uid is None: + return + core_item = self._agent.todo_store.get(item.uid) + if core_item is None: + return + if item.item is not None: + core_item.text = item.item + if item.status is not None: + if item.status == TodoItemStatus.COMPLETED: + self._agent.todo_store.complete(core_item) + else: + self._agent.todo_store.reopen(core_item) + await self._agent.async_persist() + + async def async_delete_items(self, uids: list[str]) -> None: + for uid in uids: + core_item = self._agent.todo_store.get(uid) + if core_item is not None: + self._agent.todo_store.remove(core_item) + await self._agent.async_persist() diff --git a/custom_components/meshcore_agent/translations/en.json b/custom_components/meshcore_agent/translations/en.json new file mode 100644 index 0000000..55c2815 --- /dev/null +++ b/custom_components/meshcore_agent/translations/en.json @@ -0,0 +1,42 @@ +{ + "title": "MeshCore Agent", + "config": { + "step": { + "user": { + "title": "MeshCore Agent", + "description": "Allow MeshCore nodes to talk to the agent. The allowlist accepts public key prefixes or contact names, separated by commas.", + "data": { + "allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", + "allow_all": "Allow all senders (not recommended)", + "max_reply": "Maximum reply length (characters)" + } + } + }, + "error": { + "invalid_max_reply": "Maximum reply length must be a number between 20 and 500." + } + }, + "options": { + "step": { + "init": { + "title": "MeshCore Agent options", + "description": "Allow MeshCore nodes to talk to the agent. The allowlist accepts public key prefixes or contact names, separated by commas.", + "data": { + "allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", + "allow_all": "Allow all senders (not recommended)", + "max_reply": "Maximum reply length (characters)" + } + } + }, + "error": { + "invalid_max_reply": "Maximum reply length must be a number between 20 and 500." + } + }, + "entity": { + "todo": { + "todos": { + "name": "MeshCore todos" + } + } + } +} diff --git a/hacs.json b/hacs.json new file mode 100644 index 0000000..eb11b69 --- /dev/null +++ b/hacs.json @@ -0,0 +1,5 @@ +{ + "name": "MeshCore Agent", + "render_readme": true, + "homeassistant": "2025.6.0" +} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..729eef7 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,9 @@ +[project] +name = "meshcore-ha-agent" +version = "0.1.0" +description = "A MeshCore mesh agent for Home Assistant: todo and reminder commands over the mesh" +requires-python = ">=3.12" + +[tool.pytest.ini_options] +testpaths = ["tests"] +asyncio_mode = "auto" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..e1de64d --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,6 @@ +"""Make the repository root importable so tests can load custom_components.""" + +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) diff --git a/tests/test_adapter.py b/tests/test_adapter.py new file mode 100644 index 0000000..9c9ece4 --- /dev/null +++ b/tests/test_adapter.py @@ -0,0 +1,38 @@ +"""Tests for the HA-independent parts of the adapter (truncation, targets).""" + +from custom_components.meshcore_agent import target_from_event, truncate +from custom_components.meshcore_agent.core.store import Reminder + + +def test_truncate_short_untouched(): + assert truncate("hello", 200) == "hello" + + +def test_truncate_long(): + text = "a" * 300 + out = truncate(text, 200) + assert len(out) == 200 + assert out.endswith("...") + + +def test_truncate_prefers_newline(): + text = "line one\n" + "b" * 300 + out = truncate(text, 200) + assert out == "line one..." + + +def test_target_direct(): + event = {"message_type": "direct", "pubkey_prefix": "abc123def456"} + assert target_from_event(event) == Reminder( + at="", kind="direct", target="abc123def456" + ) + + +def test_target_channel(): + event = {"message_type": "channel", "channel_idx": 2} + assert target_from_event(event) == Reminder(at="", kind="channel", target="2") + + +def test_target_missing(): + assert target_from_event({"message_type": "direct"}) is None + assert target_from_event({"message_type": "channel"}) is None diff --git a/tests/test_agent_flow.py b/tests/test_agent_flow.py new file mode 100644 index 0000000..d74b565 --- /dev/null +++ b/tests/test_agent_flow.py @@ -0,0 +1,251 @@ +"""End-to-end tests of the adapter: meshcore_message event -> reply service call. + +Uses small stubs for hass/config entry/storage so the real event handling, +allowlist, reply routing and reminder firing paths run without a full HA. +""" + +import asyncio +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace + +import pytest +from homeassistant.core import Event +from homeassistant.util import dt as dt_util + +from custom_components.meshcore_agent import MeshCoreAgent +from custom_components.meshcore_agent.core.store import TodoStore + +UTC = timezone.utc + + +class FakeBus: + def __init__(self): + self.listeners = [] + + def async_listen(self, event_type, callback): + self.listeners.append((event_type, callback)) + return lambda: None + + +class FakeServices: + def __init__(self): + self.calls = [] + + async def async_call(self, domain, service, data, blocking=False): + self.calls.append((domain, service, data)) + + +class FakeHass: + def __init__(self): + self.bus = FakeBus() + self.services = FakeServices() + self.data = {} + self.loop = asyncio.get_running_loop() + + def async_create_task(self, coro): + return asyncio.get_running_loop().create_task(coro) + + def verify_event_loop_thread(self, *_args, **_kwargs): + """Stub for homeassistant.helpers.dispatcher.""" + + +class FakeAgentStore: + def __init__(self): + self.todo_store = TodoStore() + self.saved = 0 + + async def async_save(self): + self.saved += 1 + + +def make_event(data): + return Event("meshcore_message", data) + + +@pytest.fixture(autouse=True) +def _utc_tz(): + previous = None + try: + previous = dt_util.get_default_time_zone() + except ValueError: + pass + dt_util.set_default_time_zone(UTC) + yield + if previous is not None: + dt_util.set_default_time_zone(previous) + + +def make_agent(allowlist="aabbcc,10bb", allow_all=False, data=None, options=None): + hass = FakeHass() + entry = SimpleNamespace( + entry_id="test_entry", + title="Agent", + data=data + if data is not None + else {"allowlist": allowlist, "allow_all": allow_all}, + options=options if options is not None else {}, + ) + agent_store = FakeAgentStore() + agent = MeshCoreAgent(hass, entry, agent_store) + return agent, hass + + +async def deliver(agent, data): + await agent._handle_event(make_event(data)) + + +async def test_direct_message_roundtrip(): + agent, hass = make_agent() + await deliver( + agent, + { + "message_type": "direct", + "outgoing": False, + "pubkey_prefix": "aabbcc", + "sender_name": "Phone", + "message": "todo add Buy milk", + }, + ) + assert hass.services.calls == [ + ("meshcore", "send_message", {"pubkey_prefix": "aabbcc", "message": "Added #1: Buy milk"}) + ] + assert agent.todo_store.items[0].text == "Buy milk" + assert agent.agent_store.saved == 1 + + +async def test_ignores_outgoing_and_non_allowlisted(): + agent, hass = make_agent() + await deliver( + agent, + {"message_type": "direct", "outgoing": True, "pubkey_prefix": "aabbcc", "message": "todo"}, + ) + await deliver( + agent, + {"message_type": "direct", "outgoing": False, "pubkey_prefix": "ffff00", "message": "todo"}, + ) + await deliver( + agent, + {"message_type": "direct", "outgoing": False, "pubkey_prefix": "aabbcc", "message": "hello"}, + ) + assert hass.services.calls == [] + assert agent.todo_store.items == [] + + +async def test_allow_all_option(): + agent, hass = make_agent(allow_all=True) + await deliver( + agent, + {"message_type": "direct", "pubkey_prefix": "ffff00", "message": "todo"}, + ) + assert len(hass.services.calls) == 1 + assert "No todos" in hass.services.calls[0][2]["message"] + + +async def test_channel_message_replies_to_channel(): + agent, hass = make_agent(allowlist="groupchat") + await deliver( + agent, + { + "message_type": "channel", + "channel_idx": 1, + "sender_name": "groupchat", + "message": "agent todo add From channel", + }, + ) + assert hass.services.calls == [ + ("meshcore", "send_channel_message", {"channel_idx": 1, "message": "Added #1: From channel"}) + ] + # The reminder target from a channel message is the channel itself. + await deliver( + agent, + { + "message_type": "channel", + "channel_idx": 1, + "sender_name": "groupchat", + "message": "remind 1 in 30m", + }, + ) + reminder = agent.todo_store.items[0].reminder + assert reminder.kind == "channel" + assert reminder.target == "1" + + +async def test_reminder_firing(): + agent, hass = make_agent() + await deliver( + agent, + { + "message_type": "direct", + "pubkey_prefix": "aabbcc", + "message": "todo add Buy milk", + }, + ) + await deliver( + agent, + { + "message_type": "direct", + "pubkey_prefix": "aabbcc", + "message": "remind 1 in 1h", + }, + ) + item = agent.todo_store.items[0] + from custom_components.meshcore_agent.core.store import Reminder + + # Simulate the scheduler reaching the reminder time. + agent.todo_store.set_reminder( + item, + Reminder(at=(dt_util.now() - timedelta(seconds=1)).isoformat(), kind="direct", target="aabbcc"), + ) + hass.services.calls.clear() + await agent._fire_reminder(item.id) + assert hass.services.calls == [ + ("meshcore", "send_message", {"pubkey_prefix": "aabbcc", "message": "Reminder: Buy milk"}) + ] + assert item.reminder is None + + +async def test_reminder_scheduling_starts_and_cancels(): + agent, hass = make_agent() + await deliver( + agent, + { + "message_type": "direct", + "pubkey_prefix": "aabbcc", + "message": "todo add Buy milk", + }, + ) + await deliver( + agent, + { + "message_type": "direct", + "pubkey_prefix": "aabbcc", + "message": "remind 1 in 1h", + }, + ) + assert set(agent._reminder_unsubs) == {agent.todo_store.items[0].id} + + # Clearing the reminder removes the scheduled job. + await deliver( + agent, + { + "message_type": "direct", + "pubkey_prefix": "aabbcc", + "message": "remind off 1", + }, + ) + assert agent._reminder_unsubs == {} + + +async def test_long_reply_is_truncated(): + agent, hass = make_agent() + await deliver( + agent, + { + "message_type": "direct", + "pubkey_prefix": "aabbcc", + "message": "todo add " + "x " * 100, + }, + ) + reply = hass.services.calls[0][2]["message"] + assert len(reply) <= 200 + assert reply.endswith("...") diff --git a/tests/test_commands.py b/tests/test_commands.py new file mode 100644 index 0000000..3febd6f --- /dev/null +++ b/tests/test_commands.py @@ -0,0 +1,191 @@ +"""Tests for the command registry (the todo feature over mesh messages).""" + +from datetime import datetime, timedelta, timezone + +from custom_components.meshcore_agent.core.commands import ( + Context, + handle_message, +) +from custom_components.meshcore_agent.core.store import Reminder, TodoStore + +NOW = datetime(2026, 12, 1, 10, 0, 0, tzinfo=timezone.utc) + + +def make_ctx(*texts, target=None): + return Context(store=TodoStore(), now=NOW, target=target) + + +def populate(ctx: Context): + for text in ("Buy milk", "Fix antenna", "Water plants"): + ctx.store.add(text) + + +def test_non_command_messages_are_ignored(): + ctx = make_ctx() + assert handle_message("hey, how are you?", ctx) is None + assert handle_message("", ctx) is None + assert handle_message(" ", ctx) is None + + +def test_todo_list_empty(): + ctx = make_ctx() + assert "No todos" in handle_message("todo", ctx) + + +def test_todo_list_shows_items(): + ctx = make_ctx() + populate(ctx) + reply = handle_message("todo", ctx) + assert reply.splitlines() == [ + "1. [ ] Buy milk", + "2. [ ] Fix antenna", + "3. [ ] Water plants", + ] + + +def test_todo_list_marks_completed_and_reminders(): + ctx = make_ctx() + populate(ctx) + ctx.store.complete(ctx.store.items[1]) + ctx.store.set_reminder( + ctx.store.items[0], + Reminder(at="2026-12-02T10:00:00+00:00", kind="direct", target="ab"), + ) + reply = handle_message("todo", ctx) + assert reply.splitlines() == [ + "1. [ ] Buy milk - Wed 02 Dec 10:00", + "2. [ ] Water plants", + "3. [x] Fix antenna", + ] + + +def test_todo_add(): + ctx = make_ctx() + assert handle_message("todo add Buy milk", ctx) == "Added #1: Buy milk" + assert handle_message("todo add Fix antenna ", ctx) == "Added #2: Fix antenna" + assert [i.text for i in ctx.store.items] == ["Buy milk", "Fix antenna"] + + +def test_todo_add_usage(): + ctx = make_ctx() + assert "Usage" in handle_message("todo add", ctx) + + +def test_todo_done_by_number_and_text(): + ctx = make_ctx() + populate(ctx) + assert handle_message("todo done 2", ctx) == "Done: Fix antenna" + assert ctx.store.items[1].is_completed + assert handle_message("todo done buy m", ctx) == "Done: Buy milk" + # Numbers now refer to the new display order (open items first). + assert handle_message("todo done 2", ctx) == "Already done: Buy milk" + assert handle_message("todo done 1", ctx) == "Done: Water plants" + + +def test_todo_done_by_full_text(): + ctx = make_ctx() + populate(ctx) + assert handle_message("todo done fix antenna", ctx) == "Done: Fix antenna" + + +def test_todo_done_missing(): + ctx = make_ctx() + populate(ctx) + assert "No todo matches" in handle_message("todo done 99", ctx) + ctx.store.add("Buy bread") # makes the "buy" prefix ambiguous + assert "No todo matches" in handle_message("todo done buy", ctx) # ambiguous + assert "Missing todo number" in handle_message("todo done", ctx) + + +def test_todo_uncheck(): + ctx = make_ctx() + populate(ctx) + handle_message("todo done 1", ctx) + # Buy milk is now the third item in display order (open items first). + assert handle_message("todo uncheck 3", ctx) == "Reopened: Buy milk" + assert handle_message("todo uncheck buy", ctx) == "Not done yet: Buy milk" + + +def test_todo_remove(): + ctx = make_ctx() + populate(ctx) + assert handle_message("todo remove 2", ctx) == "Removed: Fix antenna" + assert [i.text for i in ctx.store.items] == ["Buy milk", "Water plants"] + assert handle_message("todo rm 1", ctx) == "Removed: Buy milk" + + +def test_remind_by_number_relative(): + ctx = make_ctx() + populate(ctx) + reply = handle_message("remind 1 in 30m", ctx) + assert "Reminder set for #1 (Buy milk)" in reply + expected = NOW + timedelta(minutes=30) + assert ctx.store.items[0].reminder is not None + parsed = datetime.fromisoformat(ctx.store.items[0].reminder.at) + assert parsed == expected + + +def test_remind_by_text_prefix(): + ctx = make_ctx() + populate(ctx) + reply = handle_message("remind water plants tomorrow 09:00", ctx) + assert "Reminder set for #3 (Water plants)" in reply + parsed = datetime.fromisoformat(ctx.store.items[2].reminder.at) + assert parsed == (NOW + timedelta(days=1)).replace(hour=9) + + +def test_remind_stores_target(): + target = Reminder(at="", kind="direct", target="aabbcc") + ctx = make_ctx(target=target) + populate(ctx) + handle_message("remind 1 in 1h", ctx) + reminder = ctx.store.items[0].reminder + assert reminder.kind == "direct" + assert reminder.target == "aabbcc" + + +def test_remind_off(): + ctx = make_ctx() + populate(ctx) + handle_message("remind 1 in 1h", ctx) + assert handle_message("remind off 1", ctx) == "Reminder cleared: Buy milk" + assert ctx.store.items[0].reminder is None + assert handle_message("remind off 1", ctx) == "No reminder set: Buy milk" + + +def test_remind_usage_errors(): + ctx = make_ctx() + populate(ctx) + assert "Usage" in handle_message("remind", ctx) + assert "Usage" in handle_message("remind 1", ctx) # no when + assert "Bad time" in handle_message("remind 1 gibberish", ctx) + assert "No todo matches" in handle_message("remind 9 in 30m", ctx) + + +def test_help(): + ctx = make_ctx() + assert handle_message("help", ctx) == handle_message("help", make_ctx()) + assert "todo" in handle_message("help", ctx).lower() + + +def test_wake_word_prefix(): + ctx = make_ctx() + populate(ctx) + assert "Buy milk" in handle_message("agent todo", ctx) + assert "Buy milk" in handle_message("bot, todo", ctx) + assert "Usage" in handle_message("agent remind 1", ctx) + + +def test_alias_commands(): + ctx = make_ctx() + populate(ctx) + assert handle_message("todos", ctx) == handle_message("todo", ctx) + assert handle_message("done 1", ctx) == "Done: Buy milk" + # After done 1, Fix antenna is #1 in display order. + assert handle_message("rm 1", ctx) == "Removed: Fix antenna" + assert "Added #2" in handle_message("add New item", ctx) + + +def test_unknown_todo_subcommand(): + ctx = make_ctx() + assert "Unknown todo command" in handle_message("todo zap", ctx) diff --git a/tests/test_store.py b/tests/test_store.py new file mode 100644 index 0000000..918922c --- /dev/null +++ b/tests/test_store.py @@ -0,0 +1,102 @@ +"""Tests for the pure todo store.""" + +from custom_components.meshcore_agent.core.store import ( + Reminder, + TodoStore, +) + + +def make_store(*texts): + store = TodoStore() + for text in texts: + store.add(text) + return store + + +def test_add_and_list(): + store = make_store("Buy milk", "Fix antenna") + assert [i.text for i in store.items] == ["Buy milk", "Fix antenna"] + assert all(not i.is_completed for i in store.items) + + +def test_display_order_open_first(): + store = make_store("One", "Two", "Three") + one, two, three = store.items + store.complete(two) + assert [i.text for i in store.ordered()] == ["One", "Three", "Two"] + + +def test_resolve_by_number(): + store = make_store("One", "Two", "Three") + store.complete(store.items[0]) + assert store.resolve("1").text == "Two" + assert store.resolve("3").text == "One" + assert store.resolve("0") is None + assert store.resolve("9") is None + + +def test_resolve_by_text_prefix(): + store = make_store("Buy milk", "Buy bread", "Fix antenna") + assert store.resolve("fix").text == "Fix antenna" + assert store.resolve("BUY MILK").text == "Buy milk" + # Ambiguous prefix resolves to nothing. + assert store.resolve("buy") is None + assert store.resolve("nope") is None + + +def test_complete_reopen_remove(): + store = make_store("One", "Two") + one, two = store.items + store.complete(one) + assert one.is_completed + store.reopen(one) + assert not one.is_completed + store.remove(two) + assert [i.text for i in store.items] == ["One"] + + +def test_roundtrip_serialization(): + store = make_store("Buy milk", "Fix antenna") + store.complete(store.items[1]) + store.set_reminder( + store.items[0], Reminder(at="2026-12-02T10:00:00+01:00", kind="direct", target="ab12cd") + ) + restored = TodoStore.from_dict(store.to_dict()) + assert [i.text for i in restored.items] == ["Buy milk", "Fix antenna"] + assert restored.items[1].is_completed + assert restored.items[0].reminder is not None + assert restored.items[0].reminder.target == "ab12cd" + assert restored.items[0].reminder.kind == "direct" + + +def test_from_dict_tolerates_bad_rows(): + data = { + "version": 1, + "items": [ + {"text": "Good", "id": "a1", "status": "needs_action", "created": 0}, + {"no_text": True}, + "not-a-dict", + ], + } + store = TodoStore.from_dict(data) + assert [i.text for i in store.items] == ["Good"] + + +def test_from_dict_empty(): + assert TodoStore.from_dict(None).items == [] + assert TodoStore.from_dict({}).items == [] + + +def test_reminders_and_clearing(): + store = make_store("One", "Two") + store.set_reminder( + store.items[0], + Reminder(at="2026-12-02T10:00:00+01:00", kind="channel", target="0"), + ) + pending = store.pending_reminders() + assert len(pending) == 1 + item, reminder = pending[0] + assert item.text == "One" + assert reminder.kind == "channel" + store.clear_reminder(item) + assert store.pending_reminders() == [] diff --git a/tests/test_timeparse.py b/tests/test_timeparse.py new file mode 100644 index 0000000..bb4131e --- /dev/null +++ b/tests/test_timeparse.py @@ -0,0 +1,77 @@ +"""Tests for reminder time parsing.""" + +from datetime import datetime, timedelta, timezone + +import pytest + +from custom_components.meshcore_agent.core.timeparse import ( + TimeParseError, + parse_when, +) + +NOW = datetime(2026, 12, 1, 10, 0, 0, tzinfo=timezone.utc) # a Tuesday + + +def assert_future(value: datetime): + assert value > NOW + + +def test_relative_minutes_hours_days(): + assert parse_when("in 30m", NOW) == NOW + timedelta(minutes=30) + assert parse_when("in 2h", NOW) == NOW + timedelta(hours=2) + assert parse_when("in 1d", NOW) == NOW + timedelta(days=1) + assert parse_when("in 1h30m", NOW) == NOW + timedelta(hours=1, minutes=30) + assert parse_when("In 45 M", NOW) == NOW + timedelta(minutes=45) + + +def test_relative_rejects_zero(): + with pytest.raises(TimeParseError): + parse_when("in 0m", NOW) + + +def test_clock_time_same_day(): + assert parse_when("14:30", NOW) == NOW.replace(hour=14, minute=30) + assert parse_when("today 14:30", NOW) == NOW.replace(hour=14, minute=30) + with pytest.raises(TimeParseError): + parse_when("today 09:15", NOW) # already passed + + +def test_clock_time_rolls_to_tomorrow(): + assert parse_when("09:00", NOW) == (NOW + timedelta(days=1)).replace(hour=9) + assert parse_when("tomorrow 09:00", NOW) == (NOW + timedelta(days=1)).replace(hour=9) + # tomorrow always rolls even if the time already passed today + assert parse_when("tomorrow 11:00", NOW) == (NOW + timedelta(days=1)).replace(hour=11) + + +def test_weekday(): + # Now is Tuesday; monday is next Monday. + expected = (NOW + timedelta(days=6)).replace(hour=8) + assert parse_when("monday 08:00", NOW) == expected + # Friday is later this week. + assert parse_when("friday 18:00", NOW) == (NOW + timedelta(days=3)).replace(hour=18) + # Tuesday same day, later hour. + assert parse_when("tuesday 12:00", NOW) == NOW.replace(hour=12) + # Tuesday same hour rolls a week ahead. + assert parse_when("tuesday 10:00", NOW) == (NOW + timedelta(days=7)).replace(hour=10) + + +def test_absolute_date(): + assert parse_when("2026-12-24 14:30", NOW) == datetime( + 2026, 12, 24, 14, 30, tzinfo=timezone.utc + ) + # Date without time defaults to 09:00. + assert parse_when("2026-12-24", NOW) == datetime( + 2026, 12, 24, 9, 0, tzinfo=timezone.utc + ) + + +def test_invalid_inputs(): + for bad in ("", "gibberish", "in ", "25:00", "tomorrow 24:30", "2026-13-01", "2026-02-30 10:00"): + with pytest.raises((TimeParseError, ValueError)): + parse_when(bad, NOW) + + +def test_requires_aware_now(): + naive = datetime(2026, 12, 1, 10, 0) + with pytest.raises(ValueError): + parse_when("in 30m", naive)