Define a function that links the device manager to several of the curated device's events.
496960
function linkToCuratedDeviceEvents() {
        self.curatedDevice.on(
            'DEVICE_DISCONNECTED',
            curatedDeviceDisconnected
        );
        self.curatedDevice.on(
            'DEVICE_RECONNECTED',
            curatedDeviceReconnected
        );
        self.curatedDevice.on(
            'DEVICE_ERROR',
            curatedDeviceError
        );
        self.curatedDevice.on(
            'DEVICE_RECONNECTING',
            curatedDeviceReconnecting
        );
        self.curatedDevice.on(
            'DEVICE_ATTRIBUTES_CHANGED',
            cureatedDeviceAttributesChanged
        );
    }
905345
def processVREvent(self, event):
        ""
        et = event.eventType
        if et == openvr.VREvent_TrackedDeviceActivated:
            self.setupRenderModelForTrackedDevice( event.trackedDeviceIndex )
            dprintf( "Device %u attached. Setting up render model.\n" % event.trackedDeviceIndex )
        elif et == openvr.VREvent_TrackedDeviceDeactivated:
            dprintf( "Device %u detached.\n" % event.trackedDeviceIndex )
        elif et == openvr.VREvent_TrackedDeviceUpdated:
            dprintf( "Device %u updated.\n" % event.trackedDeviceIndex )
310773
function innerCollectDeviceData(infoToCache) {
        var defered = q.defer();
        self.dataCollectionDefered = defered;

        self.log('Collecting Data from a handle', self.handle);
        
        // Indicate that this device was opened by the device scanner.
        self.openedByScanner = true;

        var deviceHandle = self.handle;
        var dt = self.openParameters.deviceType;
        var ct = self.openParameters.connectionType;
        var id = self.openParameters.identifier;

        // Initialize a curated device object.
        self.curatedDevice = new device_curator.device();

        // Link the device handle to the curated device object.
        self.curatedDevice.linkToHandle(deviceHandle, dt, ct, id)
        .then(function finishedLinkingHandle(res) {
            self.log(
                'Finished linking to a handle',
                deviceHandle,
                self.curatedDevice.savedAttributes.connectionTypeName
            );
            
            // Create a data collection timeout.
            var collectionTimeout = setTimeout(
                deviceHandleDataCollectionTimeout,
                DEVICE_DATA_COLLECTION_TIMEOUT
            );

            // Attach event listeners to the curated device.
            linkToCuratedDeviceEvents();
            console.log('reading multiple...', deviceHandle);
            // Collect information from the curated device.
            self.curatedDevice.iReadMultiple(infoToCache)
            .then(function finishedCollectingData(results) {
                // Clear the data collection timeout
                clearTimeout(collectionTimeout);

                self.log('Collecting data from a handle', deviceHandle);
                printCollectedDeviceData(results);
                saveCollectedDeviceData(results);

                // Report that the device is finished collecting data.
                stopCollectingDeviceData();
            }, function(err) {
                self.log('Error collecting data from a handle', deviceHandle, err);

                // Report that the device is finished collecting data.
                stopCollectingDeviceData();
            });
        }, function errorLinkingHandle(err) {
            console.error('Error linking to handle...');
            defered.resolve();
        });
        return defered.promise;
    }
65729
function bindToFunction(target, entity, evt, method){
      target.listenTo(entity, evt, method, target);
  }
360259
function(key, cb) {

  // ensure the plugin is loaded if registration succeeds
  var success = function() {
    shared.plugin_manager.force_enable('control-panel', function(err) {
      cb();
    });
  }

  // set API key and clear Device key
  shared.keys.set_api_key(key, function(err) {
    if (err) return cb(err);

    log('Linking device...');
    shared.panel.link(function(err) {
      if (!err) return success();

      // ok, we got an error. clear the API key before returning.
      // call back the original error as well.
      shared.keys.set_api_key('', function(e) {
        cb(err);
      });
    });
  })
}
221985
def _bind_device(self):
        
        patterns = set()

        self.bound_commands = []

        for cmd in self.commands:
            bound = cmd.bind(self) or cmd.bind(self.device) or None

            if bound is None:
                raise RuntimeError(
                    'Unable to produce callable object for non-existing member \'{}\' '
                    'of device or interface.'.format(cmd.func))

            for bound_cmd in bound:
                pattern = bound_cmd.matcher.pattern
                if pattern in patterns:
                    raise RuntimeError(
                        'The regular expression {} is '
                        'associated with multiple commands.'.format(pattern))

                patterns.add(pattern)

                self.bound_commands.append(bound_cmd)
