Edge API reference

Household HTTP routes, credentials and OpenAPI, plus the read-only building and industrial demo endpoints.

15 min read · Edit this page

The household page and third-party integrations use the same local HTTP API. Inspect the gateway’s OpenAPI 3.1 document to see its routes and response types. For HTTPS, compare the certificate’s SHA-256 fingerprint with the one printed at startup before using it as hems.pem.

$ curl --cacert hems.pem https://hems.local:8080/openapi.json     # running gateway
$ hemsd openapi > openapi.json                     # or from the binary

It is also checked in as services/hemsd/openapi.json, and the build fails if a response type changes and the document does not.

Verify a replacement

The EMS household profile targets level L4. Each release measures four ports on Linux amd64 and arm64. The sender’s event ID ties the CloudEvent, signature and delivery together.

PortServicePassing observation
REST with OpenAPIhemsdThe contract lists the gateway event types. Household status requires a bearer token and returns the site identity.
CloudEvents 1.0hemsdA subscribed receiver gets a structured test event from that site, with an event ID and a versioned payload schema.
Standard WebhookshemsdThe receiver verifies the exact delivered bytes with the one-time subscription key. Revocation stops subsequent test deliveries.
MCP over HTTPtariffdAn authenticated MCP 2026-07-28 client discovers the server, lists the tools, checks that each one declares the read level, and calls get_coverage for four quarter-hours. An empty cache is a valid answer.

Each published JSON Schema describes a complete envelope. Its #/properties/data fragment describes the payload and is the URI carried in dataschema. Schemas include their transitive definitions for offline use. Test ping schema · All gateway event contracts

Rehearse both images. Run just interfaces with Docker Buildx, a running Docker Engine and Python 3.11+. The kit runs a shadow gateway, tariff service and private callback receiver on an isolated bridge. It records the four outcomes and both OCI manifest and configuration digests in target/interfaces/evidence.json.

Qualify another implementation. From the checkout or extracted release contract bundle, set HEMS_TOKEN and MCP_TOKEN in the environment. Use an authorized test household with one available subscription slot. Supply the address where the gateway can reach the probe on your private network. The probe creates and revokes a temporary ping subscription. Configure the local trust store for HTTPS endpoints.

python3 tools/conformance/probe.py \
  --gateway https://gateway.example --tariff https://tariff.example \
  --callback http://192.168.10.25:8085 --bind 192.168.10.25

Check a release. Download ems-interface-contracts.tar.gz and interfaces-<arch>.json. Read the appropriate role’s images.<role>.manifest to select ghcr.io/hupe1980/ems-hemsd@sha256:… or ghcr.io/hupe1980/ems-tariffd@sha256:…. Each version tag groups the two measured architectures. The images run as UID 65532. Mount the service configuration at /etc/ems/<role>.toml and give the gateway a writable volume at /var/lib/hemsd.

Credentials

CredentialIsOpens
householdthe box’s own token, printed at first start and on the handover sheet — as Authorization: Bearer …, or as the session cookie a browser gets from POST /v1/sessioneverything
household tokenthe same token, but only as a bearer: the cookie is refusedreplacing the token, and the sign-in QR code
managera token issued by PUT /v1/managers/{name}status, overrides and S2 — never the household’s data

Send the household token as a bearer credential.

$ curl --cacert hems.pem -H "Authorization: Bearer $HEMS_TOKEN" https://hems.local:8080/v1/status

A browser client can exchange the token for a session cookie.

$ curl --cacert hems.pem -c jar -H 'Content-Type: application/json' \
    -d "{\"token\":\"$HEMS_TOKEN\"}" https://hems.local:8080/v1/session
$ curl --cacert hems.pem -b jar https://hems.local:8080/v1/home

A request on the cookie that changes anything must carry Content-Type: application/json.

Refusals

Every refusal under /v1/ is an RFC 9457 problem document, application/problem+json. Branch on type; show detail, which is the sentence the household page shows:

