homebridge#Logging TypeScript Examples

The following examples show how to use homebridge#Logging. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: streamer.ts    From homebridge-nest-cam with GNU General Public License v3.0 6 votes vote down vote up
constructor(
    cameraInfo: CameraInfo,
    accessToken: string | undefined,
    streamQuality: StreamQuality,
    ffmpegVideo: FfmpegProcess,
    ffmpegAudio?: FfmpegProcess,
    ffmpegReturnAudio?: FfmpegProcess,
    log?: Logging,
    nestAuth?: boolean,
  ) {
    this.log = log;
    this.streamQuality = streamQuality;
    this.ffmpegVideo = ffmpegVideo;
    this.ffmpegAudio = ffmpegAudio;
    this.ffmpegReturnAudio = ffmpegReturnAudio;
    this.cameraInfo = cameraInfo;
    this.accessToken = accessToken;
    this.nestAuth = nestAuth || false;
    this.setupConnection(cameraInfo.websocket_nexustalk_host);
  }
Example #2
Source File: platform.ts    From homebridge-esphome-ts with GNU General Public License v3.0 6 votes vote down vote up
constructor(
        protected readonly log: Logging,
        protected readonly config: IEsphomePlatformConfig,
        protected readonly api: API,
    ) {
        this.subscription = new Subscription();
        this.log('starting esphome');
        if (!Array.isArray(this.config.devices) && !this.config.discover) {
            this.log.error(
                'You did not specify a devices array and discovery is ' +
                    'disabled! Esphome will not provide any accessories',
            );
            this.config.devices = [];
        }
        this.blacklistSet = new Set<string>(this.config.blacklist ?? []);

        this.api.on('didFinishLaunching', () => {
            this.onHomebridgeDidFinishLaunching();
        });
        this.api.on('shutdown', () => {
            this.espDevices.forEach((device: EspDevice) => device.terminate());
            this.subscription.unsubscribe();
        });
    }
Example #3
Source File: discovery.ts    From homebridge-esphome-ts with GNU General Public License v3.0 6 votes vote down vote up
discoverDevices = (timeout: number, log: Logging): Observable<DiscoveryResult> => {
    return new Observable<BonjourService>((subscriber) => {
        const browser = bonjour.find({ type: 'esphomelib' }, (service) => {
            subscriber.next(service);
        });
        setTimeout(() => {
            browser.stop();
            subscriber.complete();
        }, timeout);
    }).pipe(
        map((findResult: BonjourService) => {
            log.info('HAP Device discovered', findResult.name);
            const address = findResult.addresses.find((addr) => {
                return (ip.isV4Format(addr) && addr.substring(0, 7) !== '169.254') || ip.isV6Format(addr);
            });
            const port = findResult.port && findResult.port !== DEFAULT_PORT ? findResult.port : undefined;
            return {
                host: findResult.host,
                port,
                address,
            };
        }),
    );
}
Example #4
Source File: index.ts    From homebridge-fordpass with GNU General Public License v3.0 6 votes vote down vote up
constructor(log: Logging, config: PlatformConfig, api: API) {
    this.log = log;
    this.api = api;
    this.config = config as FordpassConfig;

    // Need a config or plugin will not start
    if (!config) {
      return;
    }

    if (!config.username || !config.password) {
      this.log.error('Please add a userame and password to your config.json');
      return;
    }

    api.on(APIEvent.DID_FINISH_LAUNCHING, this.didFinishLaunching.bind(this));
  }
Example #5
Source File: accessory.ts    From homebridge-nest-cam with GNU General Public License v3.0 6 votes vote down vote up
constructor(accessory: PlatformAccessory, camera: NestCam, config: PlatformConfig, log: Logging, hap: HAP) {
    this.accessory = accessory;
    this.camera = camera;
    this.config = config;
    this.log = log;
    this.hap = hap;

    // Setup events
    camera.on(NestCamEvents.CAMERA_STATE_CHANGED, (value: boolean) => {
      const service = this.accessory.getService(`${this.accessory.displayName} Streaming`);
      service && service.updateCharacteristic(this.hap.Characteristic.On, value);
    });
    camera.on(NestCamEvents.CHIME_STATE_CHANGED, (value: boolean) => {
      const service = this.accessory.getService(`${this.accessory.displayName} Chime`);
      service && service.updateCharacteristic(this.hap.Characteristic.On, value);
    });
    camera.on(NestCamEvents.CHIME_ASSIST_STATE_CHANGED, (value: boolean) => {
      const service = this.accessory.getService(`${this.accessory.displayName} Announcements`);
      service && service.updateCharacteristic(this.hap.Characteristic.On, value);
    });
    camera.on(NestCamEvents.AUDIO_STATE_CHANGED, (value: boolean) => {
      const service = this.accessory.getService(`${this.accessory.displayName} Audio`);
      service && service.updateCharacteristic(this.hap.Characteristic.On, value);
    });
    camera.on(NestCamEvents.MOTION_DETECTED, (state: boolean, alertTypes: Array<string>) => {
      this.setMotion(state, alertTypes);
    });
    camera.on(NestCamEvents.DOORBELL_RANG, () => {
      this.setDoorbell();
    });
  }
