Documentation / LemmeSee Hub

Writing a LemmeSee plugin

A plugin is one Python file in the hub's plugins directory (config.json → plugins_path). The file name is the plugin's permanent id: it names its permissions (plugins.<tier>.<name>), its URLs (/plugins/<name>/) and its installs on phones, so pick it once. Use lowercase letters, digits, and underscores, and don't start it with _.

A plugin can keep more code and data in a folder with the same name next to the file (hello.py + hello/); the folder is importable as a package.

Plugins run inside the hub process with the hub's access. Only install plugins you trust.

The demo plugin puts most of this guide in one place: a feed with its own page, a phone control with an action, and a Delivery Screen with a sound and textures. Unzip it into your plugins directory.

A minimal plugin

# hello.py
PLUGIN_NAME        = "Hello"
PLUGIN_DESCRIPTION = "Says hello."
PLUGIN_PAGES       = [{"title": "Hello", "url": "/plugins/hello/", "monitor": True}]

from fastapi.responses import HTMLResponse
from lemmesee import plugin

hub = plugin.Plugin("hello")


async def page():
    return HTMLResponse("<h1>Hello</h1>")


async def start(task_id, cfg):
    hub.route("GET", "/", page)
    news = hub.feed("hello", name="Hello")
    news.push([{"id": "1", "title": "Hi there", "ts": plugin.now_ms()}])
    hub.state("status", label="Status", value="running")
    hub.log("info", "hello started")


async def stop(task_id):
    hub.close()

To run it, add a Plugin Script task for it as described in Installing hub plugins. The task's settings are passed to start as cfg. Starting, stopping, and editing the task calls start and stop again; editing the plugin file reloads it on the next start.

Settings at the top of the file

The hub reads these without running the file, so they must be plain values placed before the first import, def, or class line.

SettingMeaning
PLUGIN_NAMEDisplay name. A task's display_name overrides it when one task uses the plugin.
PLUGIN_DESCRIPTIONOne line shown in the task picker and on phones.
PLUGIN_PRIVATETrue: users need a plugins.private.<name> grant to see the plugin at all. Otherwise everyone sees it unless plugins.public.<name> is revoked from them.
PLUGIN_PAGESPages to list on phones: {"title", "url", "monitor", "icon_url", "description", "access"}. monitor: True puts the page in the Monitor dropdown. See Pages.
PLUGIN_FEED_PAGES{feed_id: url}: show that feed as your page instead of the app's list.
PLUGIN_FEED_LABELTitle for feeds shown through your page, e.g. "Hello: {feed}".
PLUGIN_DASHBOARD_TABTrue: your states get their own tab on the server's Dashboard item.
PLUGIN_URLURL prefix your routes live under when it isn't /plugins/<name>. plugin_runner.mount refuses prefixes outside it.
PLUGIN_BRIDGETrue: your pages may use the app's LkBridge.
PLUGIN_PATHSExtra hub paths your pages load (e.g. ["/images/hello/"]).
PLUGIN_USESOther plugins whose APIs your pages and plugin keys call.
PLUGIN_NETWORKOutside hosts your pages and scripts may reach through the bridge, e.g. ["api.example.com"]; ["*"] for any.
PLUGIN_KEY_PREFIXPrefix for the names of the signing keys and secrets your pages keep on the phone, e.g. "Hello_". These stay on the phone and are separate from the hub's plugin API keys. Without a prefix your pages can't use signing keys or secrets.
PLUGIN_ALLOW_COOKIESYour pages' browser keeps cookies, including third-party ones.
PLUGIN_ALLOW_POPUPSYour pages may open pop-up windows. With cookies, links stay inside the app.
PLUGIN_SETTINGSThe task settings form. See Task settings.

A plugin is listed to phones only while it has an enabled task.

Lifecycle

FunctionRequiredWhen
async start(task_id, cfg)yesThe task starts. Start your work with asyncio.create_task(...) and return; the hub waits at most 60 s.
async stop(task_id)yesThe task stops. Cancel your work and call hub.close().
stop_all()noHub shutdown, once per plugin.
get_pages()noReturns pages computed at run time; replaces PLUGIN_PAGES while the plugin is loaded. Call mqtt.signal_plugins_dirty() when the list changes.
diagnostics()noReturns a dict shown on the hub's Diagnostics page.

Each task gets its own thread and event loop. Several tasks can use the same plugin file; they share the module, so keep per-task data in a dict keyed by task_id.

HTTP handlers run on the hub's own event loop, not your task's. Keep them fast and push slow work to your task.

A plugin that keeps crashing is left stopped; see When a plugin doesn't start.

The lemmesee.plugin API

hub = plugin.Plugin("<name>") registers everything on behalf of your plugin and removes it all on hub.close().