{
  "type": "https://hupe1980.github.io/ems/docs/api/#not-found",
  "title": "There is no such thing on this box",
  "status": 404,
  "detail": "this box does not trust that control box, so there is nothing to forget"
}
typeStatusMeans
#bad-request400The request is not one this box can read — malformed JSON, a value that is not a SKI
#unauthorized401No credential, or not one this box issued
#forbidden403This credential may not do that — a manager on a household route, a cookie write without a JSON body
#not-found404No such route, device, goal, subscription or trusted control box; a DELETE with nothing to delete
#method-not-allowed405That method is not offered on the route
#conflict409The box is not in a state to do that — a token set in the file, too many subscriptions
#too-large413The answer would be too large — a completion code beyond what a phone can scan
#unsupported-media-type415The body is not JSON
#unprocessable422Readable, and not something this box can do — the wrong goal for a device
#too-many429Too many at once
#server-error500The box failed to do it, usually to keep it
#bad-gateway502A device or service the box asked did not answer
#unavailable503The box cannot answer that yet — no plan, no prices

A DELETE answers 204 when it removed something and 404 when there was nothing to remove.

Routes

MethodPathCredentialWhat it does
GET/v1/tariffhouseholdCurrent and next signed supply contract
POST/v1/tariff/previewhouseholdVerify the seller file and review its signer, period and price
PUT/v1/tariffhouseholdAccept the exact reviewed seller terms
GET/liveznoneWhether the process is alive
GET/readyznoneWhether the box is ready to control
GET/versionnoneThe daemon’s name and version
GET/openapi.jsonnoneThis contract: the OpenAPI 3.1 document the box was built with
GET/metricsnonePrometheus metrics
POST/v1/sessionnoneSign a browser in: exchange the household’s token for a cookie
DELETE/v1/sessionnoneSign a browser out
POST/v1/tokenhousehold tokenReplace the household’s token; the old one and every sign-in stop working
GET/v1/homehouseholdThe household page’s document: now, the plan, goals, the last receipt
GET/v1/statushousehold or managerWhat the box is doing and what it cannot see
POST/v1/goals/{asset}/quotehouseholdPrice a goal or preview charging now against the saved departure
PUT/v1/goals/{asset}householdAsk for a charge or a temperature by a time; answered with a verdict
DELETE/v1/goals/{asset}householdWithdraw a goal
PUT/v1/goals/{asset}/boosthouseholdConfirm immediate charging to the saved car goal
DELETE/v1/goals/{asset}/boosthouseholdReturn the car to its plan
GET/v1/overrideshousehold or managerThe overrides in force
DELETE/v1/overrideshousehold or managerWithdraw every override
PUT/v1/overrides/{asset}household or managerBoost, pause or mark away; the guard still narrows it
DELETE/v1/overrides/{asset}household or managerWithdraw one override
GET/v1/series/{point}householdThe box’s own measurements of grid or a device
GET/v1/dayshouseholdThe closed days the box keeps, at most ninety, and their sum
GET/v1/days.csvhouseholdThe same days as CSV
GET/v1/pairinghouseholdThe control boxes this box trusts, and those asking
POST/v1/pairinghouseholdTrust a control box by its SKI
DELETE/v1/pairing/{ski}householdStop trusting a control box
POST/v1/pairing/{ski}/refusehouseholdRefuse a control box that is asking
GET/v1/trusthouseholdInstaller diagnostics for identity, devices and quarter-hour history
GET/v1/handoverhouseholdWhat the handover sheet prints: identities and the § 14a devices
GET/v1/commissioninghouseholdThe commissioning record, signed by the box: its identity, its control box, its § 14a devices
GET/v1/qr/{what}householdA QR code: ski, fingerprint, commissioning, or signin (token only, never the cookie)
GET/v1/commissioning/serial-buseshouseholdList locally provisioned serial bus names during first setup
POST/v1/commissioning/first-meterhouseholdPreview a connection meter and optional observed assets on an empty site
GET/v1/commissioning/transferhouseholdRead the controller handover review
PUT/v1/commissioning/transferhouseholdAuthorize or revoke an installer handover
GET/v1/commissioning/changehouseholdRead the latest installation outcome
POST/v1/commissioning/changehouseholdActivate the reviewed driver addition
POST/v1/discoverhouseholdLook for SHIP nodes, and for SunSpec devices at named private addresses
GET/v1/managershouseholdThe energy managers connected to this box
PUT/v1/managers/{name}householdConnect a manager; answers its token once
DELETE/v1/managers/{name}householdWithdraw a manager’s credential
GET/v1/pushhouseholdThe box’s push key and the browsers subscribed
POST/v1/pushhouseholdSubscribe a browser, or change what it is told
DELETE/v1/pushhouseholdUnsubscribe a browser
POST/v1/push/testhouseholdSend one test notification
GET/v1/subscriptionshouseholdThe systems this box tells about its events
POST/v1/subscriptionshouseholdTell one more system: CloudEvents signed per Standard Webhooks
POST/v1/subscriptions/{id}/revokehouseholdStop telling one, and forget what it was owed
POST/v1/subscriptions/{id}/testhouseholdSend it a de.ems.test.ping now
GET/v1/deliverieshouseholdThe last seven days of deliveries, newest first
GET/s2/{asset}household or managerS2 over WebSocket: a manager drives one device, narrowed by the guard

