Skip to content

About

This is a proxy for the Solcast PV forecast hobbyist API. It allows multiple API consumers despite limited hobbyist API quota (typically just ten updates daily), and incorporates schedule and state information in endpoint responses.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

JavaScript Solcast Solar hobbyist API Proxy

This is a JavaScript Worker proxy for the Solcast Solar hobbyist API.

Originally designed to run on the Cloudflare Workers free tier, it can also be run locally with Wrangler.

It is compatible with the Home Assistant custom component integration Solcast Solar, which is available via the Marketplace for 3rd party components. See the ADVOPTIONS.md file there for the way to configure it to use a proxy. The minimum supportable version of the Solcast Solar integration is v4.7.0, with specific proxy-aware capabilities added in that release to match this repository reference implementation.

This proxy does not need to be used with the Home Assistant Solcast Solar integration, and will function independently.

The worker provides forecasts, estimated actuals, scheduling guidance and cached rooftop resource serving, allowing multiple consumers to utilise a limited number of hobbyist API calls for more than one API consumer. Multiple Solcast API keys will also be proxied by a single instance.

Contents

Architecture

  • Runtime: Cloudflare Worker (proxy_cloudflare.js), but will run in Wrangler with a Python launcher.
  • Coordinator: one Durable Object (ProxyCoordinator).
  • State store: SQLite-backed Durable Object storage.
  • Scheduler model:
    • Worker cron trigger is a fixed per-minute tick (* * * * *) with light runtime.
    • Coordinator computes due forecast/actual update times from its schedule.
    • Retries are alarm-driven for efficiency and effective back-off delay between attempts.

An entirely local proxy worker is possible without bothering with Cloudflare. See Local Simulator Workflow, and get hints from the example toml. In short, run on Linux/Mac/Windows/+ with prerequisites, and set the Solcast host/port to api.solcast.com.au/443 in wrangler.toml. By doing so the Python launcher can be used to spin up the worker on any server using wrangler and bind the proxy to all interfaces by default or one specific interface.

An alternative Docker deployment is also templated in this repository. Set up the wrangler.toml to point at api.solcast.com.au with desired scheduling and then docker compose up -d --build. It will have a self-signed certificate, so test (and bootstrap) with something like curl -ksS "https://localhost:9443/rooftop_sites?format=json&api_key=my2E8APIykeysgoesxaheregkblahPuv".

Behaviour

  • There are three schedule modes:
    • cron, fetching updates at specific times of the UTC-based day.
    • daylight, dividing sunrise-to-sunset into UPDATE_DIVISIONS equal intervals and fetching at the start of each interval. The first update is at sunrise; the last is one interval before sunset, closely matching the Home Assistant integration's interval approach, but rounded to whole minutes.
    • all_day, spreading updates over 24 hours, with optional additional updates at specific times.
  • A schedule for the day ahead, rebuit on startup and the first cron tick of the new UTC day.
  • Discovery-backed site registration and stale-site cleanup. "Bootstraping" the proxy is by way of requesting rooftop sites for an API key or keys.
  • Forecast collection is always scheduled; estimated-actuals collection is optional and disabled by default.
  • Home Assistant integration retry model is lock-step: one retryable failure puts participating resources into coordinated retry where they follow the proxy retry delay advice.
  • While retry is active, scheduled tick forecast collection is suppressed and retries are handled by the Durable Object alarm.

Home Assistant: Switching between direct API access and the proxy

Deploy the proxy whenever convenient, but coordinate when it starts collecting with when the Home Assistant integration stops calling Solcast directly. If the remaining quota is uncertain, stop updating forecasts directly to Solcast before UTC midnight and start the proxy after the reset. Scheduling consistency for the Home Assistant integration and proxy might matter during the switch, with daylight scheduling very close to the integration sunrise to sunset scheduling.

The Home Assistant integration persists its own API usage counters and resets daily usage at UTC midnight, not local midnight. These counters are local bookkeeping, not a live Solcast account balance, and they are not transferred to or synchronised with the worker. The proxy does not know how many calls were already made directly (and does not care), and the integration cannot account for every upstream call made independently by the proxy. Repeated cache reads do not result in upstream calls.

Keep the integration's existing sites, usage, forecasts and other cache files, as they will be compatible.

