MELCloud & MELCloud Home API for Node.js - v48.2.0
    Preparing search index...

    Class HomeAPI

    MELCloud Home API client using the mobile BFF at mobile.bff.melcloudhome.com with Bearer-token authentication.

    Authenticates via a headless OIDC flow: PAR → IdentityServer → AWS Cognito → token exchange.

    Access and refresh tokens are persisted through the SettingManager (analogous to the Classic API's contextKey).

    Uses a private constructor — create instances via HomeAPI.create.

    Hierarchy

    • BaseAPI
      • HomeAPI

    Implements

    Index
    logger: Logger
    settingManager?: SettingManager
    • get isRateLimited(): boolean

      Whether the upstream rate-limit gate is currently holding a pause window after a recent 429 Retry-After response.

      Returns boolean

      true while the SDK is intentionally failing fast.

    • get locale(): string | undefined

      BCP-47 locale supplied via HomeAPIConfig.locale, or undefined to fall back to the runtime locale. Drives chart label formatting in the device facades.

      Returns string | undefined

      The configured BCP-47 locale tag, or undefined.

    • get timezone(): string | undefined

      IANA timezone supplied via HomeAPIConfig.timezone, or undefined to fall back to UTC. The Home wire itself speaks UTC wall-clock; this timezone only anchors chart windows and label rendering in the device facades.

      Returns string | undefined

      The configured IANA timezone identifier, or undefined.

    • Releases the auto-sync timer and any retry-guard timers; the instance must not be reused after disposal.

      Returns void

    • Sign in with explicit credentials. The server refuses them in protocol-specific ways (Classic ClientLogin3 returning LoginData: null, Home BFF returning 401, etc.). Successful return guarantees the registry reflects server state — the post-auth sync is enforced here so subclasses cannot forget it.

      Use resumeSession for a best-effort restore from persisted credentials that logs + swallows errors.

      Credentials are persisted only once the server accepts them: a rejected attempt leaves the stored pair and any live session untouched (the backoff still arms and the error still surfaces).

      Parameters

      Returns Promise<void>

      AuthenticationError when the server refuses the credentials.

    • Cancels any pending auto-sync timer; subsequent setSyncInterval or fetch calls re-arm it.

      Returns void

    • Sync check first; when it reads false, a NON-DESTRUCTIVE probe — one registry sync, which exercises the persisted session without touching it — and only if that still leaves us unauthenticated, the best-effort resumeSession fallback. The order matters: resumeSession runs a full sign-in, which spends a real login attempt (server-side throttle counters, the local backoff on a rejection) and replaces a session that may have been merely unexercised (a boot-time context fetch that lost the network reads unauthenticated while a perfectly valid refresh token sits in storage).

      Returns Promise<boolean>

      true when a session is usable afterwards.

    • Fetch the internal-temperatures report (flow/return/tank/zone) for an ATW unit. Same Result contract as getEnergy.

      Parameters

      • id: string

        Device id.

      • params: { from: string; period: string; to: string }

        Query window.

        • from: string

          ISO start timestamp (inclusive).

        • period: string

          Aggregation period (e.g. Daily, Hourly).

        • to: string

          ISO end timestamp (exclusive).

      Returns Promise<Result<HomeReportData[]>>

      Success with the report datasets, or a typed failure.

    • Fetch energy telemetry for a unit; the registry model's connection type selects the measure family — ATA's single cumulative consumption counter, or ATW's interval consumed/produced measures (kWh per bucket, live-probed 2026-07-17). Returns a Result so callers can branch on the failure class (validation for shape drift, server for 4xx/5xx, unauthorized for token rejection, rate-limited, network).

      Parameters

      • id: string

        Device id.

      • params: {
            from: string;
            interval: string;
            measure?: "consumed" | "produced";
            to: string;
        }

        Query window.

        • from: string

          ISO start timestamp (inclusive).

        • interval: string

          Aggregation interval (Minute, Hour, Day, Week or Month).

        • Optionalmeasure?: "consumed" | "produced"

          Energy direction ('consumed' or 'produced'); ATW only, where it defaults to 'consumed' — the ATA counter is consumption by definition.

        • to: string

          ISO end timestamp (exclusive). A measure passed for an ATA id is ignored — the ATA counter is consumption by definition. An id the registry does not hold folds into the not-found Result variant (the Result contract never throws for it — a cold open may query before the first fetch).

      Returns Promise<Result<HomeEnergyData>>

      Success with the telemetry bundle, or a typed failure.

    • Fetch the temperature report for a unit; the registry model's connection type selects the endpoint — ATA's trend summary or ATW's comfort graph (outside / room / set temperature). Same Result contract as getEnergy.

      Parameters

      • id: string

        Device id.

      • params: { from: string; period: string; to: string }

        Query window.

        • from: string

          ISO start timestamp (inclusive).

        • period: string

          Aggregation period (e.g. hour, day).

        • to: string

          ISO end timestamp (exclusive). An unknown id folds into the not-found Result variant.

      Returns Promise<Result<HomeReportData[]>>

      Success with the report datasets, or a typed failure.

    • Refresh the user by fetching the /context identity. On failure the last known user is returned unchanged: transient failures and device-payload drift must not read as "logged out" — the reactive-401 path (reauthenticate()) is the single owner of clearing the authentication state, so a definitive rejection has already nulled the user by the time the failure surfaces here.

      Returns Promise<HomeUser | null>

      The user or null.

    • Post-construction lifecycle hook. Every subclass create() factory must delegate to this method — it is the sole path that guarantees the #1281-class invariant at instance-creation time: a successful return leaves the registry populated whenever credentials or a persisted session are available.

      Two-branch template:

      1. tryReuseSession — if the subclass can reuse a persisted session (and populate the registry in the process), we are done.
      2. Otherwise, resumeSession runs — best-effort restore from persisted credentials. Does nothing (silently) if no credentials are persisted, so the "no creds + no session" case falls through to a documented empty state.

      Callers should check isAuthenticated after create() returns if they need to distinguish "empty state" from "ready".

      Returns Promise<void>

    • Whether the BFF /context call has resolved a user identity.

      Returns boolean

      true once authenticated.

    • Log out: the inverse of authenticate. Clears the persisted session (tokens/context/expiry), the stored username/password and the automatic-login backoff, stops the auto-sync timer, and empties the registry — so isAuthenticated reads false and no stale devices linger, identically on Classic and Home.

      User-initiated, so unlike a rejected sign-in it neither arms the backoff nor emits onAuthenticationLost. A subsequent authenticate is the only way back in.

      Returns void

    • Notify any registered events.onSyncComplete observer that a sync just landed. Routed through the lifecycle emitter so a misbehaving callback cannot break the caller. Invoked by the @syncDevices decorator after each decorated mutation.

      Parameters

      • ...args: [params?: { ids?: (string | number)[]; type?: DeviceType }]

        SyncCallback-shaped payload (type, ids).

      Returns Promise<void>

    • Best-effort session restore from persisted credentials.

      Reads username/password from the SettingManager and signs in. Unlike authenticate, failures are logged and swallowed — the method never throws. Use this from lifecycle hooks (init, 401 retry, ensureSession) where a stale or missing persisted credential must not crash the caller.

      On success, the registry is populated (delegates to authenticate).

      Returns Promise<boolean>

      true when a sign-in round-trip succeeded and the instance is now authenticated; false for "no persisted credentials" or "sign-in failed" (both indistinguishable by the return value alone — check the logger / isAuthenticated if the distinction matters).

    • Reschedules the auto-sync timer.

      The timer is unref'd, so it never keeps the Node event loop alive on its own — auto-sync still fires on cadence whenever the host application has another reason to stay running (HTTP server, other timers, open streams). Apps that must run indefinitely should provide their own keep-alive (e.g. setInterval(() => {}, 1 << 30) or a long-lived server) rather than relying on this timer.

      Parameters

      • minutes: number | false

        Cadence in minutes; pass false to disable.

      Returns void

    • Run the initial session restore, honoring the configured mode. initialize() never rejects by design (probe and resume failures are swallowed and surfaced through the lifecycle events), so the background variant only needs the fire-and-forget form.

      Parameters

      • shouldResumeInBackground: boolean = false

        When true, the restore runs off the caller's critical path and create() resolves immediately.

      Returns Promise<void>

    • Send a unit setpoint update to the BFF; the registry model's connection type selects the wire path. On success, re-sync the registry so it reflects the server-side effect of the write (the PUT response itself does not echo device fields). On failure, the typed transport error propagates and the sync is skipped — the server state is presumed unchanged, so a re-fetch would be wasted work. The mutation + post-sync orchestration lives in #putAtaAndSync/#putAtwAndSync, where @fetchDevices({ when: 'after' }) applies the same post-mutation-refresh contract as Classic facades — just resolved via syncRegistry() instead of api.fetch().

      Parameters

      • id: string

        Target device id.

      • values: HomeAtaValues | HomeAtwValues

        Partial setpoint payload matching the unit's connection type — the shape is the caller's contract: the BFF binder silently drops keys the routed unit does not know.

      Returns Promise<void>

      EntityNotFoundError when the registry does not hold the id.

    • Create and initialize a MELCloud Home API instance.

      Delegates post-construction setup to BaseAPI.initialize so the #1281-class invariant is enforced uniformly: the reuse path, the fresh-auth path, and the "no credentials" path all go through the same template and cannot leave the registry empty while claiming success.

      Parameters

      Returns Promise<HomeAPI>

      The initialized HomeAPI instance.