An error is a status and, where there is something to say, one sentence of plain text. 401 means no credential or an unknown one; 403 means a manager’s credential on a route that is the household’s.

Household readings

For GET /v1/home, a saved car or tank goal is returned with its feasibility assessment. The second tuple element is null while the necessary device telemetry is missing. The first element still contains the saved settings.

On an empty gateway, POST /v1/commissioning/first-meter validates the three-phase meter, fixed tariff and support contact. Optional roof and storage entries require separate verified units and an external_limit_controller for shadow mode. The response contains the exact initial TOML and a confirmation id for the installation endpoint.

For POST /v1/discover, supply hosts, optional unit (default 1) and port (502 or 1502). A newly found SunSpec inverter with one of models 101–103 and 123 can include review. It contains the proposed driver TOML, address, unit and a nullable configuration refusal. Where Apply is available, send only the issued proposal as {"id":"…"} to POST /v1/commissioning/change. A changed file or unknown id returns 409. Read the latest receipt with GET /v1/commissioning/change after reconnection. Retrying the same id returns its recorded outcome.

When the household Matter pilot is configured, GET /v1/home includes matter with its node, endpoint, signed watts, receipt time and status. The Setup card labels a failed read as stale when an earlier observation exists.

The home receipt and closed-day history use whole Wh and cents. metered_bill reports priced, expected and observed-mode intervals. Its energy_ct and fixed_ct fields are null when a bill cannot be computed. money contains simulation economics. On measured days, nullable comparison contains with_plan_ct, without_plan_ct and the summed absolute interval error error_ct. The monthly total counts every matched day in eligible_days. Only differences above the error contribute to conclusive_days and the monetary sum. When comparison is unavailable, comparison_gap can identify the first affected observation interval in Unix seconds and its reason. The simulated household can also report vehicle, thermal, hot-water, storage, programme or grid-limit exclusions. The CSV carries the same instant and reason in comparison_gap_at_unix_s and comparison_gap_reason. Nullable arbitrage records grid charging and household discharge for closed cycles. forecast reports the measured percentage of production and load readings inside their forecast ranges. shadow: true on the home document identifies an observing gateway.

Households can read GET /v1/commissioning/transfer while observing and submit its current id and boolean approve to PUT on the same route. Authorization lasts one hour and can be revoked until the installer switches the configured controller and restarts.

Events out

The box tells the systems a household names what it tells the household — a § 14a reduction, failsafe, a goal at risk, a device not following, the closed day — with the numbers. Each is a CloudEvent 1.0 in structured JSON, POSTed with Content-Type: application/cloudevents+json and signed per Standard Webhooks: webhook-id (the event’s id, the same on every retry), webhook-timestamp and webhook-signature, keyed with the whsec_ secret the box shows once when the subscription is made. Every webhook library verifies it as it is.

$ curl --cacert hems.pem -H "Authorization: Bearer $HEMS_TOKEN" -H 'Content-Type: application/json' \
    -d '{"name":"Home Assistant","url":"http://homeassistant.local:8123/api/webhook/replace-with-your-random-webhook-id","types":["de.ems.grid.*"]}' \
    https://hems.local:8080/v1/subscriptions
TypeWhendata
de.ems.grid.lpc.limit.receivedthe network operator reduces the connectionlimit_w, minimum_w
de.ems.grid.lpc.limit.releasedthe reduction endslasted_s
de.ems.grid.lpc.failsafe.enteredthe control box falls silentfailsafe_w
de.ems.grid.lpc.failsafe.leftthe failsafe endsreduced
de.ems.grid.lpp.limit.receivedthe export ceiling changeslimit_w
de.ems.device.losta device stops reportinglast_seen
de.ems.site.goal.at-riska goal turns tight or impossibleverdict, goal, reachable
de.ems.device.deviation.detecteda device ignores the box for ten minutescommanded_w, measured_w
de.ems.site.day.closeda day closesthe receipt: whole cents, Wh, the § 14a lines
de.ems.test.pingPOST /v1/subscriptions/{id}/testtest