Example #6
Source File: wled-platform.ts    From homebridge-simple-wled with ISC License 6 votes vote down vote up
constructor(log: Logging, config: PlatformConfig, api: API) {
    this.api = api;

    this.config = config;
    this.log = log;

    if (!config) {
      return;
    }

    if (!config.wleds) {
      this.log("No WLEDs have been configured.");
      return;
    }

    api.on(APIEvent.DID_FINISH_LAUNCHING, this.launchWLEDs.bind(this));
  }
Example #7
Source File: streaming-delegate.ts    From homebridge-nest-cam with GNU General Public License v3.0 6 votes vote down vote up
constructor(hap: HAP, camera: NestCam, config: NestConfig, log: Logging) {
    this.hap = hap;
    this.log = log;
    this.config = config;
    this.camera = camera;
    this.customFfmpeg = config.options?.pathToFfmpeg;
    this.videoProcessor = this.customFfmpeg || pathToFfmpeg || 'ffmpeg';

    // Get the correct video codec
    getCodecsOutput(this.videoProcessor)
      .then((output) => {
        const codec = config.options?.ffmpegCodec;
        if (codec === 'copy' || (codec && output.includes(codec))) {
          this.ffmpegCodec = codec;
        } else {
          this.log.error(`Unknown video codec ${codec}. Defaulting to libx264.`);
        }
        this.ffmpegSupportsLibfdk_acc = output.includes('libfdk_aac');
        this.ffmpegSupportsLibspeex = output.includes('libspeex');
      })
      .catch(() => {
        // skip
      });

    // Check if ffmpeg is installed
    isFfmpegInstalled(this.videoProcessor)
      .then((installed) => {
        this.ffmpegInstalled = installed;
      })
      .catch(() => {
        // skip
      });
  }
Example #8
Source File: index.ts    From homebridge-nest-cam with GNU General Public License v3.0 6 votes vote down vote up
constructor(log: Logging, config: PlatformConfig, api: API) {
    this.log = log;
    this.api = api;
    this.config = config as NestConfig;
    this.options = new Options();

    // Need a config or plugin will not start
    if (!config) {
      return;
    }

    this.initDefaultOptions();
    api.on(APIEvent.DID_FINISH_LAUNCHING, this.didFinishLaunching.bind(this));
    api.on(APIEvent.SHUTDOWN, this.isShuttingDown.bind(this));
  }
Example #9
Source File: endpoints.ts    From homebridge-nest-cam with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Handle an axios error
 * @param {Logging} log     The log object to output error
 * @param {any} error       The error thrown
 * @param {string} message  The message to add to the log output
 */
