Handles attached events from USBDevice.start_detection().
483212
def handle_attached(sender, device):
    
    # Create the device from the specified device arguments.
    dev = create_device(device)
    __devices[dev.id] = dev

    print('attached', dev.id)
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);
   }
228211
def _do_stale_devices_callback(self, msg):
        """"""
        for callback in self._stale_devices_callbacks:
            _LOGGER.debug('Stale Devices callback %s', callback)
            self._event_loop.call_soon(callback, msg)
312389
function () {
			BaseController.prototype.onInit.call(this);

			// manually call the handler once at startup as device API won't do this for us
			this._onOrientationChange({
				landscape: Device.orientation.landscape
			});

			this.getRouter().getRoute("tools").attachPatternMatched(this._onMatched, this);
		}
323606
function unlinkFromCuratedDeviceEvents() {
        self.curatedDevice.removeListener(
            'DEVICE_DISCONNECTED',
            curatedDeviceDisconnected
        );
        self.curatedDevice.removeListener(
            'DEVICE_RECONNECTED',
            curatedDeviceReconnected
        );
        self.curatedDevice.removeListener(
            'DEVICE_ERROR',
            curatedDeviceError
        );
        self.curatedDevice.removeListener(
            'DEVICE_RECONNECTING',
            curatedDeviceReconnecting
        );
        self.curatedDevice.removeListener(
            'DEVICE_ATTRIBUTES_CHANGED',
            cureatedDeviceAttributesChanged
        );
    }
278518
def process_events(self):
        """"""
        for event, args in iter_except(self.event_queue.popleft, IndexError):
            for callback in self.event_callbacks[event]:
                callback(*args)
1139639
def trigger_events(events, loop):
    
    for event in events:
        result = event(loop)
        if isawaitable(result):
            loop.run_until_complete(result)
571501
async def start(self):
        """"""
        if self.connection.connected:
            return

        await self.connection.connect()

        # In case credentials have been given externally (i.e. not by pairing
        # with a device), then use that client id
        if self.service.device_credentials:
            self.srp.pairing_id = Credentials.parse(
                self.service.device_credentials).client_id

        # The first message must always be DEVICE_INFORMATION, otherwise the
        # device will not respond with anything
        msg = messages.device_information(
            'pyatv', self.srp.pairing_id.decode())
        await self.send_and_receive(msg)
        self._initial_message_sent = True

        # This should be the first message sent after encryption has
        # been enabled
        await self.send(messages.set_ready_state())

        async def _wait_for_updates(_, semaphore):
            # Use a counter here whenever more than one message is expected
            semaphore.release()

        # Wait for some stuff to arrive before returning
        semaphore = asyncio.Semaphore(value=0, loop=self.loop)
        self.add_listener(_wait_for_updates,
                          protobuf.SET_STATE_MESSAGE,
                          data=semaphore,
                          one_shot=True)

        # Subscribe to updates at this stage
        await self.send(messages.client_updates_config())
        await self.send(messages.wake_device())

        try:
            await asyncio.wait_for(
                semaphore.acquire(), 1, loop=self.loop)
        except asyncio.TimeoutError:
            # This is not an issue itself, but I should do something better.
            # Basically this gives the device about one second to respond with
            # some metadata before continuing.
            pass
831461
def _on_scan(_loop, adapter, _adapter_id, info, expiration_time):
    """"""

    info['validity_period'] = expiration_time
    adapter.notify_event_nowait(info.get('connection_string'), 'device_seen', info)
911
def init():
    """"""
    global __dev, __cfg_descr
    devices = get_dfu_devices(idVendor=__VID, idProduct=__PID)
    if not devices:
        raise ValueError('No DFU device found')
    if len(devices) > 1:
        raise ValueError("Multiple DFU devices found")
    __dev = devices[0]
    __dev.set_configuration()

    # Claim DFU interface
    usb.util.claim_interface(__dev, __DFU_INTERFACE)

    # Find the DFU configuration descriptor, either in the device or interfaces
    __cfg_descr = None
    for cfg in __dev.configurations():
        __cfg_descr = find_dfu_cfg_descr(cfg.extra_descriptors)
        if __cfg_descr:
            break
        for itf in cfg.interfaces():
            __cfg_descr = find_dfu_cfg_descr(itf.extra_descriptors)
            if __cfg_descr:
                break

    # Get device into idle state
    for attempt in range(4):
        status = get_status()
        if status == __DFU_STATE_DFU_IDLE:
            break
        elif (status == __DFU_STATE_DFU_DOWNLOAD_IDLE
            or status == __DFU_STATE_DFU_UPLOAD_IDLE):
            abort_request()
        else:
            clr_status()
431051
def main():
    
    try:
        # Retrieve the specified serial device.
        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))

        # Set up an event handler and open the device
        device.on_message += handle_message

        # Override the default SerialDevice baudrate since we're using a USB device
        # over serial in this example.
        with device.open(baudrate=BAUDRATE):
            while True:
                time.sleep(1)

    except Exception as ex:
        print('Exception:', ex)
295908
def process_event(event):
    
    if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
        print()

    print(event)

    if (event.type == EventType.ON_CONVERSATION_TURN_FINISHED and
            event.args and not event.args['with_follow_on_turn']):
        print()
    if event.type == EventType.ON_DEVICE_ACTION:
        for command, params in event.actions:
            print('Do command', command, 'with params', str(params))
528048
def handle_event(self, message):
        """"""
        # _LOGGER.debug(message)
        needs_update = 0
        for zone in self.zones:
            if zone in message:
                _LOGGER.debug("Received message for zone: %s", zone)
                self.zones[zone].update_status(message[zone])

        if 'netusb' in message:
            needs_update += self.handle_netusb(message['netusb'])

        if needs_update > 0:
            _LOGGER.debug("needs_update: %d", needs_update)
            self.update_hass()
587839
function curatedDeviceDisconnected(eventData) {
        self.log(' *** Handle', self.handle, 'triggered event: DEVICE_DISCONNECTED', eventData.name, eventData.operation);
    }
1091512
def _on_io_events(self, fd=None, _events=None):
        
        if fd not in self._connections:
            LOGGER.warning('Received IO event for non-existing connection')
            return
        self._poll_connection(fd)
202638
def start_processing_handler(self, event):
        """"""
        results_path = os.path.join(self.configuration['results_folder'],
                                    "filesystem.json")
        self.logger.debug("Event %s: start comparing %s with %s.",
                          event, self.checkpoints[0], self.checkpoints[1])

        results = compare_disks(self.checkpoints[0], self.checkpoints[1],
                                self.configuration)

        with open(results_path, 'w') as results_file:
            json.dump(results, results_file)

        self.processing_done.set()
1165609
function () {
			winble.deviceManager.connectionWatcher = Windows.Devices.Enumeration.Pnp.PnpObject.createWatcher(
				Windows.Devices.Enumeration.Pnp.PnpObjectType.deviceContainer,
				["System.Devices.Connected"],
				"");
			winble.deviceManager.connectionWatcher.onupdated = winble.deviceManager.onDeviceConnectionUpdated;
			winble.deviceManager.connectionWatcher.start();
		}