omada
omada is a Go client for the TP-Link Omada SDN controller API. It is a
synchronous port of tplink-omada-client
v1.5.14. Its calls wait until they finish. It covers the controller API.
What it is
The client talks to the Omada controller REST API over HTTP. It uses the
/openapi/... and legacy /api/... namespaces. It stores session cookies in
a permissive cookie jar. It logs in again on its own when a session expires.
Supported
The client works with Omada Software Controller 5.1.0 and later.
Method families:
- Sites (controller, site, site-by-name)
- Clients (list, get, block, unblock, reconnect, update settings, known)
- Devices (list, get, topology, LED, reboot, firmware, reset)
- Access points (list, get, ports, radios, channels)
- Switches and port profiles
- Gateways and PoE
- LAN networks, VLANs and DHCP reservations
- VPN policies (server / client / site-to-site) and status updates
- Firmware updates and controller updates
Quick start
Create a client and a site client. The example creates a VLAN-only network and
blocks a client by MAC address.
client, err := controller.New("https://omada.example.com", "user", "pass")
if err != nil { ... }
sites, err := client.Sites(ctx)
if err != nil { ... }
siteClient, err := client.SiteClient(ctx, sites[0].ID())
if err != nil { ... }
// Create a VLAN-only network.
network, err := siteClient.CreateVLAN(ctx, "office", 10)
if err != nil { ... }
// Block a client by MAC.
if err := siteClient.BlockClient(ctx, "AA:BB:CC:DD:EE:FF"); err != nil { ... }
Concurrency
Client and SiteClient are safe for concurrent use. The client runs login
and re-login steps one at a time.
Errors
*RequestError: the controller answered with a non-zero error code. The
controller code is in Code. errors.Is matches ErrLoginFailed for code
-30109.
*ValidationError: the caller passed invalid input.
The client also returns these sentinel errors: ErrLoginFailed,
ErrLoginSessionClosed, ErrUnsupportedControllerVersion, ErrSiteNotFound,
ErrConnectionFailed, ErrBadControllerURL, and ErrInvalidDevice.
Differences from the Python library
This client fixes three defects in the Python library: bounded pagination,
all-pages VpnPolicies, and re-login scope. It also changes the VLAN
read-back contract message.
This client also changes the structure. It uses one Device struct. It uses
a flat Client struct. It folds the ValueError family into
*ValidationError.
Cloud northbound client (cloud/)
cloud/ is a Go client for the Omada cloud northbound API
(use1-omada-northbound.tplinkcloud.com). It covers all 2,510 public
operations from the published OpenAPI spec (/v3/api-docs). It groups them
into 19 domain packages: ap, client, device, gateway, insight, lan,
log, msp, remote, security, sim, site, stack, switch,
topology, user, voip, vpn, and wireless.
The root cloud package is hand-written. It handles construction, token
caching and refresh, auth header injection, envelope errors, and paging. The
domain packages are generated by oapi-codegen and checked in. The module
compiles without code generation or network access.
cloud/ adds one runtime dependency: github.com/oapi-codegen/runtime. The
generated code uses it. controller/ uses only the Go standard library. The
two trees do not import each other.
Authentication
cloud.New takes exactly one credential set. Both modes use the same client
and the same generated domain packages. Only BaseURL and the credential
fields differ.
Hosted mode targets Omada Cloud. It sends an Authorization: Bearer <token>
header:
cl, err := cloud.New(cloud.Options{
BaseURL: "https://use1-omada-northbound.tplinkcloud.com", // default
Username: "user",
Password: "pass",
})
if err != nil { ... }
You can omit BaseURL in hosted mode. The client then uses the US-1 endpoint.
Pass another regional *-omada-northbound.tplinkcloud.com host for other
regions.
On-prem org-level mode targets the controller. It sends an
Authorization: AccessToken=<token> header:
cl, err := cloud.New(cloud.Options{
BaseURL: "https://controller.example.com:8043", // controller address
OmadacID: "org-id",
ClientID: "client-id",
ClientSecret: "client-secret",
})
if err != nil { ... }
Create the application on the controller. Go to Settings, then Platform
Integration, then Open API. The application gives you the client_id and the
client_secret. In this mode, BaseURL is required. Set it to the
controller's own address, with the scheme, host, and port as shown in the
settings.
New makes sure that the credentials are valid. It returns an error if you
provide both sets
or neither set. It also returns an error if you omit BaseURL in on-prem
mode. The hosted token endpoint is POST /v1/token. The on-prem token
endpoint is POST /openapi/authorize/token?grant_type=client_credentials.
The client caches tokens and refreshes them about 60 seconds before expiry.
On-prem re-authentication always re-runs the client-credentials grant. The
client does not use the returned refresh token.
Making a call
Domain accessors on cloud.Client return generated clients. The client wires
them to the auth transport. The accessors are: cl.Site(), cl.Clients(),
cl.Devices(), cl.Ap(), cl.Switch(), cl.Gateway(), cl.Lan(),
cl.Wireless(), cl.Vpn(), cl.Security(), cl.Insight(), cl.Users(),
cl.Msp(), cl.Stack(), cl.Voip(), cl.Sim(), cl.OmadaLog(),
cl.Topology(), and cl.Remote().
Operations are named after the spec's operationId. They take omadacId
where the path requires it. Generated methods return the raw
*http.Response. Decode the body into the matching generated envelope type:
resp, err := cl.Site().GetSiteList(ctx, omadacID, &site.GetSiteListParams{
Page: 1,
PageSize: 100,
})
if err != nil { ... }
defer resp.Body.Close()
var env site.OperationResponseGridVOSiteSummaryInfo
if err := json.NewDecoder(resp.Body).Decode(&env); err != nil { ... }
if env.ErrorCode != nil && *env.ErrorCode != 0 {
msg := ""
if env.Msg != nil {
msg = *env.Msg
}
return cloud.NewAPIError(int(*env.ErrorCode), msg)
}
You can use a domain package on its own, as in site.NewClient(baseURL).
Requests made that way bypass the auth transport.
Errors
Most API operation responses use an envelope, a wrapper with the shape
{errorCode, msg, result}. Some spec operations declare a bare payload, for
example getTags_1 and getUnresolvedIncidentCount. Read the operation's
declared response schema to find out if it is a bare payload. A business
failure is HTTP 200 with a non-zero errorCode. It is not a non-2xx status.
The generated clients do not inspect the envelope.
Read the envelope after each call. If it holds an error, return
cloud.NewAPIError(code, msg). The call returns a *cloud.APIError. Its
Code and Msg fields carry the service values.
The hosted service reports a missing or expired token as HTTP 401 with
envelope code -44116. The transport handles that case. It drops the cached
token, fetches a new token, and retries the request exactly once. It replays
the request body.
A second 401 is returned to the caller. Other non-2xx responses are returned
as-is, with the body intact. The caller interprets them.
Paging
cloud.CollectAll collects results from page/pageSize-style endpoints. It
starts at page 1. It stops when it has totalRows rows (when known), when it
receives a short page, or when it reaches maxRows. A page that crosses the
total is cut down to the total.
// fetchSites has signature:
// func(context.Context, int, int) (cloud.Page[site.SiteSummaryInfo], error)
// It calls GetSiteList and decodes the envelope as shown above, returning
// cloud.Page[site.SiteSummaryInfo]{Rows: *env.Result.Data, TotalRows: total}.
sites, err := cloud.CollectAll(ctx, fetchSites, 100 /* page size */, 5000 /* max rows */)
pageSize and maxRows must both be at least 1.
Token invalidation
cl.InvalidateToken() drops the cached token. The next request
re-authenticates. You do not need this call in normal use. The transport
refreshes on a 401, and it refreshes cached tokens before expiry. Use this
call when a controller invalidates a token outside the client, for example
after a site copy or import, or after an application permission change.
Regeneration
go install github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@v2.8.1
make -C gen gen
make -C gen gen fetches the spec. It applies a deterministic patch for the
16 operations that are missing path-parameter declarations. It makes sure that
every public operation maps to exactly one package. It regenerates the
per-package configuration files. It runs oapi-codegen for all 19 packages. It
gofmts cloud/.
The generator is pinned to oapi-codegen v2.8.1. Set
OAPI=/path/to/oapi-codegen to use a different binary. The raw and patched
specs and the generated configuration files are gitignored build artifacts.
The *.gen.go files are checked in.
Spec drift
gen/spec.sha256 records the SHA-256 fingerprint of the raw upstream spec.
The checked-in generated code was built from that spec. The scheduled
.github/workflows/spec-regen.yml workflow fetches the spec fresh. It never
uses a cache. A fresh fetch shows when the upstream spec changes. It exits
early when the fingerprint is unchanged.
Otherwise, it patches the spec, regenerates the code, runs the full test
suite, and opens or updates a pull request on bot/omada-spec-regen when the
generated code changed. A new upstream tag makes verify_mapping.py fail.
Extend gen/tags.json by hand in that case.
Tests
go test ./... -race -count=1 runs the tests. They cover both auth flows,
token caching and refresh, the 401 retry, header shape, envelope errors, and
paging. They also include representative httptest coverage for each of the
19 domain packages.
Live read-only test
cloud/livetest uses the live build tag. It probes every GET operation of
the generated client against a live controller. It discovers a site and its
devices. Then it walks the full read-only table. It resolves each endpoint's
path parameters from the discovered resources. It skips and counts endpoints
whose resources the org does not have or cannot discover.
OMADA_BASE_URL=https://omada.example.com:8043 \
OMADA_OMADAC_ID=<org-id> \
OMADA_CLIENT_ID=<client-id> \
OMADA_CLIENT_SECRET=<client-secret> \
go test -tags live ./cloud/livetest -v -count=1
Set OMADA_INSECURE_TLS=true to skip TLS certificate verification. Use it for
controllers that serve the stock self-signed certificate (CN=localhost, no
SAN). The option is off by default. cloud.Options.InsecureTLS documents it.
OMADA_LIVE_DELAY pauses between endpoint calls. For example, set it to
100ms. The controller limits the number of fast requests. It returns
envelope errorCode -7132 for fast bursts. A small delay keeps the
~1,000-call run under the limit. That way, the report reflects real endpoint
behavior. CI sets it to 100ms.
The run fails on transport errors and non-2xx responses (401/403/404/405/5xx).
It reports business failures without failing the run. A business failure is
HTTP 200 with a non-zero errorCode. A read-only org gets these for
undeployed features.
The report contains only operation names, HTTP status codes, and envelope
errorCode/msg values. Response bodies, resource IDs, MAC addresses, and IP
addresses never reach the output. You can keep the logs public.
The test runs in two places:
- Pre-commit (
.pre-commit-config.yaml): Run pre-commit install once per
clone. The hook runs the live test on every commit. It skips fast when the
OMADA_* environment is not set.
- CI (
.github/workflows/live-api.yml): It runs nightly at 06:30 UTC, on
workflow_dispatch, and on pull requests that touch cloud/livetest/** or
the workflow itself. It runs on the self-hosted omada-runner. It probes
the controller in order through the on-premises (LAN) address and the public
(cloud) address. It uses the GitHub Test environment secrets
OMADA_TEST_BASE_URL, OMADA_TEST_CLOUD_URL, OMADA_TEST_OMADAC_ID,
OMADA_TEST_CLIENT_ID, and OMADA_TEST_CLIENT_SECRET.
Regenerate the live table after a spec regeneration:
make -C gen livetest