types takes a trailing * (de.ems.grid.*); subjects narrows to asset ids. Besides the CloudEvents core, every event carries the attributes below. A receiver must refuse an event with a classification value it does not recognise.

AttributeValue
dataschemaThe type’s versioned schema, for example https://hupe1980.github.io/ems/contracts/events/v1/de.ems.device.lost.json#/properties/data
partitionkeyThe site the event is about. Events with the same key are ordered.
dataclassificationconfidential for everything about a household, its devices or its meter; internal for de.ems.test.ping
dataregulation, datacategoryGDPR and standard on every confidential event
timeUTC, ending in Z

Each type has a closed JSON Schema that describes the whole envelope and refuses extra members. Event schemas. OpenAPI also includes the payload types in its webhooks section, along with the two types the box sends only to the fleet: de.ems.site.day.reported and de.ems.site.departure.rehearsed.

A Rust receiver can use the published catalogue, which has no dependencies:

let kind: ems_events::EventType = event_type.parse()?;    // refuses a type EMS does not send
if ems_events::matches("de.ems.grid.*", kind.as_str()) { /* … */ }

For an episode that also triggers a browser notification, notification.data.event_id matches the CloudEvent id, including after quiet hours.

A receiver returns 2xx and deduplicates retries by source and id. Retry intervals are 30 seconds, 2 minutes, 10 minutes, 30 minutes, one hour and then three hours, within a 24-hour window. Each subscription holds up to 200 pending events and drops the oldest when full. GET /v1/deliveries shows up to 500 attempts per subscription from the last seven days. The box delivers to an address on the household’s network over http or https, to one on the internet over https only and only with "public": true, and never to loopback, link-local or itself; it follows no redirect. At most eight systems.

Home Assistant

Use the same random webhook ID in the subscription URL and the automation. Keep local_only enabled. Home Assistant webhook triggers.

automation:
  - alias: "hems: the network operator reduces the connection"
    triggers:
      - trigger: webhook
        webhook_id: replace-with-your-random-webhook-id        # long and random: it is the secret here
        allowed_methods: [POST]
        local_only: true
    conditions:
      - condition: template
        value_template: "{{ trigger.json.type == 'de.ems.grid.lpc.limit.received' }}"
    actions:
      - action: persistent_notification.create
        data:
          title: "§ 14a"
          message: >-
            Reduced to {{ (trigger.json.data.limit_w / 1000) | round(1) }} kW.
            {% if trigger.json.data.minimum_w is number %}
            {{ (trigger.json.data.minimum_w / 1000) | round(1) }} kW stay guaranteed.
            {% endif %}

A commissioning record a field-service tool can verify

Whoever ordered an installation wants two things back: that the network operator’s control box is paired, and what was installed. The box says both in one signed statement, which an installer’s phone scans from the handover view or a tool fetches:

$ curl -sS --cacert hems.pem -H "Authorization: Bearer $TOKEN" \
    "https://hems.local:8080/v1/commissioning?reference=WO-2026-000417"
eyJhbGciOiJFUzI1NiIsInR5cCI6ImhlbXMtY29tbWlzc2lvbmluZytqd3MiLC…

It is a JWS in compact serialisation (RFC 7515), signed ES256 with the key behind the box’s SKI. reference is the caller’s own identifier for the work — 1 to 64 printable ASCII characters without a space — and comes back byte for byte; the box never reads it.

Protected header
algES256
typhems-commissioning+jws
x5t#S256SHA-256 of the box’s SHIP certificate, base64url
x5cthat certificate, DER in base64 — on /v1/commissioning, not in the QR code
Payload
v1
referenceas given; absent if none was
issued_atwhen the box signed, RFC 3339 UTC
boxski (40 lower-case hexadecimal characters) and ship_id
control_boxstate — none, unpaired, silent, failsafe or heard — and its ski where exactly one is trusted
identitykept if a restart restores this SKI, ephemeral if not
modulethe § 14a module, as configured
minimum_wthe power a reduction may not go below, watts
deviceseach controllable device: fallgruppe, letter, power_w, minimum_direct_w, commissioned where stated, and — not in the QR code — the box’s own names for its assets

