Skip to content

Writing packages

A protocol package teaches Connect one clock protocol. Connect handles sockets, storage, delivery, retries and the admin API. Your package says what the clock’s messages mean and how to build the commands it takes. This page walks you through a first package and then covers each part you write. The package reference lists every field. The host API lists every function.

The public example packages repository, hour-advantage-examples, holds two packages to copy from. brightlink/cloud-1.0 is a small example protocol (JSON over MQTT). zk/ is a real vendor with several protocol versions over HTTP (ZKTeco PUSH). Its _types/ folder has editor types for the whole host API (editor support).

Clock sends a message Your systems ask for a standard action its own protocol checked parameters Your package identify which device sent it route match, then handle commands build each payload emit Events stored then the clock gets the reply queued Command queue per device, in order handed out in a reply
A route reads what the clock sent and emits events. Connect stores them before the clock is answered. Commands wait in the device's queue until a route hands them out. The clock's result comes back as another message.

Every message goes through two steps you write. identify names the device from wherever the protocol puts its serial. Then the first route whose match accepts the message runs its handle. handle reads the message, emits events, hands out queued commands and returns the reply.

Commands go the other way. A caller asks for a standard action such as upsert_user. The parameters are checked against what your package declares. Your package builds one or more command payloads, and they wait in the device’s queue. A route hands them out when the clock next calls in. The clock’s result arrives later as a message that a route reports with queue.result.

