homebridge#API TypeScript Examples

The following examples show how to use homebridge#API. 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: platform.ts    From homebridge-plugin-template 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.debug('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.discoverDevices();
    });
  }
Example #2
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 #3
Source File: platform.ts    From homebridge-screenlogic with MIT License 6 votes vote down vote up
constructor(public readonly log: Logger, config: PlatformConfig, public readonly api: API) {
    this.log.debug('Finished initializing platform', PLATFORM_NAME)

    this.config = config as ScreenLogicPlatformConfig
    // do this first to make sure we have proper defaults moving forward
    this.applyConfigDefaults(config)

    this.controller = new Controller({
      log: this.log,
      ip_address: this.config.ip_address,
      port: this.config.port,
      username: this.config.username,
      password: this.config.password,
    })

    // 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.discoverDevices(0)
    })
  }
Example #4
Source File: platform.ts    From homebridge-tuya-ir 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.debug('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.discoverDevices();
    });
  }
Example #5
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 #6
Source File: index.ts    From homebridge-zigbee-nt with Apache License 2.0 6 votes vote down vote up
/**
 * This method registers the platform with Homebridge
 */
export default function(homebridge: API): void {
  HomebridgeAPI = homebridge;
  initCustomCharacteristics(homebridge);
  registerSupportedDevices();
  homebridge.registerPlatform(PLUGIN_IDENTIFIER, PLATFORM_NAME, ZigbeeNTHomebridgePlatform);
}
Example #7
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 #8
Source File: wiz.ts    From homebridge-wiz-lan with Apache License 2.0 6 votes vote down vote up
constructor(
    public readonly log: Logger,
    public readonly config: Config,
    public readonly api: API
  ) {
    this.socket = createSocket(this);

    // 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
      bindSocket(this, () => {
        registerDiscoveryHandler(this, this.tryAddDevice.bind(this));
        sendDiscoveryBroadcast(this);
      });
    });
  }
Example #9
Source File: platform.ts    From homebridge-konnected with MIT License 6 votes vote down vote up
constructor(public readonly log: Logger, public readonly config: PlatformConfig, public readonly api: API) {
    this.log.debug('Finished initializing platform');

    // Homebridge looks for and fires this event when it has retrieved all cached accessories from disk
    // this event is also used to init other methods for this plugin
    this.api.on('didFinishLaunching', () => {
      log.debug('Executed didFinishLaunching callback. Accessories retreived from cache...');

      // run the listening server & register the security system
      this.listeningServer();
      this.registerSecuritySystem();
      this.discoverPanels();
    });
  }
Example #10
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 #11
Source File: platform.ts    From homebridge-vieramatic with Apache License 2.0 6 votes vote down vote up
constructor(
    readonly log: Logger,
    private readonly config: PlatformConfig,
    private readonly api: API
  ) {
    this.storage = new Storage(api)
    this.Characteristic = this.api.hap.Characteristic
    this.Service = this.api.hap.Service

    this.log.debug('Finished initializing platform:', this.config.platform)

    this.api.on('didFinishLaunching', async () => {
      log.debug('Executed didFinishLaunching callback')
      await this.discoverDevices()
    })
  }
Example #12
Source File: platform.ts    From homebridge-iRobot 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.debug('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.discoverDevices();
    });
  }
Example #13
Source File: platform.ts    From homebridge-iRobot 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.debug('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.discoverDevices();
    });
  }
Example #14
Source File: platform.ts    From homebridge-plugin-eufy-security with Apache License 2.0 6 votes vote down vote up
constructor(
    public readonly log: Logger,
    config: PlatformConfig,
    public readonly api: API,
  ) {
    this.config = config as EufyPlatformConfig;
    // this.log.debug('Config', this.config);
    this.log.debug('Finished initializing platform:', this.config.platform);

    this.httpService = new HttpService(this.config.username, this.config.password);

    // 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', async () => {
      if (this.config.enablePush) {
        this.log.info('push client enabled');
        await this.setupPushClient();
      } else {
        this.log.info('push client disabled');
      }

      log.debug('Executed didFinishLaunching callback');
      // run the method to discover / register your devices as accessories

      try {
        this.discoverDevices();
      } catch(error) {
        this.log.error('error while discovering devices');
        this.log.error(error);
      }
    });
  }
Example #15
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 #16
Source File: platform.ts    From homebridge-tapo-p100 with Apache License 2.0 6 votes vote down vote up
constructor(
    public readonly log: Logger,
    config: PlatformConfig,
    public readonly api: API,
  ) {
    this.log.debug('config.json: %j', config);
    this.config = parseConfig(config);
    this.log.debug('config: %j', this.config);
    this.log.debug('Finished initializing platform:', this.config.name);
    this.customCharacteristics = Characteristics(api.hap.Characteristic);
    this.FakeGatoHistoryService = fakegato(this.api);
    // 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.discoverDevices();
    });
  }