export function handleError(log: Logging | undefined, error: any, message: string, debug = false): void {
  const addendum = 'Troubleshoot here: https://git.io/Jtxww';
  if (error.response) {
    const status = parseInt(error.response.status);
    const errMsg = `${message}: ${status}`;
    if (status >= 500 || status === 404) {
      log?.debug(`${errMsg}\n${addendum}`);
    } else {
      debug ? log?.debug(`${errMsg}\n${addendum}`) : log?.error(`${errMsg}\n${addendum}`);
    }
  } else if (error.code) {
    const errMsg = `${message}: ${error.code}`;
    if (error.code === 'ECONNRESET' || error.code === 'EAI_AGAIN') {
      log?.debug(`${errMsg}\n${addendum}`);
    } else {
      debug ? log?.debug(`${errMsg}\n${addendum}`) : log?.error(`${errMsg}\n${addendum}`);
    }
  } else {
    log?.error(error);
  }
}
Example #10
Source File: cam.ts    From homebridge-nest-cam with GNU General Public License v3.0 6 votes vote down vote up
constructor(config: NestConfig, info: CameraInfo, log?: Logging) {
    super();
    this.log = log;
    this.config = config;
    this.info = info;
    this.lastUpdatedTime = new Date();
    this.alertCooldown = (config.options?.alertCooldownRate || 180) * 1000;
    if (this.alertCooldown > 300000) {
      this.alertCooldown = 300000;
    }
    this.alertInterval = (config.options?.alertCheckRate || 10) * 1000;
    if (this.alertInterval > 60000) {
      this.alertInterval = 60000;
    }
    this.endpoints = new NestEndpoints(config.options?.fieldTest);

    const alertTypes = config.options?.alertTypes;
    if (typeof alertTypes !== 'undefined') {
      log?.debug(`Using alertTypes from config: ${alertTypes}`);
      this.alertTypes = alertTypes.slice();
    }
    const importantOnly = config.options?.importantOnly;
    if (typeof importantOnly !== 'undefined') {
      log?.debug(`Using importantOnly from config: ${importantOnly}`);
      this.importantOnly = importantOnly;
    }
  }
Example #11
Source File: connection.ts    From homebridge-nest-cam with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get info on all cameras
 */
export async function getCameras(config: NestConfig, log?: Logging): Promise<Array<CameraInfo>> {
  const endpoints = new NestEndpoints(config.options?.fieldTest);
  let cameras: Array<CameraInfo> = [];
  try {
    const response = await endpoints.sendRequest(
      config.access_token,
      endpoints.CAMERA_API_HOSTNAME,
      '/api/cameras.get_owned_and_member_of_with_properties',
      'GET',
    );
    cameras = response.items;
  } catch (error) {
    if (log) {
      handleError(log, error, 'Error fetching cameras');
    }
  }
  return cameras;
}
Example #12
Source File: index.ts    From homebridge-philips-air with BSD 2-Clause "Simplified" License 6 votes vote down vote up
constructor(log: Logging, config: PlatformConfig, api: API) {
    this.log = log;
    this.config = config as unknown as PhilipsAirPlatformConfig;
    this.api = api;

    this.timeout = (this.config.timeout_seconds || 5) * 1000;

    api.on(APIEvent.DID_FINISH_LAUNCHING, this.didFinishLaunching.bind(this));
  }
Example #13
Source File: index.ts    From homebridge-electrolux-wellbeing with Apache License 2.0 5 votes vote down vote up
private readonly log: Logging;
Example #14
Source File: structure.ts    From homebridge-nest-cam with GNU General Public License v3.0 5 votes vote down vote up
constructor(cameraInfo: CameraInfo, config: NestConfig, log?: Logging) {
    this.id = cameraInfo.nest_structure_id.replace('structure.', '');
    this.apiHost = cameraInfo.nexus_api_nest_domain_host;
    this.config = config;
    this.log = log;
    this.endpoints = new NestEndpoints(config.options?.fieldTest);
  }
Example #15
Source File: structure.ts    From homebridge-nest-cam with GNU General Public License v3.0 5 votes vote down vote up
private readonly log: Logging | undefined;
Example #16
Source File: streaming-delegate.ts    From homebridge-nest-cam with GNU General Public License v3.0 5 votes vote down vote up
private readonly log: Logging;
Example #17
Source File: index.ts    From homebridge-philips-air with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private readonly log: Logging;
Example #18
Source File: index.ts    From homebridge-electrolux-wellbeing with Apache License 2.0 5 votes vote down vote up
constructor(log: Logging, config: PlatformConfig, api: API) {
    this.log = log;
    this.api = api;
    this.config = config;

    api.on(APIEvent.DID_FINISH_LAUNCHING, async () => {
      if (this.needsConfiguration()) {
        this.log('Please configure this plugin first.');
        return;
      }

      //this.removeAccessories();

      try {
        this.client = await createClient({
          username: this.config.username,
          password: this.config.password,
        });
      } catch (err) {
        this.log.debug('Error while creating client', err);
        return;
      }

      const appliances = await this.getAllAppliances();
      const applianceData = await Promise.all(
        appliances.map((appliance) => this.fetchApplianceData(appliance.pncId)),
      );

      this.log.debug('Fetched: ', applianceData);

      appliances.map(({ applianceName, modelName, pncId }, i) => {
        this.addAccessory({
          pncId,
          name: applianceName,
          modelName,
          firmwareVersion: applianceData[i]?.firmwareVersion,
        });
      });

      this.updateValues(applianceData);
      setInterval(
        () => this.checkAppliances(),
        this.getPollTime(this.config.pollTime),
      );
    });
  }
