omada

module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2026 License: MIT

README

omada

Go client for the TP-Link Omada SDN controller API. This package is a synchronous port of tplink-omada-client v1.5.14 covering the controller scope.

What it is

The client speaks the Omada controller REST API (/openapi/... and legacy /api/... namespaces) over HTTP with a permissive cookie jar and automatic re-login on session expiry.

Supported

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

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. Authentication transitions are serialized.

Errors

  • *RequestError — the controller answered with a non-zero error code; the controller code is available via Code and errors.Is matches ErrLoginFailed for code -30109.
  • *ValidationError — invalid caller input.

Sentinels: ErrLoginFailed, ErrLoginSessionClosed, ErrUnsupportedControllerVersion, ErrSiteNotFound, ErrConnectionFailed, ErrBadControllerURL, ErrInvalidDevice.

Divergences from the Python library

  • Three defect fixes: bounded pagination, VpnPolicies all-pages, re-login scope, plus the VLAN read-back contract message.
  • Structural notes: a single Device struct, a flat Client struct, and the ValueError family folded into *ValidationError.

Cloud northbound client (cloud/)

cloud/ is a generated 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), grouped into 19 domain packages: ap, client, device, gateway, insight, lan, log, msp, remote, security, sim, site, stack, switch, topology, user, voip, vpn, wireless.

The root cloud package is hand-written: construction, token caching and refresh, auth header injection, envelope errors and paging. The domain packages are generated by oapi-codegen and checked in, so the module compiles without code generation or network access.

cloud/ adds one runtime dependency, github.com/oapi-codegen/runtime (used by generated code only). controller/ stays stdlib-only, and 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 (Omada Cloud, Authorization: Bearer <token>):

cl, err := cloud.New(cloud.Options{
    BaseURL:  "https://use1-omada-northbound.tplinkcloud.com", // default
    Username: "user",
    Password: "pass",
})
if err != nil { ... }

BaseURL may be omitted in hosted mode to use the US-1 endpoint; pass another regional *-omada-northbound.tplinkcloud.com host for other regions.

On-prem org-level (Authorization: AccessToken=<token>):

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 under Settings → Platform Integration → Open API; it yields the client_id and client_secret. BaseURL is required in this mode and is the controller's own address (scheme, host and port as shown in the settings).

Credentials are validated in New: providing both sets, neither set, or omitting BaseURL in on-prem mode is an error. The hosted token endpoint is POST /v1/token; the on-prem endpoint is POST /openapi/authorize/token?grant_type=client_credentials. Tokens are cached and refreshed about 60 seconds before expiry. On-prem re-authentication always re-runs the client-credentials grant; the returned refresh token is not used.

Making a call

Domain accessors on cloud.Client return generated clients wired to the auth transport: 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(), cl.Remote().

Operations are named after the spec's operationId and 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)
}

Domain packages can also be used standalone (site.NewClient(baseURL)), but requests made that way bypass the auth transport.

Errors

Most API operation responses use the {errorCode, msg, result} envelope, but some spec operations declare a bare payload (e.g. getTags_1, getUnresolvedIncidentCount) — check the operation's declared response schema. A business failure is HTTP 200 with a non-zero errorCode, not a non-2xx status. Generated clients do not inspect the envelope, so check it after each call and return cloud.NewAPIError(code, msg), a *cloud.APIError whose Code and Msg 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: the cached token is dropped, a new token is fetched, and the request is retried exactly once (the request body is replayed). A second 401 is returned to the caller. Other non-2xx responses are returned as-is with the body intact for the caller to interpret.

Paging

cloud.CollectAll collects page/pageSize-style endpoints. It starts at page 1 and stops when it has totalRows rows (when known), receives a short page, or reaches maxRows; a page that crosses the total is truncated to it.

// 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. This is normally unnecessary (the transport refreshes on a 401, and cached tokens are refreshed before expiry), but it is the recovery path when a controller invalidates a token outside the client (for example after a site copy/import or 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, applies the deterministic patch for the 16 operations missing path-parameter declarations, verifies that every public operation maps to exactly one package, regenerates the per-package configs, runs oapi-codegen for all 19 packages, and 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 configs 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. The scheduled .github/workflows/spec-regen.yml workflow fetches the spec fresh (never cached — the fetch is the drift signal), exits early when the fingerprint is unchanged, and otherwise patches, regenerates, runs the full gate, and opens or updates a pull request on bot/omada-spec-regen when the generated code changed. A new upstream tag fails verify_mapping.py loudly; extend gen/tags.json by hand in that case.