Direct access to proxy

  1. Deploy and configure the Worker, allowing for the number of sites, API keys and enabled resources when choosing its collection schedule. If you wait until its per-minute cron is visibly firing in the Cloudflare Observability logs before switching the integration (which can take 5-10 minutes) then the configured schedule can be verified in the logs. A fresh deployment with no activated sites does not collect forecasts merely because cron is running; it needs rooftop sites discovery.
  2. Stop direct collection by every consumer that will share the proxy's API key, then change the integration's advanced Solcast URL and port settings to the proxy endpoint as described in the integration's advanced options. Keep the same API key and existing caches, and reload the integration. Successful rooftop sites discovery registers its sites for scheduled collection, and the integration loads the proxy schedule on startup. A new proxy has no forecast cache until its first successful scheduled collection, so data will not be immediately availabile.
  3. If switching during a UTC day, allow for calls already made directly plus the proxy's remaining collections for today. The integration's existing local usage count may also prevent further fetches until UTC midnight reset, although an integration advanced option allow_exceed_api_limit_maximum is enabled by default when a non-standard solcast_url is in use so updates will not be limited by default. Switching just after the UTC reset is simpler, but not mandatory when you know there is enough remaining quota. Scheduling should adjust. Check /proxy_status and the integration logs rather than forcing extra updates to test the transition.

Proxy to direct access

  1. Stop upstream proxy collection for the API key before restoring direct access. This includes scheduled cron collection and any pending alarm-driven retries; removing cron alone does not cancel an existing retry alarm, so deleting the worker is advised.
  2. Restore the integration's default Solcast URL and port settings, or remove the advanced options and reload it. Direct discovery clears proxy mode, and the integration resumes its own scheduling. Keep the existing usage counters and forecast caches, but do not assume the counters are correct. For a predictable fresh daily budget, stop proxy collection before UTC midnight and resume direct collection after the reset.

Runtime controls (wrangler.toml [vars])

  • SCHEDULE_MODE: cron, daylight, all_day.
  • FORECAST_CRONS, ACTUALS_CRONS: semicolon-separated cron list (used in cron mode).
  • UPDATE_DIVISIONS: number of forecast slots for daylight/all_day.
  • SCHEDULE_EXCEPTIONS_UTC: JSON array or CSV of additional forecast collection times in UTC, in any schedule mode. HH:MM entries repeat daily; full ISO timestamps apply only on their UTC date. Duplicate times are collected once, and the estimated-actuals schedule is unchanged. For example, SCHEDULE_EXCEPTIONS_UTC = '["07:40"]' adds a forecast collection at 07:40 UTC, even outside daylight hours. Each additional time uses extra upstream quota per registered key/site pair.
  • ENABLE_ESTIMATED_ACTUALS: true/false toggle for scheduled estimated-actuals fetching (default: false).
  • LATITUDE, LONGITUDE, TIMEZONE: required for daylight/all_day.
  • ACTUALS_DELAY: minutes after local midnight baseline for actuals in daylight/all_day (mimicks the HA integration advanced option estimated_actuals_fetch_delay).
  • POLL_DELAY_SECONDS: fixed follow delay in cron mode; configured/default reference for adaptive modes.
  • POLL_DELAY_MIN_SECONDS: adaptive floor delay for daylight/all_day polling advice.
  • MAX_ATTEMPTS: maximum retry failure cycles before give_up is reported to downstream consumers.
  • RETRY_BACKOFF_SECONDS: retry backoff base for alarm scheduling.

Forced updates

It may be that you have "exceptions" to the auto-update daylight or all day update times, and if you are using the Home Assistant Solcast Solar integration then these will be configured using an automation to perform a "forced" update. This is not the way that this proxy expects an exception to that scheduling to occur.

Additional updates must be specified using the SCHEDULE_EXCEPTIONS_UTC runtime control in this proxy, which will cause the integration to fetch an update just after that specific time. In contrast, a forced update will only get the most recently acquired cached update, and will work, just will not cause an actual Solcast update to occur.

When a SCHEDULE_EXCEPTIONS_UTC set of additional updates is configured then these will be handled by the integration auto-update feature.