Fetching is the primary path and has no size limit: the record grows by under 200 octets with each device. GET /v1/qr/commissioning?reference=… is the shortcut — the same record as a QR code, without x5c and assets so that a phone can read it: about 1.3 kB for four devices, and at most 1 732 octets (QR version 30), which a house with six or seven devices stays under. A larger installation answers 413 and is fetched instead.

To verify one:

  1. Check the ES256 signature over header.payload with the public key of the certificate in x5c — or, for a scanned code, of the certificate whose SHA-256 is x5t#S256.
  2. Compare that certificate’s SKI with box.ski and with the SKI on the order. A record signed by another box is a valid signature and the wrong house.
  3. Check typ and that issued_at is recent enough for the purpose.
  4. Only then compare reference with the order. A record that verifies but names another order — or none: the field is absent when the box was commissioned before the order existed, or nobody entered it — is a different failure from an invalid signature, and should be reported as one: the box is genuine and the record has to be issued again.
  5. Read it for what it is: the signature proves this box said so at that time. It does not prove the work was done well.

Building demo

bemsd demo serves GET /v1/demo/building?case=unconfirmed and the corresponding page at /?case=unconfirmed. Supported cases are confirmed (default), delayed-arrival, station-rejoin, idle-station, above-request, unconfirmed, stale-charger, stale, over-limit, unknown-pv and no-solar. Choose moment=requested, observed, deadline or handover on either route. The default is handover. The connection snapshot first appears at handover. Until the station acknowledges, profile_accepted is null. Each station’s final_received_at distinguishes receipt from observation. In case=delayed-arrival a late sample confirms the deadline reading at handover.

For case=station-rejoin, the additional moments are rejoined, buffered and restored. A station can be connected while its current power is unknown. buffered_received_at records the queued reading’s arrival. A qualifying sample has both final_measured_at and final_received_at.

For the charging incident, charging_source is ocpp-1.6j-station-telemetry. Each member of stations gives the station ID, profile acknowledgement, initial kW and final kW. A null contribution makes the corresponding bank reading null. Station totals exclude individual connectors.

The delivery field compares final_sample_kw to requested_kw. Its values are pending before the deadline, within-limit, above-limit and unconfirmed. For a missing final reading, final_sample_at and final_sample_kw are null. final_sample_due_at preserves the expected time. A missing current measurement or an unconfirmed final sample is JSON null. The live gateway does not mount either route.

Community allocation demo

bemsd community serves GET /v1/demo/community on loopback port 8083. Use the temporary Basic login printed at startup. Select case=static or case=cascading to compare keys. Select interval=1 or 2 for the earlier or later occurrence of 02:00. Members receive only their own rows. The coordinator also receives coverage and residual energy in kWh.

Industrial demo

cemsd demo serves GET /v1/demo/industrial?moment=early. Use early, delayed or closed for the same shift. At close, projection and intervention fields are null and closed_mean_kw contains the simulated meter outcome. Add reveal=true to an early or delayed decision to compare its projection with the original synthetic close. The HTML view takes the same query at /.

Use moment=unavoidable to inspect an interval whose minimum already exceeds the prior peak. Optional evidence values are complete, stale-meter, battery-unknown, tariff-review, limited-battery, and missing-close. Each suppresses only the estimates that depend on the missing input or applies the fixture’s 60 kW limit. Reloading the same URL reproduces the same evidence.

Local power history

With a household credential, request one complete quarter at the grid connection:

GET /v1/series/grid?from=2026-11-23T10:00:00Z&to=2026-11-23T10:15:00Z&resolution=quarter_hours

at identifies the quarter start. watts is the arithmetic mean of the observations. min_watts, max_watts and samples describe their range and count. Positive watts indicate import at the grid connection. A quarter with no observations has no row. A measured zero has a row.

For explicit summaries, supplied boundaries must fall on a quarter hour. With just ?resolution=quarter_hours, the response covers the four most recently closed quarters. Omit resolution to select the available tier automatically. Windows include their start, exclude their end and may span up to 1,096 days. A box with local history disabled returns 404. During another history read it returns 503. Retry after the first request finishes.

Wired heat-meter diagnostics

When a heat meter is configured, authenticated GET /v1/trust includes heat_meter with its configured manufacturer, eight-digit ID and primary address. delivered_heat_wh is an exact decimal string while state is live. It is null for waiting, unavailable, wrong_meter and invalid_reply. last_read_at is the gateway receipt time in Unix seconds and stays null until the first accepted reading.