# Bil Butler

Self-hosted web app for one household, one Škoda and an optional Zaptec connection. Trial release 0.6.2. The interface is available in Danish and English using the language links at the top.

## Included

- Set up your own car, API key and DK1/DK2 electricity price area.
- View the car’s last known battery level, estimated range, cable, charge target and charging status, including measurement times.
- Confirm charging start/stop and 80/90/100% charge targets through Škoda, where supported by the car.
- Configure two preheating departures per day for all seven days. Preheating starts 30 minutes before departure, with a requested temperature and optional cable requirement. An acknowledged session retains its original stop request when the schedule is edited or paused.
- Fetch today’s and tomorrow’s published spot prices for DK1 or DK2. Prices exclude VAT, tariffs and taxes.
- Optionally add Zaptec with a serial number and an approved access token or API service account. Read measured power, session energy and completed history. Service accounts support automatic token renewal; live push requires existing Service Bus access.
- Local owner login, encrypted storage, shared API pause handling and a persistent action journal. Unresolved actions are not automatically repeated.

## Cheapest charging time and full-session cost

Charging advice works without a vehicle account. Enter usable battery capacity, current charge, target, charging power, loss percentage and departure time. Choose DK1 or DK2. A connected car can supply charge level only when both its measurement and fetch timestamps are at most 30 minutes old. Calculation does not request a vehicle refresh.

The app finds the cheapest **continuous** charging session before departure minus the selected buffer. It compares the entire session with the same energy charged immediately. Cost uses grid energy including losses: spot price plus entered VAT, grid tariff, supplier surcharge and other taxes including VAT. Enter a flat grid tariff or 24 hourly values for weekdays and weekends. Fixed subscriptions are excluded. Check your own electricity bill; tariffs are not guessed.

Results show battery energy, grid energy, losses, cost, estimated savings and price fetch times. Public Elprisenligenu prices are cached for up to an hour. Only published prices are used, with no forecasts. Missing intervals produce no cost or savings estimate. Departure is limited to 48 hours ahead. All times use Europe/Copenhagen, including daylight saving. Negative prices and partial price intervals are supported.

Calculation provides advice and does not start the car. You can then activate the specific session separately as described below. The vehicle charge limit is not changed automatically. Constant power is assumed; cold weather, vehicle limits and shared power can change actual results. Recalculate when charge level, prices or inputs change. Saved results are labelled as last calculated.

## Automatic vehicle charge-limit setup

Select **Also allow automatic vehicle charge-limit setup** in standing settings, or **Also set the vehicle charge limit automatically for this plan** for a single session. Confirmation includes the chosen value and permission to change it. Only 80, 90 and 100% are supported. Existing installations do not receive expanded permission on update; reapprove standing settings with the option enabled.

The limit is set **when a planned charging window begins**, with the car connected and ready. A limit that may enable more charging is not changed on saving. If the battery is already above the selected level and the car is ready, the limit can be lowered without starting charging; this also requires confirmation in a newer reading. This avoids triggering charging outside the approved window when raising a limit. No change is sent if the value already matches.

At most one PUT is sent per plan. Acknowledgement is separate from a newer vehicle reading confirming the selected value. Only then may a separate charging start be sent. Up to three automatic confirmation reads are made; unknown requests are never replayed, including after restart. A later manually refreshed reading can resolve the outcome. Late confirmation does not trigger a late charging start.

Raising a limit may itself start charging. When a newer reading reports the requested limit and charging state, no additional start is sent. Positive power must still be observed before physical charging is marked confirmed. The stop obligation remains because the limit change may have started charging, including when a separate start is rejected, the app restarts or the plan is cancelled.

A cancelled, unresolved limit request may still be delayed at the provider. The session is therefore not declared finished until a newer reading confirms both the requested limit and stopped charging. Otherwise the owner must check the car, potentially in its own app. Unknown start, limit and stop requests are not automatically resent.

## Self-planning charging without daily approval

Self-planning is off on installation. Initial setup:

1. Add your own Škoda access and read vehicle status. In Charging plan, enter usable capacity, target (80/90/100%), power, losses, DK1/DK2 and all variable tariffs. Calculate and check the settings once.
2. Under **Self-planning charging**, choose one fixed departure per day with individual enabled days. Select the first/second occurrence for a repeated autumn departure hour.
3. Enable the feature, click **Save standing charging settings**, and approve ongoing calculation and execution. A snapshot of the calculated inputs and tariffs is stored. The first calculation must be no more than ten minutes old.

