homebridge#Service TypeScript Examples

The following examples show how to use homebridge#Service. 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: util.ts    From homebridge-wiz-lan with Apache License 2.0 7 votes vote down vote up
export function turnOffIfNeeded(
  characteristic: WithUUID<{
    new (): Characteristic;
  }>,
  service: Service,
  useSetValue = false
) {
  const ch = service.getCharacteristic(characteristic);
  if (ch?.value !== 0) {
    useSetValue ? ch.setValue(0) : ch.updateValue(0);
  }
}
Example #2
Source File: accessory.ts    From homebridge-vieramatic with Apache License 2.0 6 votes vote down vote up
async updateTVstatus(nextState: CharacteristicValue): Promise<void> {
    const tvService = this.accessory.getService(this.Service.Television)
    const speakerService = this.accessory.getService(this.Service.TelevisionSpeaker)
    const customSpeakerService = this.accessory.getService(this.Service.Fan)

    if (!tvService || !speakerService) return

    speakerService.updateCharacteristic(this.Characteristic.Active, nextState)
    tvService.updateCharacteristic(this.Characteristic.Active, nextState)

    if (nextState === true) {
      const [cmd, volume] = [await this.device.getMute(), await this.getVolume()]
      const muted = Ok(cmd) ? cmd.value : true

      speakerService
        .updateCharacteristic(this.Characteristic.Mute, muted)
        .updateCharacteristic(this.Characteristic.Volume, volume)

      if (customSpeakerService)
        customSpeakerService
          .updateCharacteristic(this.Characteristic.On, !muted)
          .updateCharacteristic(this.Characteristic.RotationSpeed, volume)
    } else if (customSpeakerService)
      customSpeakerService.updateCharacteristic(this.Characteristic.On, nextState)
  }
Example #3
Source File: temperatureAccessory.ts    From homebridge-screenlogic with MIT License 6 votes vote down vote up
constructor(
    private readonly platform: ScreenLogicPlatform,
    private readonly accessory: PlatformAccessory,
  ) {
    // set accessory information
    const accessoryInfo = platform.accessoryInfo()
    this.accessory
      .getService(this.platform.Service.AccessoryInformation)!
      .setCharacteristic(this.platform.Characteristic.Manufacturer, accessoryInfo.manufacturer)
      .setCharacteristic(this.platform.Characteristic.Model, accessoryInfo.model)
      .setCharacteristic(this.platform.Characteristic.SerialNumber, accessoryInfo.serialNumber)

    // get the TemperatureSensor service if it exists, otherwise create a new TemperatureSensor service
    this.service =
      this.accessory.getService(this.platform.Service.TemperatureSensor) ||
      this.accessory.addService(this.platform.Service.TemperatureSensor)

    // set the service name, this is what is displayed as the default name on the Home app
    this.service.setCharacteristic(this.platform.Characteristic.Name, this.context.displayName)

    this.service.getCharacteristic(this.platform.Characteristic.CurrentTemperature).setProps({
      format: Formats.FLOAT,
      minValue: -40,
      maxValue: 60,
    })

    // trigger refresh if needed when HomeKit asks for this value
    this.platform.triggersRefreshIfNeded(
      this.service,
      this.platform.Characteristic.CurrentTemperature,
    )
  }
Example #4
Source File: SmartLockAccessory.ts    From homebridge-eufy-security with Apache License 2.0 6 votes vote down vote up
constructor(
    platform: EufySecurityPlatform,
    accessory: PlatformAccessory,
    eufyDevice: Lock,
  ) {
    super(platform, accessory, eufyDevice);

    this.platform.log.debug(this.accessory.displayName, 'Constructed SmartLock');

    this.SmartLock = eufyDevice;

    this.service =
      this.accessory.getService(this.platform.Service.LockMechanism) ||
      this.accessory.addService(this.platform.Service.LockMechanism);

    this.service.setCharacteristic(
      this.platform.Characteristic.Name,
      accessory.displayName,
    );

    // create handlers for required characteristics
    this.service
      .getCharacteristic(this.platform.Characteristic.LockCurrentState)
      .onGet(this.handleLockCurrentStateGet.bind(this));

    this.service
      .getCharacteristic(this.platform.Characteristic.LockTargetState)
      .onGet(this.handleLockTargetStateGet.bind(this))
      .onSet(this.handleLockTargetStateSet.bind(this));

    this.SmartLock.on('locked', (device: Device, lock: boolean) =>
      this.onDeviceLockPushNotification(device, lock),
    );
    
  }
