homebridge#APIEvent TypeScript Examples

The following examples show how to use homebridge#APIEvent. 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: 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 #2
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 #3
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 #4
Source File: platform.ts    From HomebridgeMagicHome-DynamicPlatform with Apache License 2.0 6 votes vote down vote up
constructor(
    public readonly hbLogger: Logger,
    public readonly config: PlatformConfig,
    public readonly api: API,
  ) {
    if (this.config.advancedOptions.logLevel) {
      this.logs = new Logs(hbLogger, this.config.advancedOptions.logLevel);
    } else {
      this.logs = new Logs(hbLogger);
    }

    //this.logs = getLogger();
    this.logs.warn('Finished initializing homebridge-magichome-dynamic-platform %o', loadJson<any>(join(__dirname, '../package.json'), {}).version);
    this.logs.info('If this plugin brings you joy, consider visiting GitHub and giving it a ⭐.');

    // When this event is fired it means Homebridge has restored all cached accessories from disk.
    // Dynamic Platform plugins should only register new accessories after this event was fired,
    // in order to ensure they weren't added to homebridge already. This event can also be used
    // to start discovery of new accessories.
    this.api.on(APIEvent.DID_FINISH_LAUNCHING, () => {
      this.logs.debug('Executed didFinishLaunching callback');
      this.count = 1;
      // run the method to discover / register your devices as accessories
      this.discoverDevices(true);
      // Periodic scan for devices
      const shouldRediscover = this.config.advancedOptions?.periodicDiscovery ?? false;

      if (shouldRediscover) {
        this.periodicDiscovery = setInterval(() => this.discoverDevices(false), 30000);
      }
    });
  }
Example #5
Source File: platform.ts    From homebridge-plugin-govee with Apache License 2.0 6 votes vote down vote up
private goveeScanStopped() {
    this.log.info("Govee Scan Stopped");

    if (!this.platformStatus || this.platformStatus === APIEvent.SHUTDOWN) {
      return;
    }

    const WAIT_INTERVAL = 5000;
    // wait, and restart discovery if platform status doesn't change

    setTimeout(() => {
      if (!this.platformStatus || this.platformStatus === APIEvent.SHUTDOWN) {
        return;
      }

      this.log.warn("Govee discovery stopped while Homebridge is running.");

      this.log.info("Restart Discovery");
      GoveeStartDiscovery(this.goveeDiscoveredReading.bind(this));
    }, WAIT_INTERVAL);
  }
Example #6
Source File: platform.ts    From homebridge-plugin-govee with Apache License 2.0 6 votes vote down vote up
constructor(
    public readonly log: Logger,
    public readonly config: PlatformConfig,
    public readonly api: API
  ) {
    this.log.info("Finished initializing platform:", this.config.name);

    // When this event is fired it means Homebridge has restored all cached accessories from disk.
    // Dynamic Platform plugins should only register new accessories after this event was fired,
    // in order to ensure they weren't added to homebridge already. This event can also be used
    // to start discovery of new accessories.
    this.api.on("didFinishLaunching", () => {
      log.debug("Executed didFinishLaunching callback");
      // run the method to discover / register your devices as accessories

      this.platformStatus = APIEvent.DID_FINISH_LAUNCHING;

      this.discoverDevices();
    });

    this.api.on("shutdown", () => {
      this.platformStatus = APIEvent.SHUTDOWN;
    });
  }