No daily approval is needed afterwards. The server finds the next enabled departure, reads vehicle status approximately every five minutes when planning is needed, and calculates remaining energy from **fresh vehicle SOC** to the saved limit. The original manually entered battery level is not reused. It selects the cheapest continuous session using all published price intervals, losses, VAT and the saved variable tariffs.

Without automatic limit permission, the saved vehicle limit must already match. With permission, it is set as described above. Other vehicle schedules and charger settings are not changed. The cable must be connected, car ready, quota sufficient and measurements fresh. Existing charging is not taken over. Missing prices, old status, unknown cable or insufficient time produces waiting status or a concrete error, never invented savings or fulfilled need.

A waiting plan can be recalculated after price or SOC changes. The first plan and previous window/cost are retained with a reason. Started or unresolved sessions are not moved. Each departure permits at most one start attempt, including rejected or timed-out attempts. The next departure is planned automatically after completion. A new need after charging was already attempted for the same departure requires manual handling; failures must not cause repeated starts.

**Pause planning and stop its session** revokes ongoing permission and cancels waiting. If charging was already requested by this feature, its stop obligation remains. Manual cancellation, Stop or other manual charging controls also pause planning, preventing immediate re-creation. The vehicle cannot be changed during active permission; a key may be renewed for the same car.

Planning covers the next departure within 48 hours. Disabled days require no extra vehicle reads when the next departure is further away. Nonexistent spring-time departures are skipped, not moved to a different hour. All features share the same cache and quota; public prices are reused for up to an hour. A known quota reset can resume planning. The occurrence ledger is capped at 90 entries. Disposable price caches retain seven previous days; approved calculation snapshots and settings are preserved.

The server must stay on and online. Permission, prices, plans and journal are encrypted and survive restarts. Unknown command results are not retried. See below for confirmed stop and physical-effect limits. Update tariffs through a new calculation and saved standing settings; this does not silently alter a session already started.

## Automatic charging at the cheapest time

1. Add your own Škoda key and read vehicle status. The cable must be connected and the car **ready to charge**, without charging already. Existing charging is not taken over or stopped to move it.
2. Choose 80, 90 or 100%. Enable automatic limit setup or make sure the saved vehicle limit already matches. Other charging settings are not changed.
3. Calculate Charging plan with actual needs, full variable tariffs and departure. Click **Activate this charging plan** and confirm the displayed window, cost and target. The calculation must be at most ten minutes old. Only one plan may be active.
4. The server checks vehicle status on activation, approximately every five minutes while waiting and again before start. Both the measurement and fetch must be at most two minutes old before starting. Changed charge level, cable, limit, existing charging, missing data, insufficient quota or an expiring key block start. Activation sends no charging command.
5. Start is sent once when the window begins. Actual charging requires a newer measurement reporting charging and positive power. Stop is requested on an observed charge target, cancellation, charging error or window end. Stop and target reached are reported separately.

The plan runs with the browser closed. The server must stay on, online and authorised. After a restart a waiting plan continues only if its start was not missed; a start already sent is never replayed. The original plan retains its stop obligation through cancellation or restart. Neither an unknown start nor an unknown stop is repeated. Up to three new reads can confirm stop; a later manually refreshed vehicle measurement can also resolve it. If quota is missing, stop can wait for quota only while no stop command has been sent yet.

**Cancel and stop this session** cancels waiting or sends one stop for the charging this plan requested. The ordinary Stop button also cancels an active plan. Manual start and charge-limit changes are blocked while the plan still owns the session. A key can be renewed for the same car, but the vehicle cannot be replaced mid-session.

If the network, server or API fails, charging may continue to the car's own limit. Stop cannot be guaranteed without a connection. Check the vehicle when status needs attention. Missed starts are not replayed and prices/windows are not silently changed. Recalculate and approve a new plan after changes. This is one session per approval, not a recurring daily plan. Zaptec remains optional and read-only; execution uses Škoda charging functions without requiring Zaptec.

## Easier HTTPS installation

Install Docker Engine with Compose or Docker Desktop first. Extract the ZIP into a new folder and open a terminal in `bil-butler`:

    sh ./install.sh

Windows PowerShell:

    ./install.ps1

Choose home network or public domain, then enter the address. Setup creates the HTTPS proxy, app and separate data volumes. It does not change routers, other services or phone certificate trust. Ports 80 and 443 must be free. Do not stop other services to resolve a conflict; local mode can use other ports, for example:

    sh ./install.sh --mode local --host 192.168.1.50 --https-port 8443 --http-port 8080 --backend-port 8799

Use your server's actual LAN address, not this example. A stable address is recommended. Local mode binds only that LAN address; the direct application port remains loopback-only.

### Home network and iPhone