Example #5
Source File: GenericAccessory.ts    From homebridge-tuya-ir with Apache License 2.0 6 votes vote down vote up
constructor(
        private readonly platform: TuyaIRPlatform,
        private readonly accessory: PlatformAccessory,
    ) {
        this.parentId = accessory.context.device.ir_id;
        this.tuya = TuyaAPIHelper.Instance(new Config(platform.config.client_id, platform.config.secret, platform.config.region, platform.config.deviceId, platform.config.devices), platform.log);
        // set accessory information
        this.accessory.getService(this.platform.Service.AccessoryInformation)!
            .setCharacteristic(this.platform.Characteristic.Manufacturer, accessory.context.device.product_name)
            .setCharacteristic(this.platform.Characteristic.Model, 'Infrared Controlled Switch')
            .setCharacteristic(this.platform.Characteristic.SerialNumber, accessory.context.device.id);

        // get the LightBulb service if it exists, otherwise create a new LightBulb service
        // you can create multiple services for each accessory
        this.service = this.accessory.getService(this.platform.Service.Switch) || this.accessory.addService(this.platform.Service.Switch);

        // set the service name, this is what is displayed as the default name on the Home app
        // in this example we are using the name we stored in the `accessory.context` in the `discoverDevices` method.
        this.service.setCharacteristic(this.platform.Characteristic.Name, accessory.context.device.name);

        // each service must implement at-minimum the "required characteristics" for the given service type
        // see https://developers.homebridge.io/#/service/Lightbulb

        // register handlers for the On/Off Characteristic
        this.service.getCharacteristic(this.platform.Characteristic.On)
            .onSet(this.setOn.bind(this))                // SET - bind to the `setOn` method below
            .onGet(this.getOn.bind(this));               // GET - bind to the `getOn` method below
    }
Example #6
Source File: sensor-service-builder.ts    From homebridge-zigbee-nt with Apache License 2.0 6 votes vote down vote up
constructor(
    service: WithUUID<typeof Service>,
    platform: ZigbeeNTHomebridgePlatform,
    accessory: PlatformAccessory,
    client: ZigBeeClient,
    state: DeviceState
  ) {
    super(platform, accessory, client, state);
    this.service = this.accessory.getService(service) || this.accessory.addService(service);
  }
Example #7
Source File: wiz.ts    From homebridge-wiz-lan with Apache License 2.0 6 votes vote down vote up
initAccessory(platformAccessory: PlatformAccessory) {

    // Already initialized!!
    if (this.initializedAccessories.has(platformAccessory.UUID)) {
      return;
    }

    const device = platformAccessory.context as Device;

    // Skip if it doesn't have the new context schema
    if (typeof device?.model !== "string") {
      return;
    }

    platformAccessory
      .getService(this.Service.AccessoryInformation)!!
      .setCharacteristic(this.Characteristic.Manufacturer, "Wiz")
      .setCharacteristic(this.Characteristic.Model, device.model)
      .setCharacteristic(this.Characteristic.SerialNumber, device.mac);

    const accessory = Accessories.find(accessory => accessory.is(device));

    if (typeof accessory === 'undefined') {
      this.log.warn(`Unknown device ${device.toString()}, skipping...`);
      return;
    } 

    accessory.init(platformAccessory, device, this);

    this.initializedAccessories.add(platformAccessory.UUID);
  }
Example #8
Source File: wled-accessory.ts    From homebridge-simple-wled with ISC License 6 votes vote down vote up
addEffectsInputSources(effects: any): void {

    if (this.prodLogging) {
      this.log("Adding effects: " + effects);
    }

    effects.forEach((effectName: string, i: number) => {
      let effectID = this.getEffectIdByName(effectName);
      this.effects.push(effectID);
      const effectInputSource = this.wledAccessory.addService(this.hap.Service.InputSource, effectID, effectName);
      effectInputSource
        .setCharacteristic(this.Characteristic.Identifier, i)
        .setCharacteristic(this.Characteristic.ConfiguredName, effectName)
        .setCharacteristic(this.Characteristic.IsConfigured, this.Characteristic.IsConfigured.CONFIGURED)
        .setCharacteristic(this.Characteristic.InputSourceType, this.Characteristic.InputSourceType.HDMI);
      this.effectsService.addLinkedService(effectInputSource);
    });

  }
Example #9
Source File: RoomManager.ts    From homebridge-iRobot with Apache License 2.0 6 votes vote down vote up
constructor(
    accessory: PlatformAccessory,
    platform: iRobotPlatform,
    roomba: RoombaV3,
    private readonly service: Service,
  ) {
    super(accessory, platform, roomba);
    /*for (const map of accessory.context.maps) {
      const index = accessory.context.maps.indexOf(map);
      for (const region of map.regions) {
        const service = accessory.getService(this.GetName(region, index)) ||
          accessory.addService(platform.Service.Switch, this.GetName(region, index), this.GetName(region, index));

      }
    }*/
  }
Example #10
Source File: tasmotaFanService.ts    From homebridge-tasmota with Apache License 2.0 6 votes vote down vote up
constructor(
    public readonly platform: tasmotaPlatform,
    public readonly accessory: PlatformAccessory,
    protected readonly uniq_id: string,
  ) {

    super(platform, accessory, uniq_id);

    this.service = this.accessory.getService(this.uuid) || this.accessory.addService(this.platform.Service.Fan,
      accessory.context.device[this.uniq_id].name, this.uuid);

    if (!this.service.displayName) {
      this.service.setCharacteristic(this.platform.Characteristic.Name, accessory.context.device[this.uniq_id].name);
    }

    if (this.service.getCharacteristic(this.platform.Characteristic.On).listenerCount('set') < 1) {
      this.characteristic = this.service.getCharacteristic(this.platform.Characteristic.On)
        .on('set', this.setOn.bind(this));
      this.enableStatus();
    }

    // Does the Fan include a RotationSpeed characteristic

    if (accessory.context.device[this.uniq_id].bri_cmd_t) {
      (this.service.getCharacteristic(this.platform.Characteristic.RotationSpeed) ||
        this.service.addCharacteristic(this.platform.Characteristic.RotationSpeed))
        .on('set', this.setRotationSpeed.bind(this));
    } else if (accessory.context.device[this.uniq_id].spds) {
      (this.service.getCharacteristic(this.platform.Characteristic.RotationSpeed) ||
        this.service.addCharacteristic(this.platform.Characteristic.RotationSpeed))
        .on('set', this.setRotationSpeedFixed.bind(this));
      //        .setProps({     // This causes an issue with validateUserInput in Characteristic and 33.3333 becomes 0
      //          minStep: 33.33333333333333,
      //        });
    }

  }
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: accessory.ts    From homebridge-fordpass with GNU General Public License v3.0 6 votes vote down vote up
createService(serviceType: ServiceType, name?: string): Service {
    const existingService = name
      ? this.accessory.getServiceById(serviceType, `${this.accessory.displayName} ${name}`)
      : this.accessory.getService(serviceType);

    const service =
      existingService ||
      (name
        ? this.accessory.addService(
            serviceType,
            `${this.accessory.displayName} ${name}`,
            `${this.accessory.displayName} ${name}`,
          )
        : this.accessory.addService(serviceType, this.accessory.displayName));
    return service;
  }
Example #13
Source File: accessory.ts    From homebridge-nest-cam with GNU General Public License v3.0 6 votes vote down vote up
createService(serviceType: ServiceType, name?: string): Service {
    const existingService = name
      ? this.accessory.getServiceById(serviceType, `${this.accessory.displayName} ${name}`)
      : this.accessory.getService(serviceType);

    const service =
      existingService ||
      (name
        ? this.accessory.addService(
            serviceType,
            `${this.accessory.displayName} ${name}`,
            `${this.accessory.displayName} ${name}`,
          )
        : this.accessory.addService(serviceType, this.accessory.displayName));
    return service;
  }
Example #14
Source File: TasmotaService.ts    From homebridge-tasmota with Apache License 2.0 6 votes vote down vote up
constructor(
    public readonly platform: tasmotaPlatform,
    public readonly accessory: PlatformAccessory,
    protected readonly uniq_id: string,
  ) {
    /* eslint-disable */
    this.CustomCharacteristic = require('./lib/CustomCharacteristics')(platform.Service, platform.Characteristic);
    this.uuid = this.platform.api.hap.uuid.generate(this.accessory.context.device[this.uniq_id].uniq_id);
    this.device_class = accessory.context.device[this.uniq_id].dev_cla;

    this.nunjucksEnvironment = new nunjucks.Environment();

    // Home Assistant device template filters

    this.nunjucksEnvironment.addFilter('is_defined', function(val, cb) {
      // console.log('is_defined', val, cb);
      if (val || val === 0) {
        cb(null, val);
      } else {
        cb(new Error('missing key'), val);
      }
    }, true);

    this.nunjucksEnvironment.addGlobal('float', float);

    nunjucks.installJinjaCompat();
    nunjucks.configure({
      autoescape: true,
    });

  }
Example #15
Source File: accessory.ts    From homebridge-nest-cam with GNU General Public License v3.0 6 votes vote down vote up
private setDoorbell(): void {
    const doorbellService = this.accessory.getServiceById(
      this.hap.Service.Doorbell,
      `${this.accessory.displayName} Doorbell`,
    );
    if (doorbellService) {
      this.log.debug(`Ringing ${this.accessory.displayName} Doorbell`);
      doorbellService.updateCharacteristic(
        this.hap.Characteristic.ProgrammableSwitchEvent,
        this.hap.Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS,
      );
    }

    const switchService = this.accessory.getService(this.hap.Service.StatelessProgrammableSwitch);
    if (switchService) {
      switchService.updateCharacteristic(
        this.hap.Characteristic.ProgrammableSwitchEvent,
        this.hap.Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS,
      );
    }
  }
Example #16
Source File: platformAccessory.ts    From HomebridgeMagicHome-DynamicPlatform with Apache License 2.0 5 votes vote down vote up
protected service: Service;
Example #17
Source File: tuya-onoff-double-switch.ts    From homebridge-zigbee-nt with Apache License 2.0 5 votes vote down vote up
getAvailableServices(): Service[] {
    const Characteristic = this.platform.api.hap.Characteristic;

    this.switchServiceButtonLeft =
      this.accessory.getServiceById(
        this.platform.Service.StatefulProgrammableSwitch,
        'button_left'
      ) ||
      this.accessory.addService(
        this.platform.Service.StatefulProgrammableSwitch,
        'Left Button',
        'button_left'
      );

    this.switchServiceButtonRight =
      this.accessory.getServiceById(
        this.platform.Service.StatefulProgrammableSwitch,
        'button_right'
      ) ||
      this.accessory.addService(
        this.platform.Service.StatefulProgrammableSwitch,
        'Right Button',
        'button_right'
      );

    this.switchServiceButtonLeft.setCharacteristic(
      this.platform.Characteristic.Name,
      'Button Left'
    );
    this.switchServiceButtonLeft.setCharacteristic(
      this.platform.Characteristic.ServiceLabelIndex,
      1
    );
    this.switchServiceButtonLeft
      .getCharacteristic(Characteristic.ProgrammableSwitchOutputState)
      .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => {
        callback(null, this.state.state_left === 'ON' ? 1 : 0);
      })
      .on(
        CharacteristicEventTypes.SET,
        async (outputState: number, callback: CharacteristicSetCallback) => {
          try {
            await this.client.setLeftButtonOn(this.zigBeeDeviceDescriptor, outputState === 1);
            callback(null, outputState);
          } catch (e) {
            callback(e);
          }
        }
      );

    this.switchServiceButtonRight.setCharacteristic(
      this.platform.Characteristic.Name,
      'Button Right'
    );
    this.switchServiceButtonRight.setCharacteristic(
      this.platform.Characteristic.ServiceLabelIndex,
      2
    );
    this.switchServiceButtonLeft
      .getCharacteristic(Characteristic.ProgrammableSwitchOutputState)
      .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => {
        callback(null, this.state.state_right === 'ON' ? 1 : 0);
      })
      .on(
        CharacteristicEventTypes.SET,
        async (outputState: number, callback: CharacteristicSetCallback) => {
          try {
            await this.client.setRightButtonOn(this.zigBeeDeviceDescriptor, outputState === 1);
            callback(null, outputState);
          } catch (e) {
            callback(e);
          }
        }
      );

    return [this.switchServiceButtonLeft, this.switchServiceButtonRight];
  }
Example #18
Source File: platformAccessory.ts    From homebridge-plugin-govee with Apache License 2.0 5 votes vote down vote up
private temperatureSensor: Service;
Example #19
Source File: tuya-onoff-double-switch.ts    From homebridge-zigbee-nt with Apache License 2.0 5 votes vote down vote up
protected switchServiceButtonLeft: Service;
Example #20
Source File: platform.ts    From homebridge-tasmota with Apache License 2.0 5 votes vote down vote up
public readonly Service: typeof Service = this.api.hap.Service;
Example #21
Source File: xiaomi-motion-sensor.ts    From homebridge-zigbee-nt with Apache License 2.0 5 votes vote down vote up
private sensorService: Service;
Example #22
Source File: platform.ts    From homebridge-tasmota with Apache License 2.0 5 votes vote down vote up
constructor(
    public readonly log: Logger,
    public readonly config: any,
    public readonly api: API,
  ) {
    this.log.debug('Finished initializing platform:', this.config.name);

    this.cleanup = this.config['cleanup'] || 24; // Default removal of defunct devices after 24 hours
    this.debug = this.config['debug'] || false;
    this.teleperiod = this.config['teleperiod'] || 300;

    if (this.debug) {

      let namespaces = debugEnable.disable();

      // this.log("DEBUG-1", namespaces);
      if (namespaces) {
        namespaces = namespaces + ',Tasmota*';
      } else {
        namespaces = 'Tasmota*';
      }
      // this.log("DEBUG-2", namespaces);
      debugEnable.enable(namespaces);
    }

    if (this.config.override) {
      interface Injection { key: string, value: any }
      interface Injections { topic: string, injection: Injection[] }
      const injections: Injections[] = [];
      Object.keys(this.config.override).forEach((topic) => {
        const inject: Injection[] = [];
        Object.entries(this.config.override[topic]).forEach(
          ([key, value]) => {
            // debug("topic: %s, key: %s, value: %s", topic, key, value);
            const injection: Injection = { key: key, value: value };
            inject.push(injection);
          },
        );
        injections.push({ topic: topic, injection: inject });
      });
      debug('This is your override reformated to injections.');
      debug('"injections": %s\n', JSON.stringify(injections, null, 2));
    }

    /* eslint-disable */
    this.CustomCharacteristic = require('./lib/CustomCharacteristics')(this.Service, this.Characteristic);

    // 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
      debug('%d accessories for cleanup', this.defunctAccessories.length);
      if (this.defunctAccessories.length > 0) {
        this.cleanupDefunctAccessories();
      }
      this.discoverDevices();

      if (this.config.history) {

        this.FakeGatoHistoryService = fakegato(this.api);

        // Only addEntries that match the expected profile of the function.

        this.FakeGatoHistoryService.prototype.appendData = function(entry) {
          entry.time = Math.round(new Date().valueOf() / 1000);
          switch (this.accessoryType) {
            default:
              // debug('unhandled this.accessoryType', this.accessoryType);
              this.addEntry(entry);
          }
        };
      }
    });
  }
Example #23
Source File: xiaomi-wireless-switch.ts    From homebridge-zigbee-nt with Apache License 2.0 5 votes vote down vote up
protected switchService: Service;
Example #24
Source File: TasmotaService.ts    From homebridge-tasmota with Apache License 2.0 5 votes vote down vote up
public service: Service;
Example #25
Source File: zig-bee-accessory.ts    From homebridge-zigbee-nt with Apache License 2.0 5 votes vote down vote up
private mappedServices: Service[];
Example #26
Source File: EntrySensorAccessory.ts    From homebridge-eufy-security with Apache License 2.0 5 votes vote down vote up
constructor(
    platform: EufySecurityPlatform,
    accessory: PlatformAccessory,
    eufyDevice: EntrySensor,
  ) {
    super(platform, accessory, eufyDevice);

    this.platform.log.debug(this.accessory.displayName, 'Constructed Entry Sensor');

    this.EntrySensor = eufyDevice;

    this.service =
      this.accessory.getService(this.platform.Service.ContactSensor) ||
      this.accessory.addService(this.platform.Service.ContactSensor);

    this.service.setCharacteristic(
      this.platform.Characteristic.Name,
      this.accessory.displayName,
    );

    try {
      if (this.eufyDevice.hasProperty('sensorOpen')) {
        this.platform.log.debug(this.accessory.displayName, 'has a sensorOpen, so append ContactSensorState characteristic to him.');

        // create handlers for required characteristics
        this.service
          .getCharacteristic(this.platform.Characteristic.ContactSensorState)
          .onGet(this.handleContactSensorStateGet.bind(this));

        this.EntrySensor.on('open', (device: Device, open: boolean) =>
          this.onDeviceOpenPushNotification(device, open),
        );

      } else {
        this.platform.log.warn(this.accessory.displayName, 'has no sensorOpen');
      }
    } catch (Error) {
      this.platform.log.error(this.accessory.displayName, 'raise error to check and attach a sensorOpen.', Error);
    }
  }
Example #27
Source File: thermostatAccessory.ts    From homebridge-screenlogic with MIT License 5 votes vote down vote up
private service: Service
Example #28
Source File: accessory.ts    From homebridge-vieramatic with Apache License 2.0 5 votes vote down vote up
private configureInputSource(type: InputType, configuredName: string, identifier: number): void {
    const fn = (element: HdmiInput): boolean => element.id === identifier.toString()

    const visibility = (): string => {
      let idx: number
      let hidden: number
      const { inputs } = this.storage.data

      switch (type) {
        case 'HDMI':
          idx = inputs.hdmi.findIndex((x: HdmiInput) => fn(x))
          // by default all hdmiInputs will be visible
          hidden = inputs.hdmi[idx].hidden ?? 0
          break
        case 'APPLICATION':
          idx = identifier - 1000
          // by default all apps will be hidden
          hidden = inputs.applications[idx].hidden ?? 1
          break
        // case 'TUNER':
        default:
          // by default TUNER is visible
          hidden = inputs.TUNER.hidden ?? 0
      }
      return hidden.toFixed(0)
    }

    const source = this.accessory.addService(
      this.Service.InputSource,
      configuredName.toLowerCase().replace(/\s/gu, ''),
      identifier
    )
    const visibilityState = (state: CharacteristicValue): void => {
      let idx: number
      const id = source.getCharacteristic(this.Characteristic.Identifier).value ?? 500
      const { inputs } = this.storage.data

      switch (true) {
        case id < 100:
          // hdmi input
          idx = inputs.hdmi.findIndex((x: HdmiInput) => fn(x))
          inputs.hdmi[idx].hidden = state as InputVisibility
          break
        case id > 999:
          // APP
          idx = (id as number) - 1000
          inputs.applications[idx].hidden = state as InputVisibility
          break
        // case id === 500:
        default:
          inputs.TUNER.hidden = state as InputVisibility
          break
      }
      source.updateCharacteristic(this.Characteristic.CurrentVisibilityState, state)
    }
    const hidden = visibility()

    source
      .setCharacteristic(
        this.Characteristic.InputSourceType,
        this.Characteristic.InputSourceType[type]
      )
      .setCharacteristic(this.Characteristic.CurrentVisibilityState, hidden)
      .setCharacteristic(this.Characteristic.TargetVisibilityState, hidden)
      .setCharacteristic(this.Characteristic.Identifier, identifier)
      .setCharacteristic(this.Characteristic.ConfiguredName, configuredName)
      .setCharacteristic(
        this.Characteristic.IsConfigured,
        this.Characteristic.IsConfigured.CONFIGURED
      )
    source.getCharacteristic(this.Characteristic.TargetVisibilityState).onSet(visibilityState)

    const svc = this.accessory.getService(this.Service.Television)
    if (svc) svc.addLinkedService(source)
  }
Example #29
Source File: setColorAccessory.ts    From homebridge-screenlogic with MIT License 5 votes vote down vote up
constructor(
    private readonly platform: ScreenLogicPlatform,
    private readonly accessory: PlatformAccessory,
  ) {
    // set accessory information
    const accessoryInfo = platform.accessoryInfo()
    this.accessory
      .getService(this.platform.Service.AccessoryInformation)!
      .setCharacteristic(this.platform.Characteristic.Manufacturer, accessoryInfo.manufacturer)
      .setCharacteristic(this.platform.Characteristic.Model, accessoryInfo.model)
      .setCharacteristic(this.platform.Characteristic.SerialNumber, accessoryInfo.serialNumber)

    for (const colorConfig of setColorConfig) {
      if (!platform.config.disabledLightColors.includes(colorConfig.name)) {
        this.platform.log.info('adding enabled light color:', colorConfig.name)

        // To avoid "Cannot add a Service with the same UUID another Service without also defining a unique 'subtype' property." error,
        // when creating multiple services of the same type, you need to use the following syntax to specify a name and subtype id:
        // this.accessory.getService('NAME') ?? this.accessory.addService(this.platform.Service.Lightbulb, 'NAME', 'USER_DEFINED_SUBTYPE');
        const service =
          this.accessory.getService(colorConfig.name) ??
          this.accessory.addService(
            this.platform.Service.Switch,
            colorConfig.name,
            colorConfig.name,
          )

        // set the service name, this is what is displayed as the default name on the Home app
        service.setCharacteristic(this.platform.Characteristic.Name, colorConfig.name)

        // register handlers for the On Characteristic
        service
          .getCharacteristic(this.platform.Characteristic.On)
          .on('set', (value: CharacteristicValue, callback: CharacteristicSetCallback) => {
            this.setOn(service, value, callback, colorConfig)
          })
      }
    }

    const servicesToRemove = this.accessory.services.filter(service => {
      if (service.UUID === this.platform.Service.Switch.UUID) {
        return platform.config.disabledLightColors.includes(service.displayName)
      } else {
        return false
      }
    })
    for (const service of servicesToRemove) {
      this.platform.log.info('removing disabled light color:', service.displayName)
      this.accessory.removeService(service)
    }
  }