CallDoes
hub.route(method, path, handler, public=False, feature=None)Serves handler at /plugins/<name><path>. Signed-in users only unless public=True; feature="key" requires that permission.
hub.feed(id, name=, private=, description=, icon_url=, also_published_by=)Registers a feed you own and returns it. private=True feeds need a feeds.private.<id> grant.
feed.push(items)Appends events. Each item needs id and ts (milliseconds).
feed.set(items)Replaces the feed's current state, keyed by id.
feed.push_to_user(user_id, items)Items only that user sees.
feed.clear()Empties the feed.
hub.state(name, label=, value=, display="text", alarm=False, interval=0, **extra)Publishes a state. display is one of text, key_value, table, pie, donut, bar_chart, gauge, status_row, sparkline, big_number, progress, countdown, list, timeline, heatmap, image, composite, link.
hub.clear_state(name)Removes a state.
hub.log(level, message, public=False)Logs under your plugin's name: debug, info, important, warning, or error.
hub.topics(patterns)Declares MQTT topics you publish outside your feeds (lemmesee/+/feed/public/hello/#). Readers need access to your plugin.
hub.close()Removes your routes, feeds, and states.
plugin.now_ms()Current time in milliseconds.

Anything beyond this (core.*, modules.*) is hub internals and can change.

Permissions

The hub and the MQTT broker check the same keys.

WhatKeyDefault
Your pluginplugins.<public|private>.<name>follows PLUGIN_PRIVATE
A feedfeeds.<public|private>.<id>follows the feed's private
A statestates.<name>.<state> (or states.<name>.*)needs a grant
A page that shows one record<kind>.<public|private>.<id> from its accessfollows access.private

A request for something a user can't see answers exactly like a request for something that doesn't exist (404), so nothing reveals what exists. Users who can't see your plugin get that 404 from the hub for every route under your paths. For records inside your plugin, check with core.users.can_see(kind, id, private, user) and answer JSONResponse({"detail": "Not Found"}, status_code=404), the same body an unknown route gets.

Pages on the phone

Pages are hub URLs the LemmeKnow app opens in its browser view. The app adds the user's access key to page loads and bridge requests only for your plugin's paths: /plugins/<name>/, /api/<name>/, PLUGIN_URL, PLUGIN_PATHS, the APIs of plugins in PLUGIN_USES, and the shared /api/feeds/, /api/feed/, and /api/users/me.

When a page loads with the access key, the hub also sets a session cookie for your plugin alone (ls_page_<name>), sent only to /plugins/<name>/, /api/<name>/ and PLUGIN_URL and honored only there. With PLUGIN_ALLOW_COOKIES the page's own forms and fetch calls to those paths authenticate with it. Without it the page has no cookies, so send writes through the bridge's hubPost, or hubPostStreamAsync when the response is streamed. A plain fetch POST from the page reaches the hub with no credentials and gets a 401. The hub web UI's session and other plugins' page sessions are never sent from your pages in the app.

A page that shows one record (an app, a camera, a document) declares it:

{"title": "Radarr", "url": "/plugins/hello/radarr/", "monitor": True,
 "access": {"kind": "apps", "id": "radarr", "private": False}}

The hub lists it only to users who pass can_see("apps", "radarr", False, user) and drops access from what it sends.

With PLUGIN_BRIDGE = True your pages get window.LkBridge: storage, signing keys and secrets named under PLUGIN_KEY_PREFIX, rules, hub requests limited to the paths above, and rawFetchAsync / rawPostAsync to PLUGIN_NETWORK hosts. Frames inside your page don't get the bridge; talk to it from your top-level page.

Async bridge calls take a callback id you choose and answer by calling window._lkBridgeCb(id, {ok, status, text}) on your page. For a route that streams its response, such as server-sent events, use hubPostStreamAsync(path, bodyJson, id). It sends the user's access key like hubPostAsync, calls window._lkBridgeChunk(id, line) for each response line as it arrives, then ends with window._lkBridgeCb(id, {ok, status, text}), where text is empty on success and holds the error body otherwise. Lines may be up to 120 seconds apart. Older app versions don't have it, so check LkBridge.hubPostStreamAsync exists and fall back to a non-streamed route through hubPostAsync:

const callbacks = {}, chunkHandlers = {};
window._lkBridgeCb = (id, r) => { const cb = callbacks[id]; delete callbacks[id]; cb?.(r); };
window._lkBridgeChunk = (id, line) => chunkHandlers[id]?.(line);
if (LkBridge.hubPostStreamAsync) {
  chunkHandlers[id] = line => {
    if (line.startsWith('data: ')) showProgress(JSON.parse(line.slice(6)));
  };
  callbacks[id] = r => { delete chunkHandlers[id]; if (!r.ok) showError(r.text); };
  LkBridge.hubPostStreamAsync('/plugins/hello/run/stream', JSON.stringify(body), id);
} else {
  LkBridge.hubPostAsync('/plugins/hello/run', JSON.stringify(body), id);
}

A page can also install your plugin on the phone; see Installing on the phone.

Installing on the phone

A page with the bridge can install your plugin on the phone (Premium), where it works with no hub connection. The user reviews it before anything is installed; Plugins from a hub describes what they see. In that review PLUGIN_NETWORK is shown as Can contact and PLUGIN_USES as Uses data from.

Content (themes, textures, fonts, sounds, and Delivery Screens) uses the same contributes object and hash format as a plugin package; see Building plugin packages and Delivery Screen pages. The phone downloads each declared file from /plugins/<name>/<path>, so serve every one of them there, and icon.png for the plugin's icon.

The other parts are for hub plugins only: a package manifest that declares webviewPage, execScript, or action is refused. A hub plugin passes its page, its action script and the action's settings to the install call instead:

LkBridge.installPluginWithExecAndContent(
  serverId, name, label, url, hash, keyPrefix,
  execUrl, execHash, description, bodyFieldsJson,
  manifestVersion, folderName, includeInBackup, hideManualAction,
  contributesJson)
ArgumentMeaning
serverIdLkBridge.getServerId(). The install must be for the hub the page came from.
nameYour plugin's name. A page can install only its own plugin.
labelThe name users see in the review, the Monitor tab and the System Action list.
url, hashHub path of the page that runs from the phone (e.g. /plugins/hello/local.html) and its hash.
keyPrefix"", or exactly your PLUGIN_KEY_PREFIX. The prefix the hub declares is always the one used.
execUrl, execHashHub path of the action script and its hash, or "" for no action.
descriptionShown in the review.
bodyFieldsJsonThe action's fields as a JSON list of {"key", "default", "help"}. They fill the action editor when a user picks your action.
manifestVersionA string that changes whenever anything other than the two files changes.
folderNameRule folder for the rules your plugin creates. Defaults to label.
includeInBackupfalse leaves the rules your plugin creates out of Export Config files.
hideManualActiontrue keeps your action out of the System Action list, so only the rules your plugin creates run it.
contributesJsonThe contributes object as JSON, or "{}".

The phone counts the plugin as installed while hash, execHash and manifestVersion, joined with :, match its copy. LkBridge.isPluginInstalled(serverId, combined) checks that, and LkBridge.hasPluginInstalled(serverId, name) checks for any version, so a page can offer Install or Update. The outcome arrives as an lk:plugin-installed event on window with {"ok": true} or {"ok": false, "error": "..."}; premium_required and cancelled are the usual errors.

The action script runs when a rule or custom action runs your action. It gets BODY (the action's fields) and TRIGGER, plus Lk.hubGet(path) / Lk.hubPost(path, body) on the same paths as your pages, sent to the hub it was installed from. Set result to report back.

The demo's install.json route returns every argument above, building each hash from the files on disk so they always match what the phone downloads, and its page passes them straight to the install call.

A complete example

demo.py with its demo/ folder in the plugins directory uses all of this: a private feed shown through the plugin's own page (PLUGIN_FEED_PAGES), an install button on that page, an installed control page that works offline, an action that posts to the plugin's /send route (which calls the webhook set in the task settings, keeping its secret on the hub), and a delivery screen with a sound, two textures, and a theme.

Task settings

PLUGIN_SETTINGS builds the form on the task editor and checks values when the task is saved:

PLUGIN_SETTINGS = [
    {"key": "city",     "label": "City",             "default": "Portland", "required": True},
    {"key": "interval", "label": "Check every (s)",  "default": 300},
    {"key": "metric",   "label": "Use metric units", "default": True},
    {"key": "api_key",  "label": "API key",          "type": "secret"},
    {"key": "source",   "label": "Source",           "options": ["noaa", "metno"], "default": "noaa"},
]

type is text, number, bool, secret, or select, inferred from default (or options) when left out. Numbers and booleans arrive converted. A secret field never shows its stored value, and leaving it blank keeps it. Keys you don't declare can still be set in the editor's JSON box.

Testing

  • Your plugin appears in the Script list of a Plugin Script task as soon as the file is in the plugins directory; see Installing hub plugins.
  • The hub's Logs page shows your hub.log lines; its Diagnostics page shows your diagnostics() output, plugins that stopped after repeated crashes, and MQTT topics with no access rule.
  • ?sim=<username> on any hub page shows the hub as that user (read only), which is the quickest way to check who sees what.