Example #7
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 #8
Source File: platform.ts    From homebridge-zigbee-nt with Apache License 2.0 6 votes vote down vote up
constructor(
    public readonly log: Logger,
    public readonly config: ZigBeeNTPlatformConfig,
    public readonly api: API
  ) {
    const packageJson = JSON.parse(
      fs.readFileSync(`${path.resolve(__dirname, '../package.json')}`, 'utf-8')
    );
    this.accessories = new Map<string, PlatformAccessory>();
    this.homekitAccessories = new Map<string, ZigBeeAccessory>();
    this.permitJoinAccessory = null;
    this.PlatformAccessory = this.api.platformAccessory;
    this.log.info(
      `Initializing platform: ${this.config.name} - v${packageJson.version} (API v${api.version})`
    );
    if (config.devices) {
      config.devices.forEach(config => {
        this.log.info(
          `Registering custom configured device ${config.manufacturer} - ${config.models.join(
            ', '
          )}`
        );
        registerAccessoryFactory(
          config.manufacturer,
          config.models,
          (
            platform: ZigbeeNTHomebridgePlatform,
            accessory: PlatformAccessory,
            client: ZigBeeClient,
            device: Device
          ) => new ConfigurableAccessory(platform, accessory, client, device, config.services)
        );
      });
    }
    this.api.on(APIEvent.DID_FINISH_LAUNCHING, () => this.startZigBee());
    this.api.on(APIEvent.SHUTDOWN, () => this.stopZigbee());
  }
Example #9
Source File: platform.ts    From homebridge-lg-thinq-ac with Apache License 2.0 6 votes vote down vote up
constructor(
    public readonly log: Logger,
    public readonly config: PlatformConfig & HomebridgeLgThinqPlatformConfig,
    public readonly api: API,
  ) {
    this.didFinishLaunching = new Promise((resolve) => {
      // Store the resolver locally.
      // Steps that depend on this can `await didFinishLaunching`.
      // When Homebridge is finishes launching, this will be called to resolve.
      this.handleFinishedLaunching = resolve
    })
    this.log.debug('Finished initializing platform:', this.config.name)

    this.initialize()

    // When this event is fired it means Homebridge has restored all cached accessories from disk.
    // Dynamic Platform plugins should only register new accessories after this event was fired,
    // in order to ensure they weren't added to homebridge already. This event can also be used
    // to start discovery of new accessories.
    this.api.on(APIEvent.DID_FINISH_LAUNCHING, () => {
      this.log.debug('Executed didFinishLaunching callback')
      if (this.handleFinishedLaunching) {
        this.handleFinishedLaunching()
      }
    })
  }
Example #10
Source File: platform.ts    From homebridge-plugin-govee with Apache License 2.0 5 votes vote down vote up
private platformStatus?: APIEvent;
Example #11
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 #12
Source File: new-streaming-delegate.ts    From homebridge-plugin-eufy-security with Apache License 2.0 5 votes vote down vote up
constructor(platform: EufySecurityHomebridgePlatform, device: FullDevice) {
    this.log = platform.log;
    this.hap = platform.api.hap;
    this.platform = platform;
    this.device = device;

    this.cameraName = device.device_name;
    this.videoProcessor = ffmpegPath || 'ffmpeg';

    platform.api.on(APIEvent.SHUTDOWN, () => {
      for (const session in this.ongoingSessions) {
        this.stopStream(session);
      }
    });

    const options: CameraControllerOptions = {
      cameraStreamCount: 2, // HomeKit requires at least 2 streams, but 1 is also just fine
      delegate: this,
      streamingOptions: {
        supportedCryptoSuites: [
          this.hap.SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80,
        ],
        video: {
          resolutions: [
            [320, 180, 30],
            [320, 240, 15], // Apple Watch requires this configuration
            [320, 240, 30],
            [480, 270, 30],
            [480, 360, 30],
            [640, 360, 30],
            [640, 480, 30],
            [1280, 720, 30],
            [1280, 960, 30],
            [1920, 1080, 30],
            [1600, 1200, 30],
          ],
          codec: {
            profiles: [
              this.hap.H264Profile.BASELINE,
              this.hap.H264Profile.MAIN,
              this.hap.H264Profile.HIGH,
            ],
            levels: [
              this.hap.H264Level.LEVEL3_1,
              this.hap.H264Level.LEVEL3_2,
              this.hap.H264Level.LEVEL4_0,
            ],
          },
        },
        audio: {
          twoWayAudio: false, // !!this.videoConfig.returnAudioTarget,
          codecs: [
            {
              type: AudioStreamingCodecType.AAC_ELD,
              samplerate: AudioStreamingSamplerate.KHZ_16,
            },
          ],
        },
      },
    };

    this.controller = new this.hap.CameraController(options);
  }
