Caution
This is the author's personal experiment. It is published so that others can read and review it, not for others to use.
- It is not a medical device. It is not approved, certified or cleared by any authority.
- It is not affiliated with or endorsed by AndroidAPS, Nightscout or Home Assistant.
- It can make an insulin pump deliver insulin. A bug, a wrong setting or misuse can cause severe hypoglycaemia or death.
- There is no support.
- It is provided "AS IS", without warranty of any kind, under the MIT
licence (see
LICENSE). Use it entirely at your own risk.
Warning
Safety model, in short (details in "Arming" and "Limits")
- The confirmation code, and a phrase such as "Ja, spritzen" in the author's voice package, only guard against a misheard or accidental confirmation. They do not protect against anything inside Home Assistant.
- While the switch is armed, anything that can call this integration's services can prepare and confirm a dose by itself, within the limits: the prepare services return the code to their caller.
- Arming needs an administrator: the options dialog, or the same options flow driven through the REST API with an administrator's access token. Such a token can therefore arm, prepare and confirm by itself, without a person. Once a user enables the arm button (it comes disabled), anything that can press a button can arm as well.
- Do not expose the arm button to a voice assistant (Assist).
- Before pairing, think about what in your Home Assistant can call actions: MCP clients through the LLM API "Home Assistant", every long-lived access token, every user who may press buttons, every automation and script.
- The AAPS phone's own constraints (max bolus, max carbs) remain the backstop. They must be set there.
- The dosing limits of this integration have no built-in upper bound. They are whatever is entered.
Lets Home Assistant act as one AndroidAPS 4 (AAPS) "client control" client: it
asks the AAPS master phone to prepare a bolus, shows what the master answered,
and sends the commit after a confirmation code. Everything travels through
Nightscout API v3 as signed documents in the settings collection. There is no
direct connection to the phone.
Status. Written from the AAPS source. Tested against a fake master
(tests/fake_master.py), a local throwaway Nightscout for the transport, and
an AAPS 4 build on an Android emulator with the virtual pump (test-rig/).
The author uses it on his own loop. It has not been tested by anyone else and
has had no safety validation of any kind. Off by default: every limit defaults
to "refuse", and no proposal or dose request is sent before a pairing exists,
the limits are set and the switch is armed.
This repository contains software only. It gives no medical or dosing advice; every number (limits, intervals, thresholds) is for whoever runs it to set. Numbers in examples below are placeholders, not suggestions.
This is how the author (Kusi, who has type 1 diabetes) uses it at home. It is described so that the code makes sense, not as a recommendation.
Home Assistant Voice PE (wake word)
-> speech to text
-> fixed sentence automations in a Home Assistant package ("insulin by voice")
-> this integration's prepare and confirm services
-> Nightscout
-> AAPS 4 on his phone (https://github.com/markusbaumg/AndroidAPS-Kusis-Mod)
-> pod
- Arming. The voice package listens for nothing until he presses the integration's arm button on a dashboard. That arms the integration for a limited time, for a small number of doses and a small number of proposals (the limits in the integration's options). The package then sets its own mode to "scharf" and says so in a short announcement. When the integration turns itself off (time up, counts used, an unclear outcome), the mode goes back to "aus". A third mode, "simulation", runs the whole dialogue without sending anything.
- While not armed, a second automation answers the dose sentences and "Ja, spritzen" locally with a fixed sentence ("not armed, press the button first"). Nothing is called, and these sentences never reach the language model.
- A fixed amount. "Spritze 2 Einheiten Insulin" asks AAPS for a proposal
(
prepare_fixed). Home Assistant reads back the amount AAPS answered, with the current glucose and IOB ("Aktuell 6,4, IOB 2,1."), and how many seconds are left to confirm. - A meal. Other sentences go to the conversation agent (a language
model). For a meal it estimates the carbohydrates and calls a script that
can only propose (
prepare_meal). The model learns neither the amount nor the code; Home Assistant reads the proposal out itself, on the satellite that was asked once it is free, or as a phone notification (also when the announcement fails). - Confirmation by saying "Ja, spritzen". The package keeps the open proposal's code in a helper and releases it only after a read-back that went out; before that, "Ja, spritzen" is answered with "wait", and a proposal whose read-back went out nowhere is dropped. The spoken four-digit code works too. Every attempt uses the proposal up, and "Nein ..." or "Insulin abbrechen" drops it.
- After the delivery the end of the delivery is announced (the integration's delivery event), and once Nightscout's IOB includes the dose, a short follow-up with glucose and IOB.
- Limits are set by the author in the integration's options. The package adds only its modes and a presence condition (a person entity must be at home); everything that bounds a dose is enforced by the integration.
A de-identified snapshot of his package is in
examples/home-assistant/insulin_sprache.yaml.
It is not a ready-made configuration: entity ids (satellite, phone, person,
glucose and IOB sensors, conversation agent) and the German sentences are
his and need adapting; the header lists them. The voice-package tests run
against it (AAPS_CC_VOICE_PACKAGE, see "Voice package" under "Tests").
The format is not a published interface. It was read from
- AAPS 4.0.0, commit
f77abd9b82b308e8fc330da0d7a31370fb4a0f49
and that pin is in core/protocol.py (AAPS_SOURCE_VERSION,
AAPS_SOURCE_COMMIT) and in every status output. A master on another AAPS
version may accept the same signed fields with another meaning. Re-read the
files listed at the top of core/protocol.py before using another version.
The sections from here on document how the author installs and runs his experiment. They describe what the code does; they are not instructions or an invitation for anyone else to set it up (see the warning at the top).
Domain aaps_client_control, one config entry, no YAML. It opens no port and
has no HTTP view; it only makes outgoing requests to the Nightscout address in
the pairing text. Written for Home Assistant 2026.11; the tests ran on 2026.10.4
(the newest release the test package offered).
- Copy
custom_components/aaps_client_control/into/config/custom_components/(or add this repository to HACS as a custom repository of type Integration). - Before the first pairing, keep the state file out of the configuration
repository: add
.storage/aaps_client_controlto its.gitignoreand to the exclude list of whatever copies/configelsewhere. See "What is stored where". - Restart Home Assistant.
- On the AAPS master: create a new client and show "QR code: Nightscout and pairing". The master accepts the pairing for two minutes.
- In Home Assistant: Settings, Devices & services, Add integration, "AAPS Client Control". Paste the text of the QR code into the password field and tick "I understand that this integration can make my pump deliver insulin and that I use it at my own risk". Without the tick the form comes back with an error and nothing is sent. Pairing again (below) does not ask again.
- The flow waits for the master (up to 110 s). It ends with an entry only when the key exchange is done and the master has answered a ping signed with the new secret. Otherwise it ends with the reason and nothing is stored.
The text is handed to the core once and dropped. It is not in the config entry, not in the storage file and not in the log. After the key exchange the secret from the QR code no longer signs anything.
Pair again: on the entry choose Reconfigure and paste the text of a new client. The stored pairing is replaced only when the new one has answered; a failed attempt leaves it as it was. Delete the old client on the master. Unpair: delete the entry and delete the client on the master. Deleting the entry removes every secret from the storage file. The commit log (time and units) stays in it, so the minimum interval and the 24-hour ceilings do not start again from zero when the entry is added again; without a commit log the file is deleted.
At every start the integration sends one ping and writes the result to the log
(Ping at start: pong, or a warning with the reason). It sends none while a
delivery watch from before the restart is still open (see "Entities and the
delivery event").
Entry, Configure, "Set the limits". One field per limit, named as in core.guard.Limits. Nothing
is prefilled. While any field is empty, 0 or invalid, the form does not save and
everything stays refused. Saving changed limits turns the switch off and drops an open
proposal (saving the form unchanged does nothing).
This software suggests no numbers.
| Option | What the software does with it |
|---|---|
max_units |
A request or a result from the master above it is refused, never trimmed. |
max_carbs |
A meal request above it (grams) is refused. |
min_interval_s |
A commit sooner than this after the previous one is refused. Survives restarts. |
max_commits_per_24h, max_units_per_24h |
Rolling 24 hours, not a calendar day. Survive restarts. |
bg_units |
mmol or mgdl: the unit bg_min/bg_max are given in and the unit sent to the master. A mismatch with the master's unit is refused when the answer shows it. |
bg_min, bg_max |
The newest glucose entry in Nightscout outside this range: refused. |
bg_max_age_s |
The newest glucose entry older than this: refused. |
arm_duration_s, arm_max_commits, arm_max_prepares |
The switch turns itself off after this time, after this many commits, and when a prepare is asked for after this many prepares were sent to the master. Each prepare makes the master pause SMBs for up to two minutes (MasterActionExecutorImpl.kt:256-264, :372), with or without a commit. |
code_ttl_s |
Life of a proposal and its code, at most 120. |
The limits count only what went through this integration. A dose given on the phone is not seen by the interval or the 24-hour ceilings.
Only code_ttl_s has an upper bound (120 s). The dosing limits (max_units,
max_carbs, the 24-hour ceilings) and the arming allowances have none: the
integration enforces whatever is entered. The AAPS master's own constraints
(max bolus, max carbs, set on the AAPS phone) still apply to every request and
remain the backstop; set them there. The number fields of the services in the
user interface stop at 25 U and 200 g, but that is only the form, not a limit.
A limit that is missing in stored options (for example arm_max_prepares
after an update) counts as 0: everything is refused until the form is saved again.
Two ways turn the switch on. Both run the same Guard.arm() (through
async_arm in __init__.py), with the same preconditions (paired, every limit
set) and the same allowances (arm_duration_s, arm_max_commits,
arm_max_prepares). There is no arm service.
- Options dialog: entry, Configure, "Arm the switch". It answers with the
time and the counts, or with the reason for the refusal. Home Assistant
offers it to administrators only: in the user interface, and as the same
options flow over the REST API (
POST /api/config/config_entries/options/flowwith the entry id ashandler, thenPOST /api/config/config_entries/options/flow/<flow_id>withnext_step_id: arm), which needs an administrator (require_admininhomeassistant/components/config/config_entries.pyof 2026.10.4). A service call, an automation, a script, a voice assistant, the tools of an LLM API and a user who is not an administrator cannot reach it. An administrator's access token can, without a person, and can then callprepare_fixedwithreturn_responseandconfirmas well. - Button
button.aaps_client_control_arm("Scharf schalten", English "Arm"), for a dashboard. It comes disabled in the entity registry: it has no state and nothing can press it until a user enables it in the entity's settings (Home Assistant then reloads the entry). An arm button that was enabled before keeps that setting: Home Assistant applies the default only when it creates the registry entry (EntityRegistry.async_get_or_createleaves an existing entry'sdisabled_byalone; read inhomeassistant/helpers/entity_registry.pyof 2026.10.4 and tested intests/ha/test_integration.py). A refusal (limits missing: reasonLimits; not paired:NotPaired) raises an error with the guard's German text, which the dashboard shows, for example "Nicht scharf geschaltet: nicht gekoppelt.", and the last-outcome sensor turns torefusedwith that reason. An automation or a script that presses it stops there with the same error.
What the button changes, once enabled: any caller inside Home Assistant
that can press a button can arm. button.press is an action like any other:
- Home Assistant checks the permission to press (
control) only for a call that carries a user. An administrator and a normal user may press it; only a user in the read-only group (system-read-only) is refused (Unauthorized). A call without a user, from an automation for example, is not checked. (Read inhomeassistant/helpers/service.pyof 2026.10.4 and tested intests/ha/test_integration.py.) The user interface cannot put a user into the read-only group: the 2026.11.3 frontend sets only "system-admin" and "system-users" (system-read-onlyappears in it only as a translated group name). So every account made in the user interface can press the arm button, a family member's or a wall tablet's too; only a user put into the read-only group outside the user interface (the websocket commandconfig/auth/updatewithgroup_ids) is refused. - Exposure only limits Assist. Home Assistant does not expose new button
entities to Assist by itself (
buttonis not inDEFAULT_EXPOSED_DOMAINSofhomeassistant/components/homeassistant/exposed_entities.py), and it should stay unexposed. But that does not stop a caller that may call any action. - MCP clients can arm, prepare and confirm without a person. The LLM API
"Home Assistant" (id
homeassistant, administrators only) has the toolhomeassistant__call_action. It calls any action under the caller's user, does not look at exposure, and returns the action's response (CallActionToolinhomeassistant/components/homeassistant/llm.pyof 2026.11.3). The MCP Server integration serves this API at/api/mcpwhen its entry is set to offer every LLM API rather than Assist only, and to any administrator's token at/api/mcp/homeassistantwhatever that option says (http.pyofmcp_server). With it, an MCP client presses the arm button, callsprepare_fixedand gets the code back in the response, then callsconfirm. Where an MCP client connects that way, every session of that client can do this, for example every coding agent session on a machine that has the token, including one steered by text it read (prompt injection). Before pairing such an instance, the owner of the instance has to decide: limit the MCP Server entry to Assist and connect with a token of a user who is not an administrator, or accept the path explicitly. A token of a user who is not an administrator also closes the options-flow path (see "Options dialog" above), which an administrator's token opens whether or not the arm button is enabled. - Any long-lived access token of a user who may press the button can do the
same without MCP, through the REST API (
POST /api/services/button/press, and?return_responsefor the prepare services). Turning MCP options off does not change that. An administrator's token can arm through the options flow even with the button disabled; give a token that a program or an agent holds to a user who is not an administrator. - Every service can be called by anything inside Home Assistant, and the prepare services return the code to their caller. So a caller that can press the button can arm, prepare and confirm by itself. The code only protects against a misheard or accidental confirmation. It does not protect against a caller inside Home Assistant.
- A press while the switch is on starts a new arming with the full
arm_duration_s,arm_max_commitsandarm_max_preparesand drops an open proposal, as the dialog does. Against a caller that can press the button, these three bound one arming and no more. What bounds every dose, whoever armed:max_units,max_carbs,min_interval_s, the 24-hour ceilings and the glucose gates.
With the arm button disabled, arming needs an administrator: the options
dialog in the user interface, or the same options flow driven through the REST
API (/api/config/config_entries/options/flow) with an administrator's access
token. Such a token can therefore arm, prepare and confirm by itself; no
caller without an administrator's rights can arm. Enabling the button extends
arming to every caller that can press a button, for convenience on a
dashboard; the bullets above are what that means.
The switch is in memory only and turns itself off: after arm_duration_s,
after arm_max_commits, at the prepare after arm_max_prepares, after a
commit or a delivery that ends failed or unknown, when changed limits are
saved, after a new pairing, and at every restart or reload. A refusal (a wrong
or expired code, a ceiling, the glucose gates, the interval, the 24-hour
ceilings, or a refusal by AAPS that certainly started nothing) leaves the
switch on; at a confirm it uses up the proposal, as every confirm does, and a
refusal by AAPS of a prepare still counts against arm_max_prepares. To turn
it off on purpose: the disarm service, which anything can call (a read-only
user too), or the button button.aaps_client_control_disarm ("Ausschalten",
English "Disarm"), which every user can press except one in the read-only
group (which the user interface cannot assign, see above).
What a press leaves in the recorder and the logbook (read back from an
in-memory recorder and the logbook in tests/ha/test_recorder.py): the
button's state, which is the time of its last press (the logbook shows the
press with the user who pressed, when there is one); a call_service event
whose data is the entity id; the switch; and the last outcome (armed,
refused or disarmed, the reason, arm_button or disarm_button, the
time). No amount, no code, no text. The text of a refusal goes to the caller
and, for a press from the frontend or an automation, into Home Assistant's log
(Error during service call to button.press: …); it names missing limits or
says "nicht gekoppelt", nothing else.
There is no arm service; see "Arming" for the options dialog and the arm
button. All return response data. prepare_meal, prepare_fixed, confirm and status
can only be called with a response (response_variable in a script,
return_response elsewhere); disarm, cancel and ping also work
without. No service raises for a refusal: the answer always has ok, outcome,
reason (English code) and text (German sentence), so a script can always
speak text. Only a missing required field raises.
| Service | Fields | Response |
|---|---|---|
aaps_client_control.disarm |
none | outcome: disarmed (the disarm button does the same) |
aaps_client_control.prepare_meal |
carbs (required, whole grams), note (optional text) |
outcome: prepared, units, carbs, code, valid_s, valid_until_ms, glucose, glucose_units, glucose_age_s, warnings, details; or refused with a reason |
aaps_client_control.prepare_fixed |
units (required) |
as prepare_meal, carbs is 0 |
aaps_client_control.confirm |
code (required) |
outcome: accepted with units, carbs; refused (nothing was started by this call); failed (the master reports a delivery failure, part may be delivered); unknown (with units, sometimes may_start_until_ms) |
aaps_client_control.cancel |
none | outcome: cancelled |
aaps_client_control.status |
none | paired, client_id, role, counter, armed, armed_for_s, commits_left, prepares_left, pending, delivery, limits_missing, last_commit_ms, commits_24h, units_24h, deadlines_s, and the source pin. No secret, no code. |
aaps_client_control.ping |
none | outcome: pong with skew_ms, counter; no_answer; refused |
Two more answers come from the integration itself: reason NotLoaded (outcome
refused: no entry is set up, nothing was sent) and outcome error with reason
Internal (an unexpected error; the log has the details).
- action: aaps_client_control.prepare_meal
data:
carbs: 30 # a placeholder
response_variable: vorschlag
# vorschlag.ok, vorschlag.text, vorschlag.units, vorschlag.code, vorschlag.glucose, vorschlag.warnings
- action: aaps_client_control.confirm
data:
code: "{{ gesprochener_code }}"
response_variable: ergebnis
# ergebnis.outcome is accepted, refused, failed or unknown; ergebnis.text can be spoken as it is- Timeouts. A call blocks until the core's deadline at the latest: ping 30 s, prepare 40 s, confirm 40 s (plus about one second). Home Assistant does not cut a service call short by itself; do not wrap these calls in a shorter wait.
- The code is only in the prepare response. It is in no entity, no event
and not in
status. A script that keeps the response in a variable puts it into that script's trace; the code is valid once and forcode_ttl_sat most.valid_until_msis the end of that time by Home Assistant's clock; a caller that reads the code out later should say the time that is left then.confirmaccepts it with spaces between the digits, and as a number (a template that turns "0417" into 417 or 417.0 still matches). - Any call to
confirmuses the proposal up, also with a wrong code. acceptedis not "delivered". The end of the delivery comes later as an event.- Anything in Home Assistant that can call services can call these, and whoever calls a prepare service reads the code in its response. Together with the arm button, once enabled, this means: anything that can press a button and call a service can arm, prepare and confirm by itself; an administrator's access token can do so through the options flow even with the button disabled. See "Arming".
- A state that cannot be written stops the call. The message counter and
the commit record are written to disk before anything is sent. If the write
fails, the answer is
refusedwith reasonStorageand nothing is sent.
binary_sensor.aaps_client_control_armed: the switch (read-only), attributespaired,commits_left,prepares_left,limits_missing. Read every 10 s and after each call.button.aaps_client_control_armandbutton.aaps_client_control_disarm: arm and disarm, see "Arming". The arm button is disabled in the entity registry until a user enables it. Their state is Home Assistant's own button state, the time of the last press.sensor.aaps_client_control_last_outcome:outcomeof the last service call (notstatus), arming or button press, or the state of the last delivery; attributesservice(the service name;arm_dialog,arm_buttonordisarm_button; ordelivery),reason,at. No amount, no code, no text.- Event
aaps_client_control_deliverywhen the watch after an accepted commit ends:state(delivered,failedorunknown),units,delivered,percent,text(German). The state isunknownwhen no progress frame arrives within 75 s after the master accepted the commit (the master reports nothing while the pump connects and keeps that window open for 60 s,ClientControlReceiver.kt:159,:183), or when 30 s pass without news after the first frame. A late delivery failure in the ack document ends the watch at once in both phases. Home Assistant's recorder stores events, so the amounts in this event are in its database until purged, unless the event type is excluded there.
After a restart or a reload the switch is off and an open proposal is gone. A
delivery that was being watched at that moment is watched again: the commit
writes a mark into the storage file before it is sent, and the mark is removed
when the watch ends. While the mark is there, also right after the start, ping
and prepare are refused with reason Delivering and no ping is sent at start,
because the master has a single ack document per client and a new command
would overwrite a late delivery failure. The event is fired when the resumed
watch ends (after Home Assistant has started, so automations are loaded). A
mark older than 30 minutes is reported as unknown at once.
| Where | What |
|---|---|
/config/.storage/aaps_client_control (mode 600) |
Nightscout address and token, client id, the pairing secret from the key exchange, message counter, the commit log for the interval and the 24-hour ceilings (time and units), the mark of a delivery that is being watched, last pong, clock difference. Written by the integration itself (atomic, with fsync), not through Home Assistant's storage helper, which reports no failed write and only schedules writes during shutdown. |
Config entry (.storage/core.config_entries) |
The limits (options). No secret. |
| Memory only | The switch, the open proposal and its code. |
| Recorder | The four entities and the delivery event (see above and, for a button press, "Arming"). The integration puts the code into no entity and no event of its own. But the recorder also stores every service call with its data (event call_service; homeassistant/components/recorder/core.py listens to all events and excludes none of this type by default). A script that passes the code or an amount on in a service call (an announcement, a push, script.turn_on with variables) therefore leaves it in the database until it is purged. The code is valid once and for code_ttl_s at most. To keep it out: recorder: exclude: event_types: [call_service] in configuration.yaml, at the cost of the logbook no longer knowing what called a service. |
| Diagnostics download | Options, status and last outcome; the client id is redacted, the storage file is not read. |
- Git: add
.storage/aaps_client_controlto.gitignoreof a repository that tracks/config, and to the exclude list of any script that pulls.storagefrom the instance. - Backups: Home Assistant's own backup offers no setting to leave a single
.storagefile out (not checked against the Supervisor source here), so expect the file in every backup that contains the configuration. Treat such archives as holding the pairing secret and the Nightscout token. After restoring one the counter is behind the master's; the master then ignores this client, a ping gets no answer, and the pairing has to be made again. Deleting the client on the master makes a copied secret useless.
The plan the author followed before any real use. The emulator trials in
test-rig/notes/ cover parts of stages 1 to 3. Each stage has a stop
condition; do not go on past one. Use an AAPS install on an emulator with the
virtual pump and its own Nightscout (the local throwaway one), not the install
and site of a real loop: test treatments are written to the AAPS database and
to Nightscout as if delivered. Note the AAPS and Nightscout versions and turn
AAPS auto-update off. The pairing text carries the Nightscout address as the
master knows it and the client uses the same address, so both sides must reach
Nightscout under one address (for an emulator on the same machine,
adb reverse tcp:1337 tcp:1337 makes http://127.0.0.1:1337 valid on both;
untested, as is whether AAPS accepts a plain-http address).
- Stage 0, tests.
pytest -qgreen in both set-ups, hassfest green, the transport test against the local Nightscout green. Stop on any failure. - Stage 1, pair and ping with the command line (no Home Assistant). Create
the client on the master (role for meals),
python -m core.cli pair, thenpingandstatus. Observe: the client goes from pending to active; a pong arrives;skew_msis small. Stop: no pong. Delete the client on the master before another try. - Stage 2, one prepare and one commit with the command line, limits set by
you in
limits.json. Observe: the amount in the answer equals what AAPS shows and what the virtual pump records; which acks and progress frames arrive; whether the delivery ends asdelivered. Save the raw documents (secrets removed) as test fixtures. Stop: any difference between the answer and the phone, or a progress frame the core cannot verify (it rebuilds the signed number text the way Kotlin prints it; a mismatch ends asunknown). - Stage 3, failure cases with the command line. Emulator offline right after a commit, then online again; emulator clock shifted; confirm after the code has lapsed; cancel; client control switched off on the master; client deleted on the master; an old copy of the state directory restored. Observe the reported outcome against what the virtual pump did. Stop: a delivery not reported as delivered or unknown, a "refused" with a delivery recorded, or a late execution that was not announced as possible.
- Stage 4, the integration in a throwaway Home Assistant on the same machine
(not an instance in daily use), with a new client (the command-line state and
the integration's state must not share a client: one counter, one owner).
Pair through the flow, set the limits, then call the services from Developer
tools:
status,prepare_meal,confirm(arm before that in the entry's options dialog or with the arm button; try a refused press too), and watch the event and the entities. Repeat the stage 3 cases, plus: restart during a delivery, Nightscout stopped, options saved while armed. Stop: any disagreement between response, event, entities, log and the virtual pump. - Stage 5, voice (a voice package such as the one in
examples/home-assistant/) against the same throwaway set-up. Observe what the recogniser writes for amounts and codes, and that every spoken sentence is thetextof a response. Stop: any spoken result that differs from the response. - Stage 6, teardown, every time. Delete the client on the master, delete the
entry (or
core.cli unpair), and check that the storage file holds nosecretsany more (it is gone when nothing was committed).
custom_components/aaps_client_control/
core/ no Home Assistant imports; standard library plus `cryptography`
protocol.py canonical strings, HMAC, documents, key exchange, pairing text
nightscout.py the few API calls (JWT login, settings GET/PUT, newest glucose entry)
client.py state files, signed round trip with one deadline, pairing, delivery watch
guard.py the single enforcement point: switch, code, ceilings, interval, glucose gate
cli.py bench commands; no network service
__init__.py entry set-up, the services, arming for dialog and button, the delivery event, the ping at start
config_flow.py pairing (one-time), pair again (Reconfigure), options: limits, and arming
button.py the arm and disarm buttons
storage.py the core's state in the file .storage/aaps_client_control, written directly
binary_sensor.py, sensor.py, diagnostics.py, services.yaml, strings.json, translations/
tests/
fake_master.py fake Nightscout plus fake master, written a second time from the source
test_vectors.py AAPS's own HMAC vectors, canonical strings, key exchange against the second implementation
test_roundtrip.py pairing lifecycle, deadlines, errors, delivery watch
test_guard.py every refusal, the counters, the outcomes after a commit
test_cli.py
test_local_nightscout.py transport against a local Nightscout; skipped unless asked for
ha/ integration tests in a real Home Assistant core against the fake master
test_recorder.py what a button press leaves in the recorder's database and the logbook
test_voice_package.py a voice package, end to end, plus a static check that no action in it presses a button; left out unless asked for
tools/
voice_sentences.py sentence collisions of the voice package, with Home Assistant's own matcher
voice_in_image.py the voice package in a real core of a given Home Assistant image
examples/home-assistant/
insulin_sprache.yaml de-identified snapshot of the author's voice package (see "The author's setup")
test-rig/ throwaway Nightscout, emulator notes and findings (see test-rig/README.md)
The tests import the core as the top-level package core
(pyproject.toml, pythonpath), so they never import Home Assistant.
Guard (in guard.py) is the only object a caller needs. Every method returns
a dict with ok, outcome, reason (short English code) and text (German).
| Call | Does |
|---|---|
pair(text) |
Pairs from the text of the master's QR code "Nightscout and pairing". Stored only after the key exchange and a verified pong. |
ping() |
Signed round trip; changes nothing on the master. |
arm() / disarm() |
The switch. Off at start; turns itself off after arm_duration_s, after arm_max_commits and at the prepare after arm_max_prepares. In Home Assistant arm() is reached from the options dialog and the arm button, not from a service. |
resume_delivery() / close() |
Goes on watching a delivery whose watch the end of the last process cut off; ends the watch thread without a result. |
prepare("meal", carbs=…) / prepare("units", units=…) |
Asks the master for a proposal. Returns the master's amount and a one-time code. Nothing is delivered. |
confirm(code) |
Sends the commit. accepted, refused, failed or unknown. |
delivery() / wait_delivery() |
What became of an accepted commit: delivering, delivered, failed, unknown. |
cancel() |
Drops the proposal here. |
status() |
Pairing, switch, counters, missing limits, deadlines, source pin. No secrets, no code. |
Rules kept in the core, whatever the caller does:
- Limits default to refuse.
Limits()has every value at 0 or empty, and 0 means refuse. A request above a ceiling is refused, never trimmed; so is an amount the master calculates above the ceiling. - The code is made in the guard, valid once and for
code_ttl_s, compared in constant time and never logged. A wrong code uses the proposal up. - Minimum interval and 24-hour ceilings (count and total) are written to
state.jsonbefore the commit is sent and survive restarts. If that write fails, the commit is not sent (reasonStorage); the same holds for the message counter of every command. A commit whose outcome is unknown counts. A clock that was set back does not shorten the wait. - Glucose for the gates is read by the core from Nightscout
entries, with an age limit. The caller cannot pass a value. - One deadline per operation (
client.OPERATION_DEADLINES_S: ping 30 s, prepare 40 s, confirm 40 s, pair 110 s). It covers every Nightscout call and the wait for the master; a call returns at most about one second later. Set caller timeouts above these values. The watch after an accepted commit runs in a background thread outside the deadline. - Nothing is sent twice. The counter is stored before sending. Without a
terminal answer the outcome is
unknown; for a commit the text says that the dose may still arrive, andmay_start_until_mssays until when the master could still start it (the commit is valid for 8 s by the master's clock). - After an accepted commit the ack document and the master's signed progress
document are watched until
Complete,Cleared, aDeliveryack whose status is notOk, 75 s without a first frame, or 30 s without news after the first frame. No prepare, no ping and no pairing while that runs, also across a restart (open_deliveryin the state, seeresume_delivery). - Clock. The master's signed time stamp is compared with the local clock; more than 15 s apart is refused at ping, pairing and prepare.
- Errors. A 4xx from Nightscout is reported as an error with its status;
5xx or no answer to a write is
unknown.ExecutionFailedfrom the master for a commit isunknown, not "nothing delivered". A result of 0 units cannot be confirmed. "Record only" doses are never sent.
pair(text):
- Reads the text (never stored, never taken from the command line).
- Sends the hello with a fresh P-256 public key, signed with the secret from the text, and sends it again with a new key until the master's signed key answer arrives or the pairing window ends.
- Derives the new secret (ECDH, HKDF-SHA256 with the old secret as salt) as
ClientControlKeyExchangeCryptodoes, takes the client's own Nightscout token from the answer if there is one and a login with it works. - Pings with the new secret. Only a verified pong stores the pairing. The
master makes the new secret the only one with the first message signed with
it, whether or not its answer arrives (
ClientControlReceiver.kt:331-337). So once a ping may have reached the master, no further hello is sent (the old secret could not be answered); the ping is repeated with the new secret until the pairing window ends. If that fails too, the error says that the client has to be deleted and created again on the master.
The key answer's time stamp is compared with the local clock before anything is signed with the new secret; more than 15 s apart is refused, and the same pairing text can be tried again once the clocks are set.
An existing pairing stays in place until step 4 succeeds. A text naming the stored client id only pings. When no answer comes, the error names the reasons for which the master stays silent (websocket down, client deleted, pairing window over, clocks more than five minutes apart, old counter, bad signature). PIN pairing is not implemented.
The integration keeps the same two parts in one storage file, see "What is stored where". The command line uses one directory (mode 700), two files (mode 600):
secrets.json: Nightscout address and token, client id, pairing secret; with the CLI also the switch and the open proposal with its code.state.json: message counter, commit log for the interval and the 24-hour ceilings, last pong, measured clock difference. No secret.
Keep the directory out of any repository and out of backups that leave the machine. After restoring an old copy the counter is behind the master's; the core notices and asks for a new pairing.
export PYTHONPATH=custom_components/aaps_client_control
export AAPS_CC_DIR=/path/outside/any/repository
python -m core.cli pair # paste the QR text on stdin, or: pair --file code.txt
python -m core.cli ping
python -m core.cli status
python -m core.cli arm
python -m core.cli prepare --carbs 30 # or --units 1.5 (placeholders)
python -m core.cli confirm # code on stdin; waits for the delivery outcome
python -m core.cli cancelLimits come from $AAPS_CC_DIR/limits.json (keys as in guard.Limits, all
thirteen of them). Without that file everything is refused. The command line has
its own arm: it is one local process with its own state directory, not a
service surface. If a confirm process ended before its delivery watch did,
the next command of any kind first finishes that watch and prints its result.
# the core alone (Python 3.13 or newer)
pip install cryptography pytest
pytest -q
# with the integration tests (needs the Python version of the Home Assistant release the package pins;
# tests/ha/test_voice_package.py is left out unless AAPS_CC_VOICE_PACKAGE is set, see below)
pip install pytest-homeassistant-custom-component
pytest -q
# transport against a local throwaway Nightscout (loopback only):
AAPS_CC_LOCAL_NS_TOKENS=/path/to/token-file pytest -q tests/test_local_nightscout.py
# manifest, services and translations
docker run --rm -v "$PWD":/github/workspace:ro ghcr.io/home-assistant/hassfestThese checks run a voice package file against this integration and the fake
master: the snapshot in examples/home-assistant/insulin_sprache.yaml, or the
package as it is in a Home Assistant configuration (<config>/packages/insulin_sprache.yaml).
The test reads the entity ids that differ between installations (the satellite
that announces the arming, the phone's notify action) from the file. None of
the checks covers speech recognition, a real satellite or a real language model.
# sentences -> package -> integration -> fake master (needs hassil and home-assistant-intents as well)
AAPS_CC_VOICE_PACKAGE=examples/home-assistant/insulin_sprache.yaml pytest -q tests/ha/test_voice_package.py
# the same flow in short, in a Home Assistant version the pytest plugin does not support yet
docker run --rm --network none -v "$PWD":/repo:ro -v "$PWD"/examples/home-assistant:/pkg:ro \
ghcr.io/home-assistant/home-assistant:2026.11.3 python /repo/tools/voice_in_image.py
# which sentences start which sentence trigger, across all packages of a configuration, in the
# registration order of a running system (armed: sprache_insulin last; not armed:
# sprache_insulin_nicht_scharf instead); <config> holds packages/insulin_sprache.yaml
docker run --rm --network none -v <config>:/wt:ro -v "$PWD"/tools:/chk:ro \
ghcr.io/home-assistant/home-assistant:2026.11.3 python /chk/voice_sentences.py /wtstop_bolus.- Removing a command document after an unknown outcome: the master's own comments say a delete leaves a tombstone that makes the next write to the same identifier fail with HTTP 410, and the client role has no delete right. The short validity of the commit bounds a late start instead.
- A message that drops a prepared dose on the master: AAPS 4.0.0 has none.
cancel()forgets it here; on the master it lapses by itself. - PIN pairing.
MIT, see LICENSE. Provided "as is", without warranty of any kind.
AndroidAPS is published under the GNU Affero General Public License, version 3
(AGPL-3.0). This repository contains no AndroidAPS source files. The Python
code is an independent implementation of the AAPS 4 client-control wire
format, written by reading AndroidAPS 4.0.0 (commit
f77abd9b82b308e8fc330da0d7a31370fb4a0f49) for interoperability; the
comments cite that source by file and line. These items are taken from it
verbatim because they are the interface itself or AAPS's own published test
values; they remain with their copyright holders:
- the three HMAC test vectors, inputs and expected outputs, in
tests/test_vectors.py, fromcore/nssdk/src/commonTest/.../ClientControlCryptoVectorsTest.kt, with the IV byte pattern and the base timestamp of those tests (also intests/fake_master.py); - the test token
aapstablet-0123456789abcdefand the addresshttps://ns.exampleintests/test_vectors.py, fromClientSetupCodeTest.ktandClientControlKeyExchangeCryptoTest.kt; - protocol constants and names in
custom_components/aaps_client_control/core/protocol.pyand the core:aaps-clientcontrol-key-v1,aaps_clientcontrol_,aaps-client-setup, the document date946684800001, the message, reason and role names, and the canonical field orders; - one short source comment quoted, with its source, in
test-rig/notes/nightscout-upload-collision.md(fromPatchManager.kt).
The key derivation (derive_keys, decrypt_token in core/protocol.py) and
the fake master (tests/fake_master.py) follow the behaviour of AndroidAPS's
ClientControlKeyExchangeCrypto and ClientControlReceiver, without sharing
their text. The HKDF vector in tests/test_vectors.py is test case 1 of
RFC 5869. The test-rig notes cite Nightscout (cgm-remote-monitor, AGPL-3.0) by
file and line.
Credit and thanks to the AndroidAPS project (https://github.com/nightscout/AndroidAPS, AGPL-3.0), whose client control this integration talks to.