Setup prints the HTTPS app address and an HTTP instructions page at `/__bilbutler/setup`. HTTP serves only public certificate setup, never login or keys. Use the printed server commands to inspect the certificate fingerprint before trusting it. On iPhone:

1. Open the instructions page in Safari, download your installation's root certificate and allow the profile.
2. Settings → General → VPN & Device Management → install the downloaded profile.
3. Settings → General → About → Certificate Trust Settings → enable full trust for Bil Butler Local.
4. Open the HTTPS app address, then Safari → Share → Add to Home Screen.

Trust only your own server's certificate. Do not bypass certificate warnings. Android can install the CA under Security settings; device policy may restrict this. Certificates and data stay on your server.

### Public domain

Choose public mode with your own DNS hostname. DNS and external ports 80/443 must already reach the server. The proxy attempts to obtain and renew a publicly trusted certificate automatically, removing the phone CA step. This exposes the login to the internet: select it only if you intend public access. No DNS credentials or tunnel are created.

### Owner setup and updates

Retrieve the one-time setup code privately on the server:

    docker compose -f compose.yaml -f compose.https.yaml exec bil-butler cat /data/setup-token

Open the HTTPS address, choose Dansk/English, enter the code and choose a password of at least 12 characters. Use charging advice immediately without a vehicle account. Add your own vehicle and optional Zaptec later. The code can create the owner only once.

To update: back up the full application volume and encryption key, keep the same project folder, `.env`, `https/`, `compose.https.yaml` and volumes. Replace application files from the ZIP, then run:

    docker compose -f compose.yaml -f compose.https.yaml up -d --build --wait

Never use `down -v`. Do not rerun initial setup for a normal update. `--replace` is only for an intentional HTTPS configuration change and first copies existing configuration. Keep `caddy-data`, containing private certificate keys, secret and backed up. Replacing the local CA requires renewed phone trust.

Local development without phones can still use `docker compose up -d --build` and http://localhost:8788. An existing reverse proxy must preserve Host and set BUTLER_ORIGIN correctly. Incorrect Host/Origin values are rejected. No shared cloud account or tunnel is created.

## Development

Use Python 3.14 with an isolated environment:

    python3 -m venv .venv
    .venv/bin/pip install -r requirements.txt
    .venv/bin/python server.py --data data --origin http://localhost:8788

The initial setup token is in data/setup-token.

    .venv/bin/python -m unittest discover -s tests -v

The English HTML and JavaScript are generated from the Danish files and translations.json:

    .venv/bin/python build_languages.py

## Credentials and data

Create your own key for your car in MyŠkoda under Profile → Smart Home. Do not provide your MyŠkoda password. Optional Zaptec service-account credentials for automatic token renewal are encrypted on your own server; a pasted token requires manual replacement. Only documented HTTPS endpoints are used. Provider redirects are not followed.

Settings, keys, journal entries and cached car data are encrypted in SQLite. The encryption key is stored separately in the same data directory. An administrator who has both the key and database can read the data. Keys are never returned to the browser or written to application logs. Exclude the data directory from Git.

Back up the entire Docker volume, including the database and encryption.key. Stop the container before manually copying the volume. Keep the volume during updates. Without the encryption key, data cannot be restored. The journal retains roughly 500 completed events, with active preheating sessions preserved for their stops. Only one process may own a data directory. Restarting logs the owner out while retaining saved settings, schedule and journal.

Preheating requires an online server, valid credentials and sufficient API quota. Missed departure times are not replayed. An acknowledged request does not prove the cabin became warm. Check the car and journal when an error occurs.

## Licensing

This is an independent project. No official logos or vehicle photographs are included. MIT applies to this project’s own code. API terms and dependency licences apply separately. Free software and a user’s own key do not constitute additional permission to use provider services.

- MyŠkoda Public API is for personal use and excludes commercial products/services according to its documentation. https://public.api.connect.skoda-auto.cz/docs
- Zaptec API rules and third-party access. https://docs.zaptec.com/docs/api-fair-use-policy
- Spot prices excluding VAT and taxes. https://www.elprisenligenu.dk/elpris-api
- Encryption. https://cryptography.io/en/latest/fernet/

## Verification

158 isolated tests with simulated provider responses and hand-calculated price examples pass. No real credentials or vehicle commands have been used in testing. Docker installation has been verified in a separate Debian 13 test container with fictional data. An iPhone 16 simulator is used for HTTPS, login and home-screen mode. Operation on a real car/charger remains unverified. Source code has not been published on GitHub.

## New in 0.1.2

Form controls use at least 16 px text to prevent automatic Safari zoom when logging in on iPhone. Controls can shrink to fit narrow screens. Manual page zoom remains available. Vehicle functions, weekly scheduling and the data format are unchanged.