Endpoints

  • GET /rooftop_sites?format=json&api_key=...
  • GET /rooftop_sites/<site_id>/forecasts?format=json&api_key=...&hours=...
  • GET /rooftop_sites/<site_id>/estimated_actuals?format=json&api_key=...&hours=...
  • GET /proxy_schedule (alias /schedule)
  • GET /proxy_status (alias /proxy-status)
  • POST /__scheduled (internal/manual scheduler entrypoint)

The proxy supports multiple API keys and learns which sites belong to each key when a client calls GET /rooftop_sites through the proxy for that key. It forwards the request to Solcast and stores the successful discovery response, including site metadata.

Successful discovery registers every returned site for scheduled forecast collection and, when enabled, estimated-actuals collection.

Either a valid downstream resource request or a successful upstream resource collection keeps each key/site pair active. Activity on forecasts or estimated actuals keeps both kinds active for that pair, without affecting other sites or keys. After 24 hours with neither kind of activity, its resource state and cached data are deleted and collection stops. Failed or malformed upstream responses do not refresh activity. Successful scheduled collections can keep a site active even if clients stop requesting it.

Successful discovery refreshes the API key's discovery data but does not renew existing sites' activity windows or replace their cached data. Later successful discovery calls register newly returned sites and remove resources for sites no longer returned for that key. Keys and their discovery data expire after 24 hours without successful discovery, a valid site-specific request, or successful resource collection.

Forced cached responses

Add &force=true to any of the three /rooftop_sites requests above to return the last known successful response for that API key and, where applicable, site and resource kind. This bypasses previous upstream failures, active retries, rate limiting, exhausted budgets and permanent collection failures for a read. It does not force an upstream fetch.

  • force is a proxy-only parameter, and is never forwarded upstream.
  • Bare force and the values true, 1, yes and on enable it; values are case-insensitive. Omitted force, false, 0, no, off and unrecognised values retain normal behaviour.
  • Forced sites discovery uses the persisted successful site list, but does attempt to get fresher data from Solcast; it returns cached data even if the upstream call fails. An empty successful site list is valid.
  • Forced forecasts and estimated actuals still validate format=json and positive hours, and apply the normal current-time window filtering. Old cached data can therefore produce an empty array; force does not make expired data current.
  • With no successful response cached, the proxy returns HTTP 503.
  • Collection/retry headers remain true to present state, even with HTTP 200: inspect x-proxy-last-success-at, x-proxy-upstream-status and x-proxy-last-fetch-status to assess freshness and collection failures.

The Home Assistant Solcast Solar integration never utilises the force parameter, with it favouring situational awareness and lock-step behaviour over receiving potentially out-of-date information; it caches the latest forecasts and sites data so it does not need this proxy mechanism. Your other scripts and code may need it.

Example wrangler.toml

Cloudflare workers are deployed using wrangler being installed on a remote system like a laptop, with the JavaScript code in the same folder as the wrangler.toml. All files in that folder generally get packaged up in the upload compressed package, so keep that folder slim.

This is an example configuration.

name = "solcast-proxy"
main = "proxy_cloudflare.js"
compatibility_date = "2026-11-10"

[triggers]
crons = ["* * * * *"]

[[durable_objects.bindings]]
name = "PROXY_COORDINATOR"
class_name = "ProxyCoordinator"

[[migrations]]
tag = "v1"
new_sqlite_classes = ["ProxyCoordinator"]

[vars]
SOLCAST_HOST = "localhost"
SOLCAST_PORT = "8443"
#SOLCAST_HOST = "api.solcast.com.au"
#SOLCAST_PORT = "443"

# Schedule modes: cron | daylight | all_day
SCHEDULE_MODE = "all_day"

# cron mode supports one or more cron expressions separated by semicolons (free tier has a number of crons limit)
#FORECAST_CRONS = "30 11,0,1,2,3,4 * * *"
#ACTUALS_CRONS = "05 14 * * *"

# daylight/all_day mode: number of spread updates per day
UPDATE_DIVISIONS = "9"

# Additional forecasts: JSON array or comma-separated HH:MM or full ISO timestamps in UTC
SCHEDULE_EXCEPTIONS_UTC = '["07:40"]'

# Required for daylight and all_day modes
LATITUDE = "-33.856784"
LONGITUDE = "151.215297"
TIMEZONE = "Australia/Sydney"