166160
protected function attachSelfToEventManager()
    {
        if (!$this->listener_attached) {
            if ($this->event_manager instanceof ListenerAwareInterface &&
                $this instanceof ListenerInterface
            ) {
                $this->event_manager->attachListener($this);
            }
            $this->listener_attached = true;
        }
    }
290490
def adjust_monitor(self, handle, action, devices, events):
        

        events = list(events)
        devices = list(devices)

        for event in events:
            if event not in self.SUPPORTED_EVENTS:
                raise ArgumentError("Unknown event type {} specified".format(event), events=events)

        if action not in self.SUPPORTED_ADJUSTMENTS:
            raise ArgumentError("Unknown adjustment {} specified".format(action))

        action = (handle, action, devices, events)
        if self._currently_notifying:
            self._deferred_adjustments.append(action)
        else:
            self._adjust_monitor_internal(*action)
431822
function DeviceLoader() {
  var self = this;

  // call super class
  EventEmitter2.call(this, {
    wildcard: true,
    delimiter: ':',
    maxListeners: 1000 // default would be 10!
  });

  if (this.log) {
    this.log = _.wrap(this.log, function(func, msg) {
      func(self.constructor.name + ': ' + msg);
    });
  } else if (DeviceLoader.prototype.log) {
    DeviceLoader.prototype.log = _.wrap(DeviceLoader.prototype.log, function(func, msg) {
      func(self.constructor.name + ': ' + msg);
    });
    this.log = DeviceLoader.prototype.log;
  } else {
    var debug = require('debug')(this.constructor.name);
    this.log = function(msg) {
      debug(msg);
    };
  }

  this.lookupIntervalId = null;
  this.oldDevices = [];

  this.isRunning = false;
}
419549
function (successCallback, errorCallback, deviceId) {

			// Find the requested device in our list of discovered devices
			var device = winble.deviceManager.getDeviceFromId(deviceId, "connectToDevice", errorCallback);
			if (device == null) {
				errorCallback(winble.DEVICE_NOT_FOUND);
				return;
			}

			// Save the success callback; we will need to call this whenever the connection status changes.
			if (device.connectSuccessCallback == null)
				device.connectSuccessCallback = successCallback;

			// Call the success callback if the device is connected, error callback if not
			if (device.isReachable && device.isConnected) {
				winble.logger.logDebug("connectToDevice", "Connection successful");
				var connectInfo = {
					"deviceHandle": device.handle,
					"state": 2 // 0 = Disconnected, 1 = Connecting, 2 = Connected, 3 = Disconnecting
				};
				device.connectSuccessCallback(connectInfo, { keepCallback: true });
			} else {
				winble.logger.logDebug("connectToDevice", "Connection failed");
				errorCallback(winble.DEVICE_NOT_CONNECTED);
			}
		}
995063
def _on_connected(self, device):
        
        self._logger.debug("Device connected event: {}".format(device))

        self.connected = True
        self._connection_handle = device['connection_handle']
        self.device.connected = True
        self._audit('ClientConnected')
943778
function Device(options) {

  EventEmitter.call(this);

  // Check required fields.
  if(!options || !options.id) {
    throw new Error('ID is required.');
  }

  this.options = options;
  this.id = options.id;

  // Default the options and remove whitespace.
  options.id = (options.id || '').replace(/ /g, '');
  options.key = (options.key || '').replace(/ /g, '');
  options.secret = (options.secret || '').replace(/ /g, '');

  // The MQTT topics that this device will use.
  this.commandTopic = util.format(config.topicFormatCommand, options.id);
  this.stateTopic = util.format(config.topicFormatState, options.id);

  this.mqtt = options.mqtt || new MQTT();
  this.mqtt.on('message', this.handleMessage.bind(this));

  // Only want 'connect' to be emitted the first time. Every time after
  // will only emit the reconnected event.
  var firstConnect = true;
  this.mqtt.on('connect', (function() {
    this.handleConnect();
    if(firstConnect) {
      firstConnect = false;
      this.emit('connect');
    }
    else {
      this.emit('reconnected');
    }
  }).bind(this));

  this.mqtt.on('reconnect', (function() {
    this.emit('reconnect');
  }).bind(this));

  this.mqtt.on('close', (function() {
    this.emit('close');
  }).bind(this));

  this.mqtt.on('offline', (function() {
    this.emit('offline');
  }).bind(this));

  this.mqtt.on('error', (function(err) {
    this.emit('error', err);
  }).bind(this));
}
199405
void onStart(Device device) {
	  KernelDeviceProfile currentDeviceProfile = deviceProfiles.get(device);
      if (currentDeviceProfile == null) {    	 
         currentDeviceProfile = new KernelDeviceProfile(this, kernelClass, device);
         KernelDeviceProfile existingProfile = deviceProfiles.putIfAbsent(device, currentDeviceProfile);
         if (existingProfile != null) {
        	 currentDeviceProfile = existingProfile;
         }
      }
      
      currentDeviceProfile.onEvent(ProfilingEvent.START);
      currentDevice.set(device);
   }