Example #17
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 #18
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 #19
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 #20
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 #21
Source File: index.ts    From homebridge-zigbee-nt with Apache License 2.0 5 votes vote down vote up
export function initCustomCharacteristics(homebridge: API): void {
  HAP.Service = homebridge.hap.Service;
  HAP.Characteristic = homebridge.hap.Characteristic;
  HAP.PlatformAccessory = homebridge.platformAccessory;
  HAP.FakeGatoHistoryService = fakegato(homebridge);

  HAP.CurrentPowerConsumption = class CurrentPowerConsumption extends HAP.Characteristic {
    public static readonly UUID: string = 'E863F10D-079E-48FF-8F27-9C2605A29F52';

    constructor() {
      super('CurrentConsumption', CurrentPowerConsumption.UUID, {
        format: Formats.UINT16,
        unit: 'watts' as Units, // ??
        maxValue: 100000,
        minValue: 0,
        minStep: 1,
        perms: [Perms.PAIRED_READ, Perms.NOTIFY],
      });
    }
  };

  HAP.CurrentVoltage = class CurrentVoltage extends HAP.Characteristic {
    public static readonly UUID: string = 'E863F10A-079E-48FF-8F27-9C2605A29F52';

    constructor() {
      super('CurrentVoltage', CurrentVoltage.UUID, {
        format: Formats.UINT16,
        unit: 'volts' as Units, // ??
        maxValue: 1000,
        minValue: 0,
        minStep: 1,
        perms: [Perms.PAIRED_READ, Perms.NOTIFY],
      });
    }
  };

  HAP.CurrentConsumption = class CurrentConsumption extends HAP.Characteristic {
    public static readonly UUID: string = 'E863F126-079E-48FF-8F27-9C2605A29F52';

    constructor() {
      super('CurrentConsumption', CurrentConsumption.UUID, {
        format: Formats.UINT16,
        unit: 'ampere' as Units, // ??
        maxValue: 1000,
        minValue: 0,
        minStep: 1,
        perms: [Perms.PAIRED_READ, Perms.NOTIFY],
      });
    }
  };

  HAP.TotalConsumption = class TotalConsumption extends HAP.Characteristic {
    public static readonly UUID: string = 'E863F10C-079E-48FF-8F27-9C2605A29F52';

    constructor() {
      super('TotalConsumption', TotalConsumption.UUID, {
        format: Formats.FLOAT,
        unit: 'kWh' as Units, // ??
        minValue: 0,
        minStep: 0.001,
        perms: [Perms.PAIRED_READ, Perms.NOTIFY],
      });
    }
  };
}
Example #22
Source File: storage.ts    From homebridge-vieramatic with Apache License 2.0 5 votes vote down vote up
constructor(api: API) {
    this.#filePath = path.join(api.user.cachedAccessoryPath(), 'vieramatic.json')
    const data = fsExtra.readJsonSync(this.#filePath, { throws: false })

    this.accessories = data ?? {}
  }
Example #23
Source File: platform.ts    From homebridge-eufy-security with Apache License 2.0 5 votes vote down vote up
constructor(
    public readonly hblog: Logger,
    config: PlatformConfig,
    public readonly api: API,
  ) {
    this.config = config as EufySecurityPlatformConfig;

    this.eufyConfig = {
      username: this.config.username,
      password: this.config.password,
      country: 'US',
      language: 'en',
      persistentDir: api.user.storagePath(),
      p2pConnectionSetup: 0,
      pollingIntervalMinutes: this.config.pollingIntervalMinutes ?? 10,
      eventDurationSeconds: 10,
    } as EufySecurityConfig;


    this.config.ignoreStations = this.config.ignoreStations || [];
    this.config.ignoreDevices = this.config.ignoreDevices || [];

    if (this.config.enableDetailedLogging >= 1) {

      const plugin = require('../package.json');

      this.log = bunyan.createLogger({
        name: '[EufySecurity-' + plugin.version + ']',
        hostname: '',
        streams: [{
          level: (this.config.enableDetailedLogging === 2) ? 'trace' : 'debug',
          type: 'raw',
          stream: bunyanDebugStream({
            forceColor: true,
            showProcess: false,
            showPid: false,
            showDate: (time) => {
              return '[' + time.toLocaleString('en-US') + ']';
            },
          }),
        }],
        serializers: bunyanDebugStream.serializers,
      });
      this.log.info('Eufy Security Plugin: enableDetailedLogging on');
    } else {
      this.log = hblog;
    }

    this.eufyClient = (this.config.enableDetailedLogging === 2)
      ? new EufySecurity(this.eufyConfig, this.log)
      : new EufySecurity(this.eufyConfig);

    // Removing the ability to set Off(6) waiting Bropat feedback bropat/eufy-security-client#27
    this.config.hkOff = (this.config.hkOff === 6) ? 63 : this.config.hkOff;

    // 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', async () => {
      // await this.createConnection();
      // run the method to discover / register your devices as accessories
      await this.discoverDevices();
    });

    this.log.info('Finished initializing Eufy Security Platform');
  }
Example #24
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);
  }
Example #25
Source File: index.ts    From homebridge-fordpass with GNU General Public License v3.0 5 votes vote down vote up
private readonly api: API;
Example #26
Source File: TuyaIRDiscovery.ts    From homebridge-tuya-ir with Apache License 2.0 5 votes vote down vote up
private api: API;
Example #27
Source File: platform.d.ts    From homebridge-tuya-ir with Apache License 2.0 5 votes vote down vote up
readonly api: API;
Example #28
Source File: platform.d.ts    From homebridge-tuya-ir with Apache License 2.0 5 votes vote down vote up
constructor(log: Logger, config: PlatformConfig, api: API);
Example #29
Source File: index.d.ts    From homebridge-tuya-ir with Apache License 2.0 5 votes vote down vote up
_default: (api: API) => void