Example #19
Source File: session.ts    From homebridge-nest-cam with GNU General Public License v3.0 5 votes vote down vote up
constructor(config: NestConfig, log?: Logging) {
    this.endpoints = new NestEndpoints(config.options?.fieldTest);
    this.config = config;
    this.log = log;
  }
Example #20
Source File: wled-accessory.ts    From homebridge-simple-wled with ISC License 5 votes vote down vote up
private readonly log: Logging;
Example #21
Source File: wled-platform.ts    From homebridge-simple-wled with ISC License 5 votes vote down vote up
readonly log: Logging;
Example #22
Source File: logger.ts    From homebridge-eufy-security with Apache License 2.0 5 votes vote down vote up
constructor(log: Logging) {
    this.log = log;
    this.debugMode = process.argv.includes('-D') || process.argv.includes('--debug');
  }
Example #23
Source File: logger.ts    From homebridge-eufy-security with Apache License 2.0 5 votes vote down vote up
private readonly log: Logging;
Example #24
Source File: streamer.ts    From homebridge-nest-cam with GNU General Public License v3.0 5 votes vote down vote up
private readonly log: Logging | undefined;
Example #25
Source File: session.ts    From homebridge-nest-cam with GNU General Public License v3.0 5 votes vote down vote up
private readonly log: Logging | undefined;
Example #26
Source File: fordpass-connection.ts    From homebridge-fordpass with GNU General Public License v3.0 5 votes vote down vote up
constructor(config: FordpassConfig, log: Logging) {
    this.config = config;
    this.log = log;
    this.applicationId = config.options?.region || defaultAppId;
  }
Example #27
Source File: connection.ts    From homebridge-nest-cam with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Attempt to authenticate using unmigrated Nest account
 */
export async function nest_auth(nest_token: string, log?: Logging): Promise<string> {
  let req: AxiosRequestConfig;

  log?.debug('Authenticating via pre-defined nest_token');
  let result;
  try {
    req = {
      method: 'POST',
      timeout: API_TIMEOUT_SECONDS * 1000,
      url: NEST_AUTH_URL,
      data: querystring.stringify({
        access_token: nest_token,
      }),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: 'Basic ' + nest_token,
        'User-Agent': NestEndpoints.USER_AGENT_STRING,
        Referer: 'https://home.nest.com',
      },
    };
    result = (await axios(req)).data;
    if (result.error) {
      log?.error('Nest authentication was unsuccessful.');
      throw result;
    }
    return result.items[0].session_token;
  } catch (error: any) {
    error.status = error.response && error.response.status;
    log?.error('Nest authentication failed (code ' + (error.status || error.code) + ').');
    if (['ECONNREFUSED', 'ESOCKETTIMEDOUT', 'ECONNABORTED', 'ENOTFOUND', 'ENETUNREACH'].includes(error.code)) {
      log?.error('Retrying in ' + API_AUTH_FAIL_RETRY_DELAY_SECONDS + ' second(s).');
      await delay(API_AUTH_FAIL_RETRY_DELAY_SECONDS * 1000);
      return await nest_auth(nest_token, log);
    } else {
      return '';
    }
  }
}
Example #28
Source File: connection.ts    From homebridge-nest-cam with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Attempt to authenticate Nest via Google account with browser cookies
 */