## New in 0.1.3

The approved Bil Butler logo appears in the header in both languages and is included with the installation. The Safari fix from 0.1.2 is retained.

## New in 0.1.4

The car and bow tie are used as the home-screen app icon. Apple touch and manifest icons are included in both languages. An existing shortcut may retain its cached icon; recreate only the shortcut if needed, while keeping the installation and its data. The Safari fix from 0.1.2 is retained.

## New in 0.2.0

Charging advice with full-session cost, losses, tariffs and an immediate-charge comparison. HTTPS setup with a separate proxy and local CA instructions. No new automatic vehicle control.

## New in 0.3.0

One approved automatic session with start at the calculated cheapest time, durable journal, restart handling, stop and separate confirmation from vehicle measurements. Activation and cancellation were tested with fictional data. No real accounts or physical vehicle commands were used. Real vehicle/charger testing remains outstanding.

## New in 0.4.0

Standing vehicle-bound permission with seven departures and automatic planning/activation without daily approval. Waiting plans retain their original window through updates; manual takeover pauses permission. 90 simulated-response tests pass. Up to five seconds of forward clock skew is tolerated; old-data limits are unchanged. No real car or charger has been tested.

## New in 0.6.2

Optional charge-limit setup when a window begins, confirmation from vehicle readings, charging triggered by a limit change, and restart/unknown-result handling without retries. 158 simulated-response tests pass. No real vehicle commands or private accounts/keys have been used.

## Zaptec · telemetry, history and token renewal

Read-only integration: no start/stop commands, current limits or charger settings. Vehicle plans still execute via Škoda. Disabled Zaptec makes no background requests.

Enter your charger serial and either a pasted token or your own approved API service account. Pasted tokens require manual replacement. Service account email/password are encrypted on your own server and never returned to the browser. Blank password retains it; switching to token mode removes saved service account credentials. Approved owner/service API permissions are required; this app cannot grant API access. The documented password grant requests a new access token before expiry. Rejected credentials stop automatic login attempts until settings are corrected. No undocumented refresh-token flow is assumed.

For live push, enter a user group ID with Service Bus access already enabled by Zaptec. Fresh connection details are obtained over verified HTTPS before every reconnect; secure AMQP WebSocket receives observations. No subscription or installation configuration is changed. Without push, the refresh button reads current REST status at most once a minute; there is no continuous state polling. Each observation retains its source timestamp. Values older than two minutes are marked last known. A connected push channel does not imply a fresh measurement.

Completed sessions use `/api/sessions/archived`, charger/date filtering and cursor pagination. History synchronizes hourly, at most five pages per pass, continuing large imports on the next pass. The last week is reread for corrections and the full 365-day window is checked daily. Retention is the last 365 days / 2,000 sessions; limits and incomplete synchronization are shown. Duplicate IDs are merged; voided/replaced records remain documented but excluded from totals. These are charger-delivered kWh, not energy stored in the vehicle, and may include guests/other vehicles. They are not added to the vehicle ledger. Last known data survives errors; rate limits respect Retry-After and increasing backoff.

158 tests pass with simulated responses, including a simulated AMQP receiver. Real Zaptec accounts, physical chargers and a real Service Bus connection remain untested. Current provider prerequisites:
- https://docs.zaptec.com/docs/api-authentication
- https://docs.zaptec.com/docs/zaptec-service-bus-subscriptions
- https://docs.zaptec.com/reference/api_sessions_archived_get

## Graceful shutdown (0.6.2)

Docker stop / SIGTERM and Ctrl+C / SIGINT reject new requests and wake waiting workers. Admitted HTTP requests and background work, including the push receiver, drain before the database and instance lock close. Plans, consent, history and settings are not reset; shutdown sends no additional vehicle commands. Compose allows up to two minutes for in-flight work. A stuck process or power loss can still cause a hard shutdown. Take file backups only after the app has fully stopped.

## Disk errors and unresolved commands (0.6.2)

Failed database/status writes no longer terminate the scheduler. It waits for the next normal attempt and can resume after space returns. /api/health and Docker healthcheck report an error during the disk failure, when a worker is dead, or after more than two minutes without a successful scheduler tick. Health needs no private settings or database writes. Recovery never authorizes replay of an unknown write or catch-up of a missed charging start.

The 500-record retention limit excludes pending events (sending, unknown, unresolved), regardless of age or newer history. Internal safety checks read the whole journal, so old barriers are not hidden behind a 2,000-row read limit. Pending events are prioritized in the action overview. Existing future climate-stop protection remains. Records already deleted by older versions cannot be automatically recovered.