This walkthrough writes toy-http, a package for a made-up clock that speaks JSON over HTTP. The clock posts punches to /toy/punch, polls /toy/poll for commands, and posts each command’s result to /toy/result. It sends its serial number in an x-toy-serial header.

  1. Make the folders:

    packages/
    toy/
    http-1.0/
    package.toml
    main.lua
    tests/
    01-punch.toml
    02-commands.toml
  2. Write packages/toy/http-1.0/package.toml:

    name = "toy-http"
    version = "1.0.0"
    vendor = "Toy"
    description = "A made-up clock that speaks JSON over HTTP."
    transports = ["http"]
    host_api = 2
  3. Write packages/toy/http-1.0/main.lua:

    local M = {}
    -- The clock sends its serial in a header on every request.
    function M.identify(req)
    return req.headers["x-toy-serial"]
    end
    M.options = {
    { name = "timezone", type = "timezone", required = true,
    description = "The zone the clock's times are in." },
    }
    M.routes = {
    { name = "punch", description = "The clock posts one punch.",
    match = function(req) return req.method == "POST" and req.path == "/toy/punch" end,
    handle = function(req, ctx)
    local ok, p = pcall(json.decode, req.body)
    local at = ok and type(p) == "table" and time.at(ctx.options.timezone, p.at or "") or nil
    if not at then
    emit("unparsed", { reason = "not a punch", raw = req.body }, req.body)
    return "OK"
    end
    emit("punch", {
    user_id = tostring(p.user), local_time = at["local"], utc_offset = at.offset, time = at.time,
    dst_ambiguous = at.ambiguous, time_zone = at.time_zone, zoned = at.zoned,
    state_name = p.dir == "in" and "check_in" or "check_out",
    }, req.body)
    return "OK"
    end },
    { name = "poll", description = "The clock asks for commands.",
    match = function(req) return req.method == "GET" and req.path == "/toy/poll" end,
    handle = function(req, ctx)
    local out, ids = {}, {}
    for _, c in ipairs(queue.pending {}) do
    out[#out + 1] = c.id .. " " .. c.payload
    ids[#ids + 1] = c.id
    end
    queue.mark_sent(ids)
    return table.concat(out, "\n")
    end },
    { name = "result", description = "The clock reports a command's result.",
    match = function(req) return req.method == "POST" and req.path == "/toy/result" end,
    handle = function(req)
    local id, code = string.match(req.body, "^(%d+) (%-?%d+)$")
    if id then queue.result(id, tonumber(code)) end
    return "OK"
    end },
    }
    M.commands = {
    delete_user = {
    title = "Delete user",
    implements = "delete_user",
    params = { "user_id!" },
    build = function(p) return "DEL " .. p.user_id end,
    },
    reboot = {
    title = "Restart",
    implements = "reboot",
    params = {},
    build = function() return "REBOOT" end,
    },
    }
    return M
  4. Write the first scenario, tests/01-punch.toml. The clock posts a punch. The test expects the route that takes it, the reply and the event stored.

    description = "A punch is stored with its time placed in the endpoint's zone"
    [endpoint]
    options = { timezone = "America/Chicago" }
    [[step]]
    method = "POST"
    path = "/toy/punch"
    headers = { "x-toy-serial" = "T1" }
    body = '{"user":1001,"at":"2026-10-01 08:00:00","dir":"in"}'
    [step.expect]
    route = "punch"
    body = "OK"
    events = [{ type = "punch", data = { user_id = "1001", state_name = "check_in", time = "2026-10-01T08:00:00-05:00" } }]
  5. Write the second, tests/02-commands.toml. Two standard actions are queued. The clock collects them on its next poll and reports a result.

    description = "Commands go out on the next poll and complete with the clock's result"
    [endpoint]
    options = { timezone = "UTC" }
    [[step]]
    name = "the clock calls in"
    path = "/toy/poll"
    headers = { "x-toy-serial" = "T1" }
    [step.expect]
    route = "poll"
    status = 200
    body = ""
    [[step]]
    device = "T1"
    action = { name = "reboot" }
    [step.expect]
    payloads = ["REBOOT"]
    [[step]]
    device = "T1"
    action = { name = "delete_user", params = { user_id = "7" } }
    [step.expect]
    payloads = ["DEL 7"]
    [[step]]
    path = "/toy/poll"
    headers = { "x-toy-serial" = "T1" }
    [step.expect]
    body = "{command:1} REBOOT\n{command:2} DEL 7"
    [[step]]
    method = "POST"
    path = "/toy/result"
    headers = { "x-toy-serial" = "T1" }
    body = "{last_command_id} 0"
    [step.expect]
    route = "result"
    events = [{ type = "command.result", data = { ok = true } }, { type = "action.result" }]
  6. Run the scenarios from the folder that holds packages:

    Terminal window
    hourctl pkg test
    ok [email protected] toy\http-1.0\tests\01-punch.toml (1 steps)
    ok [email protected] toy\http-1.0\tests\02-commands.toml (5 steps)
    2 scenarios, 0 failed
    coverage routes commands actions
    [email protected] 3/3 2/2 2/2

    Every route, command and action is covered, so hourctl pkg test exits 0. Leave a step out and it lists what is untested and exits 1.

  7. Print a command’s payload while you work on it:

    Terminal window
    hourctl pkg render toy-http delete_user user_id=7
  8. Build the bundle you push to a gateway:

    Terminal window
    hourctl pkg build packages -o bundles

    Packages covers pushing the bundle. Developing packages runs a package against a real clock.

A folder with package.toml is a package. Any other folder groups packages. Its *.lua files are modules every package beneath it can require:

packages/
zk/ a vendor folder
zk.lua require("zk"): shared by every package below
push-3.4/ a package
package.toml
main.lua
tests/*.toml scenarios
dev/seed.toml people for `hourd dev` (not in the bundle)
push-2.4/
push-2.0/

Keep code that is the same for every version of a protocol in the vendor module. Give each protocol version a package of its own. When two versions differ, each main.lua says how. The vendor module never checks a version. The layout rules list what fails a load.

Callers manage clocks with standard actions: upsert_user, delete_user, set_cards, reboot, wipe and the rest. They have the same parameters on every clock. Offer each one your clocks can do. Do it either as one command (implements = "upsert_user") or as an M.actions entry. An entry expands into steps, and each step is one of your commands. The reference has the rules checked at load.

The steps of an action are queued in order. They go to the device together, in the same batch as far as it allows. No step waits for the answer to the one before it. A device that runs every command it is handed runs every step even after one failed. Steps not yet handed out when a failure is known are skipped. The action reports the first failed step. So:

  • Build steps that are harmless if an earlier one failed. A template for a user that was not added just fails too.
  • Never put a step that destroys what Connect cannot give back after one whose failure should have stopped it. Refuse the action instead (ZK change_user_id refuses unless the templates are given or allow_reenroll = true). Or make the earlier step a gate.
  • Raise an error, in words a caller can act on, for what the device cannot do ("this clock holds one card per user"). Do not do part of what was asked.

upsert_user replaces the user. So send every field the device keeps (with its default when not given), never only the ones given.

A step with gate = true must be answered, and pass, before anything after it goes. Use it where a later step must not run unless an earlier one is known to have worked. For example, add a user, then a gate that asks for the user back and checks it is there, then what depends on it.

The steps before the gate go first. The gate goes on its own. Nothing more is handed to the device until it has answered. The steps after it go once it passes. It passes when the result is a success. That is the command’s success rule, or the route’s own verdict queue.result(id, code, text, ok) for a gate that has to look into what the device sent. A gate that fails or goes unanswered fails the action, drops the steps after it, and holds the device. Nothing more is sent to it until an operator releases it (hourctl device release). Add a gate only where carrying on blind could do harm.

A route sees only a result’s id, not the command’s parameters. A gate that compares what the device answers with what was sent notes what it expects in the device’s store when its commands are handed out. It reads that back where the answer comes in.

A route that reads an answer saying the device is not ready (rebooting, busy) calls queue.retry(id, seconds) instead of queue.result. The same command, with the same id, goes again no earlier than seconds later. It goes again as often as the device asks, until the action expires. A device that polls gets it on its first poll after that time. For example, asked again in 5 seconds by a clock that polls every 15, it goes up to 15 seconds later. A gate that is asked again holds nothing else back meanwhile. The steps after it still wait for it to pass. A command with sensitive parameters cannot go again, because only their size is kept once it went. queue.retry fails it.

wipe leaves the device as a fresh member. People, punches, access and list data are gone. Every network, server and other setting is kept. Build it from the protocol’s own clear commands, one kind of data each. Never use a catch-all that may reset options (a factory reset). Never set an option: no step may write settings. Leave out what the protocol has no command for, and say so in the action’s description. A package that cannot clear its people does not offer wipe.

Not every clock takes every action. M.supports(name, info, kind) answers whether a device takes an action or command, and why not (no face reader, say). It answers from what the device reported about itself. A device’s page in the API and hourctl device actions then list only what it takes.

A package offers what the standard vocabulary has no word for (a firmware upgrade, a vendor diagnostic) as an action of its own. That is an M.actions entry whose name is not a standard action. It goes exactly as a standard action does in steps (ordered steps, gates, queue.retry, the same results and events). It is offered the same way:

  • on the device’s page (available_actions, hourctl device actions);
  • in GET /api/packages/{name} ("standard": false);
  • to POST .../actions by name;
  • to jobs.

It declares its own typed parameters and the sync domains it writes (writes = {} for a device operation):

M.actions = {
firmware_upgrade = {
description = "Loads a firmware image, applies it, and waits for the clock to come back.",
params = {
{ name = "url", type = "string", required = true, description = "Where the clock fetches the image." },
{ name = "sha256", type = "string", required = true, pattern = "^[0-9a-f]{64}$" },
},
writes = {},
expand = function(p)
return {
{ action = "fw_upload", params = { url = p.url, sha256 = p.sha256 } },
-- Nothing after this goes unless the clock took the image.
{ action = "fw_apply", gate = true },
-- The route answering this calls queue.retry(id, 10) while the
-- clock is still rebooting.
{ action = "fw_version" },
}
end,
},
}

Mark its step commands internal = true when they make no sense sent on their own. The ZK packages’ add_user_verified, set_option_verified and reboot_and_wait (ZK) are worked examples. They come with scenarios for a gate that compares, and for one answered with queue.retry until the clock has restarted.

A device key stops another device from posting as one of yours. When a key is registered for a device, Connect compares it with the key identify returned. It refuses a message without the right one (401).

M.set_key(key, ctx) queues the commands that put the key on the device, or take it away (key is nil), with queue.add. Connect calls it when a key is set or cleared. Without it, keys are put on devices by hand.

A protocol that signs messages (an HMAC over the body, an HTTP digest) declares M.verify(req, secret) instead. Connect calls it with the device’s key. While a key is on its way to the device, Connect also calls it with that key. It returns true when the message is signed with it. It returns false when it is not. It returns nil when the message carries no signature:

function M.verify(req, secret)
local sig = req.headers["x-acme-signature"]
if sig == nil then return nil end
return crypto.equals(sig, crypto.hmac_sha256(secret, req.headers["x-acme-timestamp"] .. req.body))
end

The engine keeps facts only: which commands it handed to a device, and which the device answered. It draws no conclusion from the order of answers. Whether a command was missed is the protocol’s to say, so a package that knows says it as it handles a message.

M.missed(req, in_hand, answered) is asked of every message that carries results, and of the requests of the routes the manifest lists in [commands] missed_on, while commands are in the device’s hand. in_hand is the hand in the order it was handed out. Each entry is { id, action, writes }, where writes says whether the command declares what it writes. answered is the ids of the results the message carries. Return true (all of in_hand), a list of ids, or false. A command that is not in the hand is refused.

A clock that works through what it writes in order, and answers in order, is a few lines:

function M.missed(req, in_hand, answered)
local done, last, missed = {}, 0, {}
for _, id in ipairs(answered) do done[id] = true end
for i, c in ipairs(in_hand) do
if done[c.id] then last = i end
end
for i = 1, last - 1 do
local c = in_hand[i]
if c.writes and not done[c.id] then missed[#missed + 1] = c.id end
end
return missed
end

The engine does the rest: a missed command whose action is in [commands] resend is handed out once more, up to resend_times; any other ends unanswered, with its command.unanswered event, and its action fails. A package that never says a command is missed has only the action’s deadline and an app giving up.

A sync group keeps chosen data the same on many clocks. Connect does the syncing. Your package declares in M.sync what its clocks take (id patterns, name lengths, cards, template formats, slot ranges) and what they report. Nothing undeclared is sent to them. A row a clock cannot hold is reported unsupported for that clock. There are two exceptions. A name too long for the clock is cut. Cards past what it holds are left out. Each is listed as omitted. A package without M.sync is never sent anything by a group.

When you fill in M.sync (reference):

  • Give the device’s real limits. Make a limit a function of the device’s info when models differ.
  • For slots, pick the top of the device’s range. Slot 1 is usually a factory default, and installers number their own from the bottom.
  • Share a settings class between packages only when their registries use the same names with the same meanings.
  • Make every action a group sends build the same commands when built again from the same parameters, because a group may send it twice.

Events are a public contract (events). Emit the types and neutral fields documented there. What only your protocol says (a raw code, an extra field) goes under data.vendor.<your vendor>, which the contract leaves to you. Document it with your package.

Every punch carries local_time, utc_offset, time, dst_ambiguous, time_zone and zoned. Take them from time.at, with the device’s own offset when it sends one and otherwise with the endpoint’s zone. A package whose clocks send wall-clock times without an offset declares a required timezone option. A punch whose offset the device stated says so with offset_stated = true (dates.rfc3339 returns stated for an offset taken from the timestamp). Such a device is never taken for a clock behind.

Give each event a key that identifies the record. The same record gives the same key, and a changed record a different one (the whole line is usually right). The key decides the event’s id. Consumers deduplicate on that id. A record sent twice is seen once, and a changed record is not mistaken for a duplicate.

A device that is acknowledged moves on and forgets what it sent. So never drop what the package cannot read. Emit it as an unparsed event with the raw data.

A device that did not get its reply sends the same message again: after a dropped connection, a reboot or a timeout, or because a broker gives a message again when its acknowledgement was lost. A commit that landed in the database and was never answered is the same case: the gateway does not know it was kept and tells the device it was not. What to do with a message that comes again is the package’s choice. The gateway makes none for it. An implementer may:

  • Keep duplicates. Emit the record again. Its event has the same id, so a consumer that deduplicates on the id sees it once. Time and Attendance stores a punch under that id for this reason, and a punch sent twice is one fact there. This costs the package nothing.
  • Pass them on with the same key, and let the sinks decide.
  • Drop them, as the bundled ZK and BrightLink packages do. The package keeps what identifies the messages it took in, in the device’s store, and a message it has kept is not emitted again.

Dropping is written in the package, with store.get and store.set:

  • Whatever the package does with a repeat, it still answers the device as it answers a first message. The clock must be told OK to stop sending it again. The reply is the route’s, so a route that finds a repeat stores nothing, emits nothing and queues nothing and returns the same reply.
  • Name the unit. A device whose batches overlap (a clock whose reply was lost sends the records again with the newer ones, in a batch cut elsewhere) is asked about each record. A device that sends one message and one id (BrightLink) is asked about the message.
  • Keep a bounded list. The device’s store is read with every message and a message may write at most 16 KiB of it, so keep the last few hundred small keys (a short digest of the line, a message id) and say how many in the package, as a count and not an age. How far back a device sends again is a fact about its protocol. A repeat from further back than the list is emitted again, as if the package kept duplicates.
  • Know what it costs. A message that is new writes the list, so it writes the device’s store, which moves the device’s version. A message that is a repeat writes nothing. The list is kept only if the message’s events were stored, so a message whose events could not be stored is the first when it is sent again.

The device’s messages are handled one at a time, and two instances that handle one device at once are settled by the device’s version: the one that loses runs again on what the other kept, and finds the key. So the list is safe to read, change and write back.

Patterns every batch-upload protocol follows, whatever its wire format (zk/zk.lua is the worked example):

  • Upload cursors. A device that uploads a table in batches says how far it got. Save that with uploads.save_cursor(table, value) while handling the batch. Tell the device what was saved when it asks where to start. store writes are kept only once the batch’s events are stored, so a batch that fails is sent again from the old cursor.
  • Unparsed rows. Emit a row the package cannot read with uploads.unparsed(table, line, reason). A row that names nobody, or that no handler knows, is unparsed too.
  • Tagged rows. Some tables carry rows of several kinds (USER PIN=1\tName=Ann). Split the tag off. Parse the rest with parse_key_value. Hand each row to a handler by tag. Key each event on the whole line, so a changed record is a new event.
  • Command results. A device that reports results in batches often sends a result line followed by lines that belong to it. Read each result with the lines up to the next one. Report it with queue.result. Act on what it carries (a capability list updates the device’s info).

Every package carries scenarios in tests/*.toml. They are scripted conversations with a device, run through the real gateway pipeline with no hardware. hourctl pkg test runs them and fails while any route, command or action is untested. The scenario reference has the file format and how coverage is counted.

Take expected payloads from an independent source, such as the vendor’s specification or a capture from a real device, not from the package’s own output. Otherwise the test only shows the package agrees with itself. Developing packages shows how to record a capture from a real clock and turn it into a test.