How to use home-assistant-js-websocket - 10 common examples

To help you get started, we’ve selected a few home-assistant-js-websocket examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github zachowj / node-red-contrib-home-assistant-websocket / lib / ha-websocket.js View on Github external
async startListening(eventOpts = {}) {
        this.config.websocket.includeRegex =
            eventOpts.includeRegex || this.config.websocket.includeRegex;
        this.config.websocket.excludeRegex =
            eventOpts.excludeRegex || this.config.websocket.excludeRegex;

        try {
            this.client = await homeassistant.createConnection({
                self: this,
                createSocket: this.createSocket
            });
            this.onClientOpen();
            this.emit('ha_client:connected');
        } catch (e) {
            this.connectionState = HaWebsocket.DISCONNECTED;
            this.emit('ha_client:close');
            return false;
        }

        // Client events
        this.client.addEventListener('ready', this.onClientOpen.bind(this));
        this.client.addEventListener(
            'disconnected',
            this.onClientClose.bind(this)
github home-assistant / home-assistant-polymer / src / onboarding / onboarding-create-user.ts View on Github external
ev.preventDefault();
    if (!this._name || !this._username || !this._password) {
      this._errorMsg = "required_fields";
      return;
    }

    if (this._password !== this._passwordConfirm) {
      this._errorMsg = "password_not_match";
      return;
    }

    this._loading = true;
    this._errorMsg = "";

    try {
      const clientId = genClientId();

      const result = await onboardUserStep({
        client_id: clientId,
        name: this._name,
        username: this._username,
        password: this._password,
        language: this.language,
      });

      fireEvent(this, "onboarding-step", {
        type: "user",
        result,
      });
    } catch (err) {
      // tslint:disable-next-line
      console.error(err);
github keesschollaart81 / vscode-home-assistant / src / language-service / src / home-assistant / socket.ts View on Github external
const closeOrError = (errorText?: string) => {

            if (errorText) {
                console.log(`WebSocket Connection to Home Assistant closed with an error: ${errorText}`);
            }
            if (invalidAuth) {
                promReject(ha.ERR_INVALID_AUTH);
                return;
            }

            // Reject if we no longer have to retry
            if (triesLeft === 0) {
                // We never were connected and will not retry
                promReject(ha.ERR_CANNOT_CONNECT);
                return;
            }

            const newTries = triesLeft === -1 ? -1 : triesLeft - 1;
            // Try again in a second
            setTimeout(
                () =>
                    connect(
                        newTries,
github keesschollaart81 / vscode-home-assistant / src / language-service / src / home-assistant / socket.ts View on Github external
const closeOrError = (errorText?: string) => {

            if (errorText) {
                console.log(`WebSocket Connection to Home Assistant closed with an error: ${errorText}`);
            }
            if (invalidAuth) {
                promReject(ha.ERR_INVALID_AUTH);
                return;
            }

            // Reject if we no longer have to retry
            if (triesLeft === 0) {
                // We never were connected and will not retry
                promReject(ha.ERR_CANNOT_CONNECT);
                return;
            }

            const newTries = triesLeft === -1 ? -1 : triesLeft - 1;
            // Try again in a second
            setTimeout(
                () =>
                    connect(
                        newTries,
                        promResolve,
                        promReject
                    ),
                1000
            );
        };
github home-assistant / home-assistant-polymer / src / onboarding / ha-onboarding.ts View on Github external
private async _connectHass(auth: Auth) {
    const conn = await createConnection({ auth });
    // Make sure config and user info is loaded before we initialize.
    // It is needed for the core config step.
    await Promise.all([
      subscribeOne(conn, subscribeConfig),
      subscribeOne(conn, subscribeUser),
    ]);
    this.initializeHass(auth, conn);
    // Load config strings for integrations
    (this as any)._loadFragmentTranslations(this.hass!.language, "config");
    // Make sure hass is initialized + the config/user callbacks have called.
    await new Promise((resolve) => setTimeout(resolve, 0));
  }
}
github zachowj / node-red-contrib-home-assistant-websocket / lib / ha-websocket.js View on Github external
'disconnected',
            this.onClientClose.bind(this)
        );
        this.client.addEventListener(
            'reconnect-error',
            this.onClientError.bind(this)
        );

        // Home Assistant Events
        homeassistant.subscribeEntities(this.client, ent =>
            this.onClientStates(ent)
        );
        homeassistant.subscribeServices(this.client, ent =>
            this.onClientServices(ent)
        );
        homeassistant.subscribeConfig(this.client, config =>
            this.onClientConfigUpdate(config)
        );

        return true;
    }
github home-assistant / home-assistant-polymer / src / state / connection-mixin.ts View on Github external
const conn = this.hass!.connection;

      broadcastConnectionStatus("connected");

      conn.addEventListener("ready", () => this.hassReconnected());
      conn.addEventListener("disconnected", () => this.hassDisconnected());
      // If we reconnect after losing connection and auth is no longer valid.
      conn.addEventListener("reconnect-error", (_conn, err) => {
        if (err === ERR_INVALID_AUTH) {
          broadcastConnectionStatus("auth-invalid");
          location.reload();
        }
      });

      subscribeEntities(conn, (states) => this._updateHass({ states }));
      subscribeConfig(conn, (config) => this._updateHass({ config }));
      subscribeServices(conn, (services) => this._updateHass({ services }));
      subscribePanels(conn, (panels) => this._updateHass({ panels }));
    }
github home-assistant / home-assistant-polymer / src / entrypoints / core.ts View on Github external
window.hassConnection.then(({ conn }) => {
  const noop = () => {
    // do nothing
  };
  subscribeEntities(conn, noop);
  subscribeConfig(conn, noop);
  subscribeServices(conn, noop);
  subscribePanels(conn, noop);
  subscribeThemes(conn, noop);
  subscribeUser(conn, noop);

  if (location.pathname === "/" || location.pathname.startsWith("/lovelace/")) {
    (window as WindowWithLovelaceProm).llConfProm = fetchConfig(conn, false);
  }
});
github home-assistant / home-assistant-polymer / src / state / connection-mixin.ts View on Github external
const conn = this.hass!.connection;

      broadcastConnectionStatus("connected");

      conn.addEventListener("ready", () => this.hassReconnected());
      conn.addEventListener("disconnected", () => this.hassDisconnected());
      // If we reconnect after losing connection and auth is no longer valid.
      conn.addEventListener("reconnect-error", (_conn, err) => {
        if (err === ERR_INVALID_AUTH) {
          broadcastConnectionStatus("auth-invalid");
          location.reload();
        }
      });

      subscribeEntities(conn, (states) => this._updateHass({ states }));
      subscribeConfig(conn, (config) => this._updateHass({ config }));
      subscribeServices(conn, (services) => this._updateHass({ services }));
      subscribePanels(conn, (panels) => this._updateHass({ panels }));
    }
github home-assistant / home-assistant-polymer / src / entrypoints / core.ts View on Github external
window.hassConnection.then(({ conn }) => {
  const noop = () => {
    // do nothing
  };
  subscribeEntities(conn, noop);
  subscribeConfig(conn, noop);
  subscribeServices(conn, noop);
  subscribePanels(conn, noop);
  subscribeThemes(conn, noop);
  subscribeUser(conn, noop);

  if (location.pathname === "/" || location.pathname.startsWith("/lovelace/")) {
    (window as WindowWithLovelaceProm).llConfProm = fetchConfig(conn, false);
  }
});