# Enable estimated actuals collection/scheduling.
# Default is off; set true to collect /estimated_actuals on schedule.
ENABLE_ESTIMATED_ACTUALS = "true"

# Minutes after local midnight for estimated actuals collection when using daylight/all_day mode.
# Proxy adds a daily randomized +1..14 minute offset.
ACTUALS_DELAY = "0"

# Poll delay behaviour:
# - cron mode: fixed POLL_DELAY_SECONDS used as-is.
# - daylight/all_day: adaptive delay is advertised from observed tick timing; this value is kept as configured/default reference.
#POLL_DELAY_SECONDS = "30"
POLL_DELAY_MIN_SECONDS = "15"
MAX_ATTEMPTS = "5"
RETRY_BACKOFF_SECONDS = "45"

[observability.logs]
enabled = true
invocation_logs = true

Deployment

Once the worker is deployed at Cloudflare it will take approximately five minutes for the per-minute cron schedule to begin firing. With worker observability logs enabled the first every-minute * * * * * will eventually show up, and it is at this point that things like schedules are created for all-day and daylight scheduling options. The Home Assistant integration (or anything else) should not be configured to use the proxy until this first cron execution has occurred.

The per-minute cron rebuilds the schedule on its first tick after UTC midnight and continues collection without integration requests. Cloudflare may dispatch that tick partway through the minute. A normal redeploy preserves Durable Object state, but the next coordinator request rebuilds the schedule when deployment configuration changed. This includes POLL_DELAY_SECONDS and POLL_DELAY_MIN_SECONDS, so a freshly deployed x-proxy-poll-delay-seconds value is not paired with stale schedule metadata. (The proxy version is also part of the rebuild key; bump PROXY_VERSION with schedule-affecting implementation changes so code-only deploys invalidate the persisted schedule.)

Local simulator workflow

For development purposes, this repo includes a local Python launcher that wires Wrangler HTTPS to the Solcast Solar integration simulator certificate and emulates the per-minute cron locally. To run the JavaScript proxy under wrangler it can be mounted at /workspaces/homeAssistant-core/tests/components/solcast_solar/proxy_js or copied there. The .gitignore file for the Solcast integration ignores its presence at a proxy_js location.

0) Set-up in the dev. container if required

Install node, npm and wrangler. Versions may change.

curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
export NVM_DIR="$HOME/.nvm"
. "$NVM_DIR/nvm.sh"
nvm install 26
nvm alias default 26
npm install -g wrangler
rehash
node --version
npm --version
wrangler --version

1) Start the simulator

In a discrete zsh shell.

cd /workspaces/homeAssistant-core/tests/components/solcast_solar
python -u wsgi_sim.py --limit 5000 --port 8443 --use-guidance --bomb429 10-12

2) Validate simulator trust (optional)

In another zsh shell.

cd /workspaces/homeAssistant-core/tests/components/solcast_solar/proxy_js
python run_proxy_js.py --check-only

3) Launch local JS proxy

In that same shell.

cd /workspaces/homeAssistant-core/tests/components/solcast_solar/proxy_js
python run_proxy_js.py

What run_proxy_js.py does:

  • Verifies simulator TLS using its live in-memory certificate. It expects the simulator at TCP 8443.
  • Starts wrangler dev with HTTPS on 127.0.0.1:9443.
  • Primes discovery for default accounts (1, 2) unless overridden with --api-key.
  • Dispatches one immediate __scheduled tick.
  • Emulates configured cron triggers against __scheduled, using one logged random delay of 0-59 seconds selected at launch and retained for every tick.

Use --simulator-port and --port to override defaults.

Verification examples

Direct Worker regression tests (Node.js 22+):

node --test proxy_cloudflare.test.mjs

Local (wrangler dev)

In yet another zsh shell.

BASE_URL="https://127.0.0.1:9443"
API_KEY="1"
SITE_ID="1111-1111-1111-1111"

curl -k -sS "$BASE_URL/proxy_status"
curl -k -sS -D - "$BASE_URL/rooftop_sites?format=json&api_key=$API_KEY" -o /dev/null
curl -k -sS -D - "$BASE_URL/rooftop_sites/$SITE_ID/forecasts?format=json&api_key=$API_KEY&hours=336" -o /dev/null
curl -k -sS -D - "$BASE_URL/rooftop_sites/$SITE_ID/estimated_actuals?format=json&api_key=$API_KEY&hours=168" -o /dev/null