Example #13
Source File: platform.ts    From homebridge-samsungtv-control2 with MIT License 5 votes vote down vote up
constructor(
    public readonly log: Logger,
    public readonly config: PlatformConfig,
    public readonly api: API,
  ) {
    this.log = log
    this.config = config
    this.api = api

    this.Service = api.hap.Service
    this.Characteristic = api.hap.Characteristic

    this.log.debug(`Got config`, this.config)

    // Add devices
    api.on(APIEvent.DID_FINISH_LAUNCHING, async () => {
      const dir = path.join(api.user.storagePath(), `.${PLUGIN_NAME}`)
      this.log.debug(`Using node-persist path:`, dir)
      await storage.init({
        dir,
        logging: (...args) => this.log.debug(`${PLATFORM_NAME} db -`, ...args),
      })

      let devices = await this.discoverDevices()
      devices = await this.applyConfig(devices)
      this.devices = await this.checkDevicePairing(devices)

      // Register all TV's
      for (const device of this.devices) {
        // Log all devices so that the user knows how to configure them
        this.log.info(
          chalk`Found device {blue ${device.name}} (${device.modelName}), usn: {green ${device.usn}}`,
        )
        this.log.debug(
          `${device.name} - (ip: ${device.lastKnownIp}, mac: ${device.mac})`,
        )
        // Register it
        this.registerTV(device.usn)
      }

      // Regularly discover upnp devices and update ip's, locations for registered devices
      setInterval(async () => {
        const devices = await this.discoverDevices()
        this.devices = await this.applyConfig(devices)
        /**
         * @todo
         * add previously not registered devices
         */
      }, 1000 * 60 * 5 /* 5min */)

      /**
       * @TODO
       * Add subscriptions to update getters
       */
    })
  }
Example #14
Source File: streamingDelegate.ts    From homebridge-eufy-security with Apache License 2.0 5 votes vote down vote up
constructor(platform: EufySecurityPlatform, device: Camera, cameraConfig: CameraConfig, api: API, hap: HAP) { // eslint-disable-line @typescript-eslint/explicit-module-boundary-types
    this.log = platform.log;
    this.hap = hap;

    this.device = device;

    this.cameraName = device.getName()!;
    this.unbridge = false;
    this.videoConfig = cameraConfig.videoConfig!;
    this.videoProcessor = ffmpegPath || 'ffmpeg';

    api.on(APIEvent.SHUTDOWN, () => {
      for (const session in this.ongoingSessions) {
        this.stopStream(session);
      }
    });

    const options: CameraControllerOptions = {
      cameraStreamCount: this.videoConfig.maxStreams || 2, // HomeKit requires at least 2 streams, but 1 is also just fine
      delegate: this,
      streamingOptions: {
        supportedCryptoSuites: [hap.SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80],
        video: {
          resolutions: [
            [320, 180, 30],
            [320, 240, 15], // Apple Watch requires this configuration
            [320, 240, 30],
            [480, 270, 30],
            [480, 360, 30],
            [640, 360, 30],
            [640, 480, 30],
            [1280, 720, 30],
            [1280, 960, 30],
            [1920, 1080, 30],
            [1600, 1200, 30]
          ],
          codec: {
            profiles: [hap.H264Profile.BASELINE, hap.H264Profile.MAIN, hap.H264Profile.HIGH],
            levels: [hap.H264Level.LEVEL3_1, hap.H264Level.LEVEL3_2, hap.H264Level.LEVEL4_0]
          }
        },
        audio: {
          twoWayAudio: !!this.videoConfig.returnAudioTarget,
          codecs: [
            {
              type: AudioStreamingCodecType.AAC_ELD,
              samplerate: AudioStreamingSamplerate.KHZ_16
              /*type: AudioStreamingCodecType.OPUS,
              samplerate: AudioStreamingSamplerate.KHZ_24*/
            }
          ]
        }
      }
    };

    this.controller = new hap.CameraController(options);
  }