681682
function(Device, filter) {
    var sub = new EventEmitter2({
      wildcard: true,
      delimiter: ':',
      maxListeners: 1000 // default would be 10!
    });
    sub.Device = Device;
    sub.filter = filter;
    sub.oldDevices = [];
    sub.newDevices = [];

    /**
     * Calls the callback with an array of devices.
     * @param  {Array}    ports    When called within this file this are the listed system ports. [optional]
     * @param  {Function} callback The function, that will be called when finished lookup.
     *                             `function(err, devices){}` devices is an array of Device objects.
     */
    sub.lookup = function(ports, callback) {
      if (!callback) {
        callback = ports;
        ports = null;
      }

      if (this.newDevices.length > 0) {
        if (callback) { callback(null, this.newDevices); }
        return;
      } else {
        var self = this;
        globalSerialDeviceLoader.lookup(function(err) {
          if (err && !err.name) {
            err = new Error(err);
          }
          if (callback) { callback(err, self.newDevices); }
        });
      }
    };

    /**
     * Calls lookup function with optional callback
     * and emits 'plug' for new attached devices
     * and 'unplug' for removed devices.
     * @param  {Function} callback The function, that will be called when finished triggering. [optional]
     *                             `function(err, devices){}` devices is an array of Device objects.
     */
    sub.trigger = function(callback) {
      var self = this;
      globalSerialDeviceLoader.trigger(function(err) {
        if (err && !err.name) {
          err = new Error(err);
        }
        if (callback) { callback(err, self.newDevices); }
      });
    };

    /**
     * Starts to lookup.
     * @param  {Number}   interval The interval milliseconds. [optional]
     * @param  {Function} callback The function, that will be called when trigger has started. [optional]
     *                             `function(err, devices){}` devices is an array of Device objects.
     */
    sub.startLookup = function(interval, callback) {
      if (!callback && _.isFunction(interval)) {
        callback = interval;
        interval = null;
      }

      subscribers.push(this);

      var self = this;
      if (isRunning) {
        if (callback) { callback(null, self.newDevices); }
        return;
      } else {
        globalSerialDeviceLoader.startLookup(interval, function(err) {
          if (err && !err.name) {
            err = new Error(err);
          }
          if (callback) { callback(err, self.newDevices); }
        });
      }
    };

    /**
     * Removes itself as subscriber.
     * If last stops the interval that calls trigger function.
     */
    sub.stopLookup = function() {
      var self = this;
      if (!isRunning) {
        return;
      } else {
        subscribers = _.reject(function(s) {
          return s === self;
        });
        if (subscribers.length === 0) {
          globalSerialDeviceLoader.stopLookup();
        }
        return;
      }
    };

    return sub;
  }
917403
function(events){
    this._delegateDOMEvents(events);
    Marionette.bindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
    Marionette.bindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
  }
140842
def _device_node(self, device):
        """"""
        label = device.ui_label
        dev_label = device.ui_device_label
        # determine available methods
        methods = [Action(method, device,
                          self._labels[method].format(label, dev_label),
                          partial(self._actions[method], device))
                   for method in self._get_device_methods(device)]
        # find the root device:
        root = device.parent_object_path
        # in this first step leave branches empty
        return device.object_path, Device(root, [], device, dev_label, methods)
469359
def _wire_events(self):
        
        self._device.on_open += self._on_open
        self._device.on_close += self._on_close
        self._device.on_read += self._on_read
        self._device.on_write += self._on_write
        self._zonetracker.on_fault += self._on_zone_fault
        self._zonetracker.on_restore += self._on_zone_restore