Manual tick trigger:

curl -k --get --data-urlencode 'cron=* * * * *' "$BASE_URL/__scheduled"

Cloud (workers.dev)

If testing against a Cloudflare deployment...

BASE_URL="https://<worker>.<subdomain>.workers.dev"
API_KEY="<solcast-api-key>"

curl -sS "$BASE_URL/proxy_status"
curl -sS -D - "$BASE_URL/rooftop_sites?format=json&api_key=$API_KEY" -o /dev/null

Home Assistant integration notes

  • For local dev (https://127.0.0.1:9443), Wrangler uses a development certificate; set integration ssl_verify to false unless that cert is explicitly trusted, which it won't be, so set it in solcast-advanced.json.
  • x-proxy-poll-delay-seconds behaviour:
    • cron mode: fixed from POLL_DELAY_SECONDS.
    • daylight/all_day: adaptive from observed tick timing, floored by POLL_DELAY_MIN_SECONDS.
    • The integration refreshes proxy schedule headers five seconds before the next proxy forecast collection so that it can do things like adjust proxy-follow timing.
  • Estimated actuals schedule behaviour:
    • ENABLE_ESTIMATED_ACTUALS=false (default): no estimated-actuals slots are scheduled.
    • ENABLE_ESTIMATED_ACTUALS=true: estimated-actuals slots are scheduled per mode (ACTUALS_CRONS or ACTUALS_DELAY).

Durable Object storage notes

The implementation uses SQLite-backed Durable Object storage. Deploying under a different Worker script/namespace creates a separate storage space.

For storage continuity keep Worker and DO migration lineage consistent.

Troubleshooting

  • ReferenceError ... is not defined after edits:
    • Wrangler hot-reload can lag; restart run_proxy_js.py.
  • SSL: WRONG_VERSION_NUMBER from HA:
    • Verify HA URL is https://..., not http://....
  • No simulator is listening on port ...:
    • Start wsgi_sim.py first, then run_proxy_js.py.
  • not_fetched responses:
    • Check /proxy_status and launcher logs ([local-cron:info]) to ensure scheduler is dispatching.

Prerequisites

  • Local launcher needs: Python 3.14+, Node.js 20+, wrangler, and lsof.
  • Quick install (Debian/Ubuntu): sudo apt install -y lsof nodejs npm && npm install -g wrangler.
  • Quick install (macOS/Homebrew): brew install lsof node && npm install -g wrangler.
  • Verify tools: python --version && node --version && npm --version && wrangler --version && lsof -v | head -n 1.
  • Optional for cloud deploy only: wrangler login, then wrangler deploy.
  • Windows: run_proxy_js.py is Linux/dev-container oriented (/proc + lsof); use WSL/dev-container, or run Wrangler manually.

Response headers issued

The Home Assistant integration reacts to a small, explicit subset of proxy response headers, and other things can too.

Discovery and scheduling headers

These are emitted on /rooftop_sites discovery responses and on the dedicated schedule refresh endpoint (/proxy_schedule, alias /schedule). They tell the integration how to follow the proxy schedule. They are mode-specific, and the useful set depends on whether the proxy is running in cron mode or daylight/all_day mode.

Shared discovery headers

These are always relevant regardless of schedule mode.

  • x-solcast-proxy: true — discovery marker identifying the response as coming from a Solcast-compatible proxy.
  • x-proxy-name / x-proxy-version — human-readable proxy identity and version metadata.
  • x-proxy-status-url — status endpoint that can be used to inspect runtime health and scheduler state.
  • x-proxy-timezone — schedule timezone; the integration expects UTC.
  • x-proxy-forecast-mode — current forecast mode (cron, daylight, or all_day), established during discovery. Schedule refreshes retain the discovered mode and do not require this header.
  • x-proxy-estimated-actuals-enabled: true|false — whether scheduled estimated-actuals collection is active.

Cron mode headers

These are the headers that matter when the proxy is following a cron-driven forecast schedule.

  • x-proxy-forecast-cron / x-proxy-estimated-actuals-cron — cron expressions the integration should use for scheduled follow-up.
  • x-proxy-poll-delay-seconds — fixed per-collection follow delay used by the integration while polling a cron schedule.

Daylight and all_day mode headers

These are the headers that describe the adaptive schedule used for daylight and all-day collection. The tick statistics are emitted in every mode, but they are only materially used to drive the adaptive delay in daylight/all_day mode.

Tick timing history persists across restarts. Three consecutive ticks spanning at most two seconds, all at least ten seconds away from the previous history's P90, reset the timing samples and observation count. The previous history must contain at least three samples, but may contain mixed timing phases. The reset is logged and preserves schedules, cached forecasts, usage, and retry state.

  • x-proxy-poll-delay-seconds — adaptive follow delay recommended from observed tick timing.
  • x-proxy-poll-delay-confidence — optional confidence signal for the adaptive scheduling estimate; not a hard gate, but a useful indicator of schedule stability.
  • x-proxy-observed-tick-second-p90 — observed tick timing percentile used to estimate safe follow delays in adaptive scheduling.
  • x-proxy-schedule-day-utc — the currently active UTC schedule day in the proxy.
  • x-proxy-forecast-times-utc — comma-separated forecast collection times in UTC as 'hh:mm' with no seconds. (The seconds are adaptively worked out from the poll delay, which might mean the integration ends up fetching in the minute after the proxy, but still closely following it.)
  • x-proxy-estimated-actuals-times-utc — comma-separated estimated-actuals collection times in UTC.

In other words: cron mode is driven by the cron headers and fixed delay, while daylight and all_day are driven by the time-slot and adaptive polling headers rather than a fixed cron expression.

Per-resource state and retry headers

These are emitted on individual resource responses, and the integration interprets them to decide whether to keep polling, retry, or wait on a shared upstream failure.

  • x-proxy-upstream-status — most recent upstream HTTP status for this resource.
  • x-proxy-last-fetch-at — timestamp of the last completed upstream attempt in ISO 8601 UTC format.
  • x-proxy-last-success-at — timestamp of the last successful upstream fetch in ISO 8601 UTC format.
  • x-proxy-last-fetch-status — current resource state, one of not_fetched, clean_success, retry_success, retrying, give_up, budget_exhausted, or permanent_error.
  • x-proxy-consecutive-failures — number of consecutive failed attempts since the last success.
  • x-proxy-retries-used — number of retry attempts used in the current cycle.
  • x-proxy-next-attempt-at — ISO 8601 UTC timestamp for the next retry; empty when the resource is not retrying.
  • x-proxy-give-up — boolean indicating the current retry cycle ended unsuccessfully.
  • x-proxy-halted — boolean indicating a permanent resource failure that should stop retry scheduling.
  • x-proxy-fetch-in-progress — boolean indicating a collection is still running and the next poll may be too soon.
  • x-proxy-collection-deferred — boolean indicating the read was deferred because a shared collection gate is active.

Cache and truncation headers

These are read when the proxy is serving cached data and when it is responding to truncated requests.

  • x-proxy-requested-hours — client-requested forecast or actuals horizon.
  • x-proxy-cache-hours — currently available cache coverage, in hours.
  • x-proxy-hours-truncated — boolean indicating the cached response was truncated against the number of hours asked for.

Notes for custom proxy authors

  • The integration treats x-proxy-next-attempt-at as the authoritative retry schedule while a resource is retrying.
  • x-proxy-halted is a hard stop: once it is true, the integration should stop queueing retries for that resource.
  • x-proxy-give-up is not the same as a permanent halt; it tells the integration a retry cycle exhausted but the resource may recover on the next cycle.
  • x-proxy-collection-deferred tells the integration that a shared upstream failure is blocking other resources even though they may have valid local cache data.
  • When a resource is in flight, a short follow delay may still be too aggressive; x-proxy-fetch-in-progress is the indicator to honor.

A compatible proxy does not need to emit every header in the wider worker implementation, but these are the ones that matter for timing, retries, and schedule-follow behaviour.

About

This is a proxy for the Solcast PV forecast hobbyist API. It allows multiple API consumers despite limited hobbyist API quota (typically just ten updates daily), and incorporates schedule and state information in endpoint responses.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages