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 <n> <when> / remind off <n> (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
This commit is contained in:
@@ -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()
|
||||
@@ -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)
|
||||
@@ -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"
|
||||
@@ -0,0 +1 @@
|
||||
"""Pure-Python core of the MeshCore Agent (no Home Assistant imports)."""
|
||||
@@ -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 <text>`` add a todo
|
||||
- ``todo done <n>`` check a todo off
|
||||
- ``todo uncheck <n>`` reopen a todo
|
||||
- ``todo remove <n>`` remove a todo
|
||||
- ``remind <n> <when>`` set a reminder for a todo
|
||||
- ``remind off <n>`` clear a todo's reminder
|
||||
- ``help`` command overview
|
||||
|
||||
``<n>`` is the 1-based number shown by ``todo``, or a unique text prefix
|
||||
of the item. ``<when>`` 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 <text> | todo done <n> | "
|
||||
"todo uncheck <n> | todo remove <n> | remind <n> <when> | "
|
||||
"remind off <n> | help. <when>: 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 <text>"
|
||||
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 <text>"
|
||||
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 <n> <when> (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 <n> <when> (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 <text>"),
|
||||
"done": Command("done", handle_todo_done, "done <n>"),
|
||||
"uncheck": Command("uncheck", handle_todo_uncheck, "uncheck <n>"),
|
||||
"remove": Command("remove", handle_todo_remove, "remove <n>"),
|
||||
"rm": Command("rm", handle_todo_remove, "rm <n>"),
|
||||
"remind": Command("remind", handle_remind, "remind <n> <when>"),
|
||||
}
|
||||
|
||||
|
||||
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)
|
||||
@@ -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
|
||||
@@ -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}")
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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())
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user