export async function old_auth(issueToken: string, cookies: string, apiKey?: string, log?: Logging): Promise<string> {
  let req: AxiosRequestConfig;

  issueToken = issueToken.replace('Request URL: ', '');
  cookies = cookies.replace('cookie: ', '');
  const referer: string = querystring.parse(issueToken).ss_domain?.toString() || '';
  if (!referer) {
    log?.error('issueToken is invalid');
    return '';
  }
  const fieldTest = referer !== 'https://home.nest.com';

  apiKey =
    apiKey?.replace('x-goog-api-key: ', '') ||
    (fieldTest ? 'AIzaSyB0WNyJX2EQQujlknzTDD9jz7iVHK5Jn-U' : 'AIzaSyAdkSIMNc51XGNEAYWasX9UOWkS5P6sZE4');

  log?.debug('Authenticating via Google.');
  let result;
  try {
    req = {
      method: 'GET',
      timeout: API_TIMEOUT_SECONDS * 1000,
      url: issueToken,
      headers: {
        'Sec-Fetch-Mode': 'cors',
        'User-Agent': NestEndpoints.USER_AGENT_STRING,
        'X-Requested-With': 'XmlHttpRequest',
        Referer: 'https://accounts.google.com/o/oauth2/iframe',
        cookie: cookies,
      },
    };
    result = (await axios(req)).data;
    const googleAccessToken = result.access_token;
    if (result.error) {
      log?.error(
        'Google authentication was unsuccessful. Make sure you did not log out of your Google account after getting your googleAuth parameters.',
      );
      throw result;
    }
    req = {
      method: 'POST',
      timeout: API_TIMEOUT_SECONDS * 1000,
      url: 'https://nestauthproxyservice-pa.googleapis.com/v1/issue_jwt',
      data: {
        embed_google_oauth_access_token: true,
        expire_after: '3600s', //expire the access token in 1 hour
        google_oauth_access_token: googleAccessToken,
        policy_id: 'authproxy-oauth-policy',
      },
      headers: {
        Authorization: 'Bearer ' + googleAccessToken,
        'User-Agent': NestEndpoints.USER_AGENT_STRING,
        'x-goog-api-key': apiKey,
        Referer: referer,
      },
    };
    result = (await axios(req)).data;
    return result.jwt;
  } catch (error: any) {
    error.status = error.response && error.response.status;
    log?.error('Access token acquisition via googleAuth failed (code ' + (error.status || error.code) + ').');
    if (['ECONNREFUSED', 'ESOCKETTIMEDOUT', 'ECONNABORTED', 'ENOTFOUND', 'ENETUNREACH'].includes(error.code)) {
      log?.error('Retrying in ' + API_AUTH_FAIL_RETRY_DELAY_SECONDS + ' second(s).');
      await delay(API_AUTH_FAIL_RETRY_DELAY_SECONDS * 1000);
      return await old_auth(issueToken, cookies);
    } else {
      return '';
    }
  }
}
Example #29
Source File: connection.ts    From homebridge-nest-cam with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Attempt to authenticate Nest via Google account with refresh token
 */
export async function auth(refreshToken: string, ft = false, log?: Logging): Promise<string> {
  let req: AxiosRequestConfig;
  const apiKey = ft ? APIKEY_FT : APIKEY;

  log?.debug('Authenticating via Google refresh token.');
  let result;
  try {
    req = {
      method: 'POST',
      timeout: API_TIMEOUT_SECONDS * 1000,
      url: TOKEN_URL,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': NestEndpoints.USER_AGENT_STRING,
      },
      data: querystring.stringify({
        refresh_token: refreshToken,
        client_id: ft ? CLIENT_ID_FT : CLIENT_ID,
        grant_type: 'refresh_token',
      }),
    };
    result = (await axios(req)).data;
    const googleAccessToken = result.access_token;
    if (result.error) {
      log?.error('Google authentication was unsuccessful.');
      throw result;
    }
    req = {
      method: 'POST',
      timeout: API_TIMEOUT_SECONDS * 1000,
      url: ISSUE_JWT_URL,
      data: {
        embed_google_oauth_access_token: true,
        expire_after: '3600s', //expire the access token in 1 hour
        google_oauth_access_token: googleAccessToken,
        policy_id: 'authproxy-oauth-policy',
      },
      headers: {
        Authorization: 'Bearer ' + googleAccessToken,
        'User-Agent': NestEndpoints.USER_AGENT_STRING,
        'x-goog-api-key': apiKey,
      },
    };
    result = (await axios(req)).data;
    return result.jwt;
  } catch (error: any) {
    error.status = error.response && error.response.status;
    log?.error('Access token acquisition via refresh token failed (code ' + (error.status || error.code) + ').');
    if (['ECONNREFUSED', 'ESOCKETTIMEDOUT', 'ECONNABORTED', 'ENOTFOUND', 'ENETUNREACH'].includes(error.code)) {
      log?.error('Retrying in ' + API_AUTH_FAIL_RETRY_DELAY_SECONDS + ' second(s).');
      await delay(API_AUTH_FAIL_RETRY_DELAY_SECONDS * 1000);
      return await auth(refreshToken, ft, log);
    } else {
      return '';
    }
  }
}