Tests

go test ./... -race -count=1 covers both auth flows, token caching and refresh, the 401 retry, header shape, envelope errors and paging, plus representative httptest coverage for each of the 19 domain packages.

Live read-only test

cloud/livetest (build tag live) probes every GET operation of the generated client against a live controller: it discovers a site and its devices, then walks the full read-only table, resolving each endpoint's path parameters from the discovered resources. Endpoints whose resources the org does not have (or that cannot be discovered) are skipped and counted.

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

OMADA_INSECURE_TLS=true skips TLS certificate verification; use it for controllers that serve the stock self-signed certificate (CN=localhost, no SAN). It is opt-in and documented as such on cloud.Options.InsecureTLS.

OMADA_LIVE_DELAY (e.g. 100ms) pauses between endpoint calls. The controller rate-limits fast bursts (envelope errorCode -7132); a small delay keeps the ~1,000-call run under the limit so 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), and reports (without failing) business failures — HTTP 200 with a non-zero errorCode — which a read-only org legitimately gets for undeployed features.

Log safety: 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, so the logs are safe to keep public.

The test is wired into:

  • Pre-commit (.pre-commit-config.yaml): pre-commit install once per clone; the hook runs the live test on every commit and skips fast when the OMADA_* environment is not set.
  • CI (.github/workflows/live-api.yml): nightly (06:30 UTC), workflow_dispatch, and pull requests that touch cloud/livetest/** or the workflow itself. It runs on the self-hosted omada-runner and probes the controller sequentially through the on-premises (LAN) and public (cloud) addresses, using 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

Directories

Path Synopsis
ap
Package ap provides primitives to interact with the openapi HTTP API.
Package ap provides primitives to interact with the openapi HTTP API.
client
Package client provides primitives to interact with the openapi HTTP API.
Package client provides primitives to interact with the openapi HTTP API.
device
Package device provides primitives to interact with the openapi HTTP API.
Package device provides primitives to interact with the openapi HTTP API.
gateway
Package gateway provides primitives to interact with the openapi HTTP API.
Package gateway provides primitives to interact with the openapi HTTP API.
insight
Package insight provides primitives to interact with the openapi HTTP API.
Package insight provides primitives to interact with the openapi HTTP API.
lan
Package lan provides primitives to interact with the openapi HTTP API.
Package lan provides primitives to interact with the openapi HTTP API.
log
Package log provides primitives to interact with the openapi HTTP API.
Package log provides primitives to interact with the openapi HTTP API.
msp
Package msp provides primitives to interact with the openapi HTTP API.
Package msp provides primitives to interact with the openapi HTTP API.
remote
Package remote provides primitives to interact with the openapi HTTP API.
Package remote provides primitives to interact with the openapi HTTP API.
security
Package security provides primitives to interact with the openapi HTTP API.
Package security provides primitives to interact with the openapi HTTP API.
sim
Package sim provides primitives to interact with the openapi HTTP API.
Package sim provides primitives to interact with the openapi HTTP API.
site
Package site provides primitives to interact with the openapi HTTP API.
Package site provides primitives to interact with the openapi HTTP API.
stack
Package stack provides primitives to interact with the openapi HTTP API.
Package stack provides primitives to interact with the openapi HTTP API.
switch
Package switchpkg provides primitives to interact with the openapi HTTP API.
Package switchpkg provides primitives to interact with the openapi HTTP API.
topology
Package topology provides primitives to interact with the openapi HTTP API.
Package topology provides primitives to interact with the openapi HTTP API.
user
Package user provides primitives to interact with the openapi HTTP API.
Package user provides primitives to interact with the openapi HTTP API.
voip
Package voip provides primitives to interact with the openapi HTTP API.
Package voip provides primitives to interact with the openapi HTTP API.
vpn
Package vpn provides primitives to interact with the openapi HTTP API.
Package vpn provides primitives to interact with the openapi HTTP API.
wireless
Package wireless provides primitives to interact with the openapi HTTP API.
Package wireless provides primitives to interact with the openapi HTTP API.
internal/testutil
Package testutil provides shared mock-controller test helpers for the controller and site package tests.
Package testutil provides shared mock-controller test helpers for the controller and site package tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL