How to use hap-nodejs - 10 common examples

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

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

github Capevace / halbert / system / home-kit.js View on Github external
function homeKitSetup(moduleRegistry) {
  init();

  const bridge = new Bridge('H.A.L.B.E.R.T.', config.device.uuid);

  // Identification Event
  bridge.on('identify', (paired, callback) => {
    console.logger.info('HomeKit paired:', paired);
    callback();
  });

  const modules = moduleRegistry.getRegisteredModules();
  Object.keys(modules).forEach(moduleKey => {
    if (!modules[moduleKey].accessories) return;

    modules[
      moduleKey
    ].accessories.forEach(accessory => bridge.addBridgedAccessory(accessory));
github Capevace / halbert / system / home-kit.js View on Github external
function homeKitSetup(moduleRegistry) {
  init();

  const bridge = new Bridge('H.A.L.B.E.R.T.', config.device.uuid);

  // Identification Event
  bridge.on('identify', (paired, callback) => {
    console.logger.info('HomeKit paired:', paired);
    callback();
  });

  const modules = moduleRegistry.getRegisteredModules();
  Object.keys(modules).forEach(moduleKey => {
    if (!modules[moduleKey].accessories) return;

    modules[
      moduleKey
    ].accessories.forEach(accessory => bridge.addBridgedAccessory(accessory));
  });
github nfarina / homebridge / lib / cli.js View on Github external
var shuttingDown = false;

  program
    .version(version)
    .option('-C, --color', 'force color in logging', function() { require('./logger').forceColor(); })
    .option('-D, --debug', 'turn on debug level logging', function() { require('./logger').setDebugEnabled(true); })
    .option('-I, --insecure', 'allow unauthenticated requests (for easier hacking)', function() { insecureAccess = true; })
    .option('-P, --plugin-path [path]', 'look for plugins installed at [path] as well as the default locations ([path] can also point to a single plugin)', function(p) { Plugin.addPluginPath(p); })
    .option('-Q, --no-qrcode', 'do not issue QRcode in logging', function() { hideQRCode = true; })
    .option('-R, --remove-orphans', 'remove cached accessories for which plugin is not loaded', function() { cleanCachedAccessories = true; })
    .option('-T, --no-timestamp', 'do not issue timestamps in logging', function() { require('./logger').setTimestampEnabled(false); })
    .option('-U, --user-storage-path [path]', 'look for homebridge user files at [path] instead of the default location (~/.homebridge)', function(p) { User.setStoragePath(p); })
    .parse(process.argv);

  // Initialize HAP-NodeJS with a custom persist directory
  hap.init(User.persistPath());

  var server = new Server({cleanCachedAccessories:cleanCachedAccessories, insecureAccess:insecureAccess, hideQRCode:hideQRCode});

  var signals = { 'SIGINT': 2, 'SIGTERM': 15 };
  Object.keys(signals).forEach(function (signal) {
    process.on(signal, function () {
      if (shuttingDown) {
        return
      }
      shuttingDown = true;

      log.info("Got %s, shutting down Homebridge...", signal);

      server._teardown();
      setTimeout(function (){
        process.exit(128 + signals[signal]);
github agrippa1994 / FS20 / main.js View on Github external
if (error) {
      logger.error("Failed to connect to the serial interface, " + error);
      process.exit(0);
    }

    logger.info("Connection to the serial interface has been established");
  },
  function (error) {
    logger.error("Serial connection disconnected");
    process.exit(0);
  }
);

//--------------------------------------------------------------------------------------
// Initialize HAP
hap.init(path.join(__dirname, "hap-db"));

// Read all devices
var devices = hap.AccessoryLoader.loadDirectory(path.join(__dirname, "devices"));
var targetPort = 51826;

// Iterate through all devices
devices.forEach(device => {
  device.stateChange = (value, callback) => {
    logger.info(`Changing state of device ${device.username} to ${value} ...`);
    fs20.setDeviceState(device.code, value, (error, received) => {
      if (error)
        logger.error(`Can't change state of device ${device.username} to ${value}, ${error}`);
      else
        logger.info(`Changed state of device ${device.username} to ${value}, code: ${received.code}, text: ${received.text}`);

      if (error)
github nfarina / homebridge / lib / server.js View on Github external
// The returned "services" for this accessory is assumed to be the old style: a big array
    // of JSON-style objects that will need to be parsed by HAP-NodeJS's AccessoryLoader.

    // Create the actual HAP-NodeJS "Accessory" instance
    return AccessoryLoader.parseAccessoryJSON({
      displayName: displayName,
      services: services
    });
  }
  else {
    // The returned "services" for this accessory are simply an array of new-API-style
    // Service instances which we can add to a created HAP-NodeJS Accessory directly.

    var accessoryUUID = uuid.generate(accessoryType + ":" + (uuid_base || displayName));

    var accessory = new Accessory(displayName, accessoryUUID);

    // listen for the identify event if the accessory instance has defined an identify() method
    if (accessoryInstance.identify)
      accessory.on('identify', function(paired, callback) { accessoryInstance.identify(callback); });

    services.forEach(function(service) {

      // if you returned an AccessoryInformation service, merge its values with ours
      if (service instanceof Service.AccessoryInformation) {
        var existingService = accessory.getService(Service.AccessoryInformation);

        // pull out any values you may have defined
        var manufacturer = service.getCharacteristic(Characteristic.Manufacturer).value;
        var model = service.getCharacteristic(Characteristic.Model).value;
        var serialNumber = service.getCharacteristic(Characteristic.SerialNumber).value;
        var firmwareRevision = service.getCharacteristic(Characteristic.FirmwareRevision).value;
github nfarina / homebridge / lib / server.js View on Github external
if (!(services[0] instanceof Service)) {
    // The returned "services" for this accessory is assumed to be the old style: a big array
    // of JSON-style objects that will need to be parsed by HAP-NodeJS's AccessoryLoader.

    // Create the actual HAP-NodeJS "Accessory" instance
    return AccessoryLoader.parseAccessoryJSON({
      displayName: displayName,
      services: services
    });
  }
  else {
    // The returned "services" for this accessory are simply an array of new-API-style
    // Service instances which we can add to a created HAP-NodeJS Accessory directly.

    var accessoryUUID = uuid.generate(accessoryType + ":" + (uuid_base || displayName));

    var accessory = new Accessory(displayName, accessoryUUID);

    // listen for the identify event if the accessory instance has defined an identify() method
    if (accessoryInstance.identify)
      accessory.on('identify', function(paired, callback) { accessoryInstance.identify(callback); });

    services.forEach(function(service) {

      // if you returned an AccessoryInformation service, merge its values with ours
      if (service instanceof Service.AccessoryInformation) {
        var existingService = accessory.getService(Service.AccessoryInformation);

        // pull out any values you may have defined
        var manufacturer = service.getCharacteristic(Characteristic.Manufacturer).value;
        var model = service.getCharacteristic(Characteristic.Model).value;
github htreu / OpenHAB-HomeKit-Bridge / lib / openHABBridge.js View on Github external
function publishOpenHABBridgeAccessory(bridgeName, openHABWidgets) {
  let accessoryProvider = new AccessoryProvider();
  let homeKitAccessories = accessoryProvider.createHomeKitAccessories(openHABWidgets);
  let openHabBridge = new Bridge(bridgeName, uuid.generate(bridgeName));

  homeKitAccessories.forEach(function(accessory) {
    openHabBridge.addBridgedAccessory(accessory);
  });

  // Publish the Bridge on the local network.
  openHabBridge.publish({
    username: generateUniqueUsername(bridgeName),
    port: parseInt(targetPort),
    pincode: pincode,
    category: Accessory.Categories.OTHER
  });
};
github nfarina / homebridge / lib / bridgeSetupSession.js View on Github external
function BridgeSetupSession(stateChar, controlChar) {
  this.validSession = false
  this.sessionUUID = uuid.generate(crypto.randomBytes(32));
  this.stateChar = stateChar;
  this.controlChar = controlChar;

  this.transactionID = 0;
  this.preferedLanguage = "en-US";

  this.lastResponse = null;

  // 0 - Waiting for negotiate
  // 1 - Waiting for selection
  // 2 - List platforms, waiting selection to give session to plugin
  // 3 - Forward message to platform
  // 4 - Manage accessory config, waiting selection
  this.currentStage = 0;

  this.currentPluginName;
github nfarina / homebridge / accessories / Http.js View on Github external
getServices: function() {

    // you can OPTIONALLY create an information service if you wish to override
    // the default values for things like serial number, model, etc.
    var informationService = new Service.AccessoryInformation();
    
    informationService
      .setCharacteristic(Characteristic.Manufacturer, "HTTP Manufacturer")
      .setCharacteristic(Characteristic.Model, "HTTP Model")
      .setCharacteristic(Characteristic.SerialNumber, "HTTP Serial Number");
    
    var lightbulbService = new Service.Lightbulb();
    
    lightbulbService
      .getCharacteristic(Characteristic.On)
      .on('set', this.setPowerState.bind(this));
    
    lightbulbService
      .addCharacteristic(new Characteristic.Brightness())
      .on('set', this.setBrightness.bind(this));
    
    return [informationService, lightbulbService];
  }
};
github htreu / OpenHAB-HomeKit-Bridge / lib / Colorpicker.js View on Github external
if (finished === 4) {
          this.updatingFromOpenHAB = false;
        }
      }.bind(this)
    );
    // set saturation
    this.getCharacteristic(Characteristic.Saturation).setValue(saturation,
      function() { // callback to signal us iOS did process the update
        finished++;
        if (finished === 4) {
          this.updatingFromOpenHAB = false;
        }
      }.bind(this)
    );
    // update ON/OFF state
    this.getCharacteristic(Characteristic.On).setValue(power,
      function() { // callback to signal us iOS did process the update
        finished++;
        if (finished === 4) {
          this.updatingFromOpenHAB = false;
        }
      }.bind(this)
    );
	};