Esempio n. 1
0
int AoEProperties::configure_matching(void)
{
//	debugVerbose("AoEProperties::configure_matching\n");
	
	// Obtain ports for notifications (this will be used for all service matching notifications)
	kern_return_t kresult;
	mach_port_t MasterPort;
	kresult = IOMasterPort(MACH_PORT_NULL, &MasterPort);
	if ( kresult )
	{
		debugError("Could not get masterport. Error=%d\n", kresult);
		return false;
	}
	
	ms_NotificationPort = IONotificationPortCreate(MasterPort);
	
	ms_IOKitNotificationRunLoopSource = IONotificationPortGetRunLoopSource(ms_NotificationPort);
	CFRunLoopAddSource(CFRunLoopGetCurrent(), ms_IOKitNotificationRunLoopSource, kCFRunLoopDefaultMode);
	
	// SetUp Notification for matching to our device
	CFMutableDictionaryRef MatchingDict = IOServiceMatching(AOE_KEXT_NAME_Q);

	IOServiceAddMatchingNotification(ms_NotificationPort,
									 kIOMatchedNotification,
									 MatchingDict,
									 AoEProperties::matched_callback,
									 this,
									 &ms_MatchIt);
	
	// Call the callback immediately to check if our iterator already contains our device (ie. the device is already loaded)
	matched_callback(this, ms_MatchIt);
	
	return m_fMatched ? 0 : -1;
}
Esempio n. 2
0
TorcUSBPrivOSX::TorcUSBPrivOSX(TorcUSB *Parent)
  : QObject(Parent),
    m_usbRef(NULL),
    m_usbNotifyPort(NULL),
    m_iterator(0),
    m_notificationsLock(new QMutex())
{
    if (!gAdminRunLoop)
    {
        LOG(VB_GENERAL, LOG_ERR, "OS X callback run loop not present - aborting");
        return;
    }

    CFMutableDictionaryRef match = IOServiceMatching(kIOUSBDeviceClassName);

    m_usbNotifyPort = IONotificationPortCreate(kIOMasterPortDefault);
    m_usbRef = IONotificationPortGetRunLoopSource(m_usbNotifyPort);
    CFRunLoopAddSource(gAdminRunLoop, m_usbRef, kCFRunLoopCommonModes);

    IOReturn ok = IOServiceAddMatchingNotification(m_usbNotifyPort, kIOFirstMatchNotification, match,
                                                   (IOServiceMatchingCallback)DeviceAddedCallback,
                                                   this, &m_iterator);
    if (kIOReturnSuccess == ok)
        DeviceAddedCallback(this, m_iterator);
    else
        LOG(VB_GENERAL, LOG_ERR, "Failed to register for attachment notifications");
}
Esempio n. 3
0
int usbmain(){
    int vendor = V_CORSAIR;
    int products[] = { P_K65, P_K70, P_K70_NRGB, P_K95, P_K95_NRGB/*, P_M65*/ };
    // Tell IOService which type of devices we want (IOHIDDevices matching the supported vendor/products)
    CFMutableDictionaryRef match = IOServiceMatching(kIOHIDDeviceKey);
    CFNumberRef cfvendor = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &vendor);
    CFDictionarySetValue(match, CFSTR(kIOHIDVendorIDKey), cfvendor);
    CFRelease(cfvendor);
    CFMutableArrayRef cfproducts = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
    for(uint i = 0; i < sizeof(products) / sizeof(int); i++){
        int product = products[i];
        CFNumberRef cfproduct = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &product);
        CFArrayAppendValue(cfproducts, cfproduct);
        CFRelease(cfproduct);
    }
    CFDictionarySetValue(match, CFSTR(kIOHIDProductIDArrayKey), cfproducts);
    CFRelease(cfproducts);

    notify = IONotificationPortCreate(kIOMasterPortDefault);
    CFRunLoopAddSource(mainloop = CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopDefaultMode);
    io_iterator_t iterator;
    IOReturn res = IOServiceAddMatchingNotification(notify, kIOMatchedNotification, match, iterate_devices, 0, &iterator);
    if(res != kIOReturnSuccess){
        ckb_fatal("Failed to list devices: %x\n", res);
        return -1;
    }
    // Iterate existing devices
    iterate_devices(0, iterator);
    // Enter loop to scan/connect new devices
    CFRunLoopRun();
    return 0;
}
Esempio n. 4
0
void IOKitEventPublisher::stop() {
  if (run_loop_ == nullptr) {
    // If there is no run loop then the publisher thread has not started.
    return;
  }

  // Stop the run loop.
  WriteLock lock(mutex_);
  CFRunLoopStop(run_loop_);

  // Stop the run loop before operating on containers.
  // Destroy the IOPort.
  if (port_ != nullptr) {
    auto source = IONotificationPortGetRunLoopSource(port_);
    if (CFRunLoopContainsSource(run_loop_, source, kCFRunLoopDefaultMode)) {
      CFRunLoopRemoveSource(run_loop_, source, kCFRunLoopDefaultMode);
    }
    // And destroy the port.
    IONotificationPortDestroy(port_);
    port_ = nullptr;
  }

  // Clear all devices and their notifications.
  for (const auto& device : devices_) {
    IOObjectRelease(device->notification);
  }
  devices_.clear();
}
Esempio n. 5
0
    void mac_sleep_stop()
    {
      if (root_port)
	{
	  // remove the sleep notification port from the application runloop
	  CFRunLoopRemoveSource(CFRunLoopGetCurrent(),
				IONotificationPortGetRunLoopSource(notifyPortRef),
				kCFRunLoopCommonModes);

	  // deregister for system sleep notifications
	  IODeregisterForSystemPower(&notifierObject);

	  // IORegisterForSystemPower implicitly opens the Root Power Domain IOService
	  // so we close it here
	  IOServiceClose(root_port);

	  // destroy the notification port allocated by IORegisterForSystemPower
	  IONotificationPortDestroy(notifyPortRef);

	  // reset object members
	  root_port = 0;
	  notifyPortRef = NULL;
	  notifierObject = 0;
	}
    }
Esempio n. 6
0
void CCocoaPowerSyscall::DeleteOSPowerCallBacks(void)
{
#if !defined(TARGET_DARWIN_IOS)
  CCocoaAutoPool autopool;
  // we no longer want sleep/wake notifications
  // remove the sleep notification port from the application runloop
  CFRunLoopRemoveSource( CFRunLoopGetCurrent(),
    IONotificationPortGetRunLoopSource(m_notify_port), kCFRunLoopDefaultMode );
  // deregister for system sleep notifications
  IODeregisterForSystemPower(&m_notifier_object);
  // IORegisterForSystemPower implicitly opens the Root Power Domain IOService
  // so we close it here
  IOServiceClose(m_root_port);
  // destroy the notification port allocated by IORegisterForSystemPower
  IONotificationPortDestroy(m_notify_port);
  
  // we no longer want power source change notifications
  if (m_HasBattery)
  {
    if (m_power_source)
    {
      CFRunLoopRemoveSource( CFRunLoopGetCurrent(), m_power_source, kCFRunLoopDefaultMode );
      CFRelease(m_power_source);
    }
  }
#endif
}
Esempio n. 7
0
void XNotificationPort::addInterestNotification(XReceiver &receiver, io_service_t service, 
	const io_name_t interestType)
{
	io_iterator_t iterator;
	mach_port_t pp = NotificationPort::port();
//	MachPlusPlus::Port(pp).dump(0);
	secdebug("iokit", "XNotificationPort::addInterest - type: %s [port: %p (0x%08X), service: 0x%08X]",
		interestType, mPortRef, pp, service);	// IOServiceMatched
#if 1
	CFRunLoopSourceRef notificationRunLoopSource = IONotificationPortGetRunLoopSource(mPortRef);
	CFRunLoopSourceRef classRunLoopSource = NotificationPort::source();
//    IONotificationPortRef r_notify_port = IONotificationPortCreate(0);
	kern_return_t kr = ::IOServiceAddInterestNotification(mPortRef,	//,r_notify_port
		service, interestType, ioDeviceNotification, &receiver, &iterator);
	const char *msgstr = mach_error_string(kr);
	const char *msgtyp = mach_error_type(kr);
	if (msgstr && msgtyp)
		secdebug("iokit", " msg: %s, typ: %s", msgstr, msgtyp);
//	Error::check(kr);
//    if(r_notify_port) IOObjectRelease((io_object_t)r_notify_port);
#else
	Error::check(::IOServiceAddInterestNotification(mPortRef,
		service, interestType, ioDeviceNotification, &receiver, &iterator));
#endif
}
Esempio n. 8
0
/* Cleanup of the open ports */
void PortsCleanup()
{
	CFRunLoopRemoveSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes);    /* Remove the notification port from the runloop */
	IODeregisterForSystemPower(&notifierObject);                                                                               /* Deregister from power notifications */
	IOServiceClose(root_power_port);                                                                                           /* Close the Root Power Domain IOService port */
	IONotificationPortDestroy(notifyPortRef);                                                                                  /* Destroy the notification port */
}
Esempio n. 9
0
static Boolean InitIOKit() {
	Boolean	success = TRUE;
	
	write_log(LOG_NOTICE, "Creating IOKit notification port.");
	
	ioKitNotificationPort = IONotificationPortCreate(kIOMasterPortDefault);
	
    if(ioKitNotificationPort == NULL) {
		write_log(LOG_ERR, "Couldn't create IOKit notification port!");
		success = FALSE;
		goto EXIT;
	}
	
	write_log(LOG_NOTICE, "Creating IOKit RunLoop source.");
	
	ioRunLoopSource = IONotificationPortGetRunLoopSource(ioKitNotificationPort);
	if(ioRunLoopSource == NULL) {
		write_log(LOG_ERR, "Couldn't create IOKit RunLoop source!");
		success = FALSE;
		goto EXIT;
	}
	
    CFRunLoopAddSource(CFRunLoopGetCurrent(), ioRunLoopSource, 
					   kCFRunLoopDefaultMode);
	
EXIT:
	return success;
}
Esempio n. 10
0
static void cbWork(uv_work_t *req) {
	// We have this check in case we `Stop` before this thread starts,
	// otherwise the process will hang
	if(!isRunning) {
		return;
	}

	uv_signal_start(&int_signal, cbTerminate, SIGINT);
	uv_signal_start(&term_signal, cbTerminate, SIGTERM);

	runLoopSource = IONotificationPortGetRunLoopSource(gNotifyPort);

	gRunLoop = CFRunLoopGetCurrent();
	CFRunLoopAddSource(gRunLoop, runLoopSource, kCFRunLoopDefaultMode);

	// Creating `gRunLoop` can take some cycles so we also need this second
	// `isRunning` check here because it happens at a future time
	if(isRunning) {
		// Start the run loop. Now we'll receive notifications.
		CFRunLoopRun();
	}

	// The `CFRunLoopRun` is a blocking call so we also need this second
	// `isRunning` check here because it happens at a future time
	if(isRunning) {
		// We should never get here while running
		fprintf(stderr, "Unexpectedly back from CFRunLoopRun()!\n");
	}
}
Esempio n. 11
0
int main(int argc, char** argv)
{
    //
    // From https://developer.apple.com/library/mac/qa/qa1340/_index.html
    // I have basically no idea how this works :)
    //
    // notification port allocated by IORegisterForSystemPower
    IONotificationPortRef  notifyPortRef;

    // notifier object, used to deregister later
    io_object_t            notifierObject;
    // this parameter is passed to the callback
    void*                  refCon;

    // register to receive system sleep notifications

    root_port = IORegisterForSystemPower(refCon, &notifyPortRef, SleepCallBack, &notifierObject);
    if (root_port == 0) {
        printf("IORegisterForSystemPower failed\n");
        return 1;
    }

    // add the notification port to the application runloop
    CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes);

    /* Start the run loop to receive sleep notifications. Don't call CFRunLoopRun if this code
        is running on the main thread of a Cocoa or Carbon application. Cocoa and Carbon
        manage the main thread's run loop for you as part of their event handling
        mechanisms.
    */
    CFRunLoopRun();

    //Not reached, CFRunLoopRun doesn't return in this case.
    return 0;
}
Esempio n. 12
0
void CCocoaPowerSyscall::CreateOSPowerCallBacks(void)
{
#if !defined(TARGET_DARWIN_IOS)
  CCocoaAutoPool autopool;
  // we want sleep/wake notifications, register to receive system power notifications
  m_root_port = IORegisterForSystemPower(this, &m_notify_port, OSPowerCallBack, &m_notifier_object);
  if (m_root_port)
  {
    // add the notification port to the application runloop
    CFRunLoopAddSource(CFRunLoopGetCurrent(),
      IONotificationPortGetRunLoopSource(m_notify_port), kCFRunLoopDefaultMode);
  }
  else
  {
    CLog::Log(LOGERROR, "%s - IORegisterForSystemPower failed", __FUNCTION__);
  }

  // if we have a battery, we want power source change notifications (on AC, on Battery, etc)
  if (m_HasBattery)
  {
    m_power_source = IOPSNotificationCreateRunLoopSource(OSPowerSourceCallBack, this);
    if (m_power_source)
      CFRunLoopAddSource(CFRunLoopGetCurrent(), m_power_source, kCFRunLoopDefaultMode);
    else
      CLog::Log(LOGERROR, "%s - IOPSNotificationCreateRunLoopSource failed", __FUNCTION__);
  }
#endif
}
Esempio n. 13
0
static int
InitUSB()
{
    CFMutableDictionaryRef  matchingDict;
    CFRunLoopSourceRef      runLoopSource;
    SInt32                  vendor, if_subclass, if_protocol;
    unsigned                i;

    //* To set up asynchronous notifications, create a notification port and
    //* add its run loop event source to the program's run loop
    notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
    runLoopSource = IONotificationPortGetRunLoopSource(notificationPort);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);

    memset(notificationIterators, 0, sizeof(notificationIterators));

    //* loop through all supported vendors
    for (i = 0; i < vendorIdCount; i++) {
        //* Create our matching dictionary to find the Android device's
        //* adb interface
        //* IOServiceAddMatchingNotification consumes the reference, so we do
        //* not need to release this
        matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);

        if (!matchingDict) {
            DBG("ERR: Couldn't create USB matching dictionary.\n");
            return -1;
        }

        //* Match based on vendor id, interface subclass and protocol
        vendor = vendorIds[i];
        if_subclass = ADB_SUBCLASS;
        if_protocol = ADB_PROTOCOL;
        CFDictionarySetValue(matchingDict, CFSTR(kUSBVendorID),
                             CFNumberCreate(kCFAllocatorDefault,
                                            kCFNumberSInt32Type, &vendor));
        CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceSubClass),
                             CFNumberCreate(kCFAllocatorDefault,
                                            kCFNumberSInt32Type, &if_subclass));
        CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceProtocol),
                             CFNumberCreate(kCFAllocatorDefault,
                                            kCFNumberSInt32Type, &if_protocol));
        IOServiceAddMatchingNotification(
                notificationPort,
                kIOFirstMatchNotification,
                matchingDict,
                AndroidInterfaceAdded,
                NULL,
                &notificationIterators[i]);

        //* Iterate over set of matching interfaces to access already-present
        //* devices and to arm the notification
        AndroidInterfaceAdded(NULL, notificationIterators[i]);
    }

    return 0;
}
Esempio n. 14
0
int
main(void)
{
    CFMutableDictionaryRef match;
    IONotificationPortRef  notifyPort;
    CFRunLoopSourceRef     notificationRunLoopSource;
    io_iterator_t          notificationIn, notificationOut;
   
    // Create a matching dictionary for all IOMedia objects.
    if (!(match = IOServiceMatching("IOMedia"))) {
        fprintf(stderr, "*** failed to create matching dictionary.\n");
        exit(1);
    }
   
    // Create a notification object for receiving I/O Kit notifications.
    notifyPort = IONotificationPortCreate(kIOMasterPortDefault);
   
    // Get a CFRunLoopSource that we will use to listen for notifications.
    notificationRunLoopSource = IONotificationPortGetRunLoopSource(notifyPort);
   
    // Add the CFRunLoopSource to the default mode of our current run loop.
    CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource,
                       kCFRunLoopDefaultMode);
   
    // One reference of the matching dictionary will be consumed when we install
    // a notification request. Since we need to install two such requests (one
    // for ejectable media coming in and another for it going out), we need
    // to increment the reference count on our matching dictionary.
    CFRetain(match);
   
    // Install notification request for matching objects coming in.
    // Note that this will also look up already existing objects.
    IOServiceAddMatchingNotification(
        notifyPort,             // notification port reference
        kIOMatchedNotification, // notification type
        match,                  // matching dictionary
        matchingCallback,       // this is called when notification fires
        NULL,                   // reference constant
        &notificationIn);       // iterator handle
   
    // Install notification request for matching objects going out.
    IOServiceAddMatchingNotification(
        notifyPort,
        kIOTerminatedNotification,
        match,
        matchingCallback,
        NULL,
        &notificationOut);
   
    // Invoke callbacks explicitly to empty the iterators/arm the notifications.
    matchingCallback(0, notificationIn);
    matchingCallback(0, notificationOut);
   
    CFRunLoopRun(); // run
   
    exit(0);
}
Esempio n. 15
0
/*! Deregisters the daemon with the kernel to no longer receive power events. */
void iSCSIDDeregisterForPowerEvents()
{
    CFRunLoopRemoveSource(CFRunLoopGetCurrent(),
                          IONotificationPortGetRunLoopSource(powerNotifyPortRef),
                          kCFRunLoopDefaultMode);

    IODeregisterForSystemPower(&powerNotifier);
    IOServiceClose(powerPlaneRoot);
    IONotificationPortDestroy(powerNotifyPortRef);
}
Esempio n. 16
0
void InitUPSNotifications()
{
    CFMutableDictionaryRef 	matchingDict;
    CFMutableDictionaryRef	propertyDict;
    kern_return_t		kr;

    // Create a notification port and add its run loop event source to our run loop
    // This is how async notifications get set up.
    //
    gNotifyPort = IONotificationPortCreate(kIOMasterPortDefault);
    CFRunLoopAddSource(	CFRunLoopGetCurrent(), 
                        IONotificationPortGetRunLoopSource(gNotifyPort), 
                        kCFRunLoopDefaultMode);

    // Create the IOKit notifications that we need
    //
    matchingDict = IOServiceMatching(kIOServiceClass); 
    
    if (!matchingDict)
	return;    
        
    propertyDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 
                    0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    if (!propertyDict)
    {
        CFRelease(matchingDict);
	return;
    }
        
    // We are only interested in devices that have kIOUPSDeviceKey property set
    CFDictionarySetValue(propertyDict, CFSTR(kIOUPSDeviceKey), kCFBooleanTrue);
    
    CFDictionarySetValue(matchingDict, CFSTR(kIOPropertyMatchKey), propertyDict);
    
    CFRelease(propertyDict);


    // Now set up a notification to be called when a device is first matched by I/O Kit.
    // Note that this will not catch any devices that were already plugged in so we take
    // care of those later.
    kr = IOServiceAddMatchingNotification(gNotifyPort,			// notifyPort
                                          kIOFirstMatchNotification,	// notificationType
                                          matchingDict,			// matching
                                          UPSDeviceAdded,		// callback
                                          NULL,				// refCon
                                          &gAddedIter			// notification
                                          );

    if ( kr != kIOReturnSuccess )
        return;
        
    UPSDeviceAdded( NULL, gAddedIter );
}
Esempio n. 17
0
    bool mac_sleep_start()
    {
      if (!root_port)
	{
	  root_port = IORegisterForSystemPower(this, &notifyPortRef, callback_static, &notifierObject);
	  if (!root_port)
	    return false;
	  CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes);
	}
      return true;
    }
Esempio n. 18
0
bool HIDDevice::setupDevicePluggedInNotification()
{
    
    // Setup notification when devices are plugged in.
    RepluggedNotificationPort = IONotificationPortCreate(kIOMasterPortDefault);
    
    CFRunLoopSourceRef notificationRunLoopSource =
        IONotificationPortGetRunLoopSource(RepluggedNotificationPort);
    
    CFRunLoopAddSource(HIDManager->getRunLoop(),
                       notificationRunLoopSource,
                       kCFRunLoopDefaultMode);
    
    CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
    
    // Have to specify vendorId and productId. Doesn't seem to accept additional
    // things like serial number.
    SInt32 vendorId = DevDesc.VendorId;
    CFNumberRef numberRef = CFNumberCreate(kCFAllocatorDefault,
                                           kCFNumberSInt32Type,
                                           &vendorId);
    CFDictionarySetValue(matchingDict, CFSTR(kUSBVendorID), numberRef);
    CFRelease(numberRef);
    
    SInt32 deviceProductId = DevDesc.ProductId;
    numberRef = CFNumberCreate(kCFAllocatorDefault,
                               kCFNumberSInt32Type,
                               &deviceProductId);
    CFDictionarySetValue(matchingDict, CFSTR(kUSBProductID), numberRef);
    CFRelease(numberRef);
    
    kern_return_t result =
            IOServiceAddMatchingNotification(RepluggedNotificationPort,
                                             kIOMatchedNotification,
                                             matchingDict,
                                             staticDeviceAddedCallback,
                                             this,
                                             &RepluggedNotification);
    
    if (result != KERN_SUCCESS)
    {
        CFRelease(RepluggedNotificationPort);
        RepluggedNotificationPort = 0;
        return false;
    }
    
    // Iterate through to arm.
    while (IOIteratorNext(RepluggedNotification))
    {
	}
    
    return true;
}
// m_LoopRef needs to be set before this is called
void InputHandler_MacOSX_HID::StartDevices()
{
	int n = 0;

	ASSERT( m_LoopRef );
	FOREACH( HIDDevice *, m_vDevices, i )
		(*i)->StartQueue( m_LoopRef, InputHandler_MacOSX_HID::QueueCallback, this, n++ );

	CFRunLoopSourceRef runLoopSource = IONotificationPortGetRunLoopSource( m_NotifyPort );

	CFRunLoopAddSource( m_LoopRef, runLoopSource, kCFRunLoopDefaultMode );
}
Esempio n. 20
0
void
COSXScreen::watchSystemPowerThread(void*)
{
	io_object_t				notifier;
	IONotificationPortRef	notificationPortRef;
	CFRunLoopSourceRef		runloopSourceRef = 0;

	m_pmRunloop = CFRunLoopGetCurrent();
	// install system power change callback
	m_pmRootPort = IORegisterForSystemPower(this, &notificationPortRef,
											powerChangeCallback, &notifier);
	if (m_pmRootPort == 0) {
		LOG((CLOG_WARN "IORegisterForSystemPower failed"));
	}
	else {
		runloopSourceRef =
			IONotificationPortGetRunLoopSource(notificationPortRef);
		CFRunLoopAddSource(m_pmRunloop, runloopSourceRef,
								kCFRunLoopCommonModes);
	}
	
	// thread is ready
	{
		CLock lock(m_pmMutex);
		*m_pmThreadReady = true;
		m_pmThreadReady->signal();
	}

	// if we were unable to initialize then exit.  we must do this after
	// setting m_pmThreadReady to true otherwise the parent thread will
	// block waiting for it.
	if (m_pmRootPort == 0) {
		return;
	}

	// start the run loop
	LOG((CLOG_DEBUG "started watchSystemPowerThread"));
	CFRunLoopRun();
	
	// cleanup
	if (notificationPortRef) {
		CFRunLoopRemoveSource(m_pmRunloop,
								runloopSourceRef, kCFRunLoopDefaultMode);
		CFRunLoopSourceInvalidate(runloopSourceRef);
		CFRelease(runloopSourceRef);
	}

	CLock lock(m_pmMutex);
	IODeregisterForSystemPower(&notifier);
	m_pmRootPort = 0;
	LOG((CLOG_DEBUG "stopped watchSystemPowerThread"));
}
Esempio n. 21
0
int main( int argc, char **argv ) {
    IONotificationPortRef notifyPortRef; 
    io_object_t notifierObject; 
    void* refCon; 
    root_port = IORegisterForSystemPower( refCon, &notifyPortRef, MySleepCallBack, &notifierObject );
    if ( root_port == 0 ) {
        printf("IORegisterForSystemPower failed\n");
        return 1;
    }
    CFRunLoopAddSource( CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes ); 
    CFRunLoopRun();
    return (0);
}
MacSystemWatch::MacSystemWatch()
{
    // Initialize sleep callback
    IONotificationPortRef notify;
    io_object_t           anIterator;
    root_port = IORegisterForSystemPower(this, &notify, sleepCallBack, &anIterator);
    if (!root_port) {
        printf("IORegisterForSystemPower failed\n");
    }
    else {
        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopCommonModes);
    }
}
void SystemEventsManager::stopLoop(bool forceStop) {
    if (systemEventLoopRunning && (forceStop || allEventsDisabled())) {
        CFRunLoopRemoveSource(CFRunLoopGetCurrent(),
                              IONotificationPortGetRunLoopSource(notifyPortRef),
                              kCFRunLoopCommonModes);
        IODeregisterForSystemPower(&notifierObject);
        IOServiceClose(rootPort);
        IONotificationPortDestroy(notifyPortRef);
        
        CFRunLoopStop(CFRunLoopGetCurrent());
        
        systemEventLoopRunning = false;
    }
}
Esempio n. 24
0
static void initializePowerNotifications (void)
{
	static io_connect_t	rootPort;	/* used by powerCallback() via context pointer */
	
	IONotificationPortRef	notificationPort;
	io_object_t		notifier;

	rootPort = IORegisterForSystemPower(&rootPort, &notificationPort, powerCallback, &notifier);
	if (! rootPort) {
		message (LOG_ERR, "IORegisterForSystemPower failed\n");
		exit (1);
	}
	CFRunLoopAddSource (CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode);
}
Esempio n. 25
0
void IOKitEventPublisher::restart() {
  static std::vector<const std::string*> device_classes = {
      &kIOUSBDeviceClassName_,
      &kIOPCIDeviceClassName_,
      &kIOPlatformExpertDeviceClassName_,
      &kIOACPIPlatformDeviceClassName_,
      &kIOPlatformDeviceClassname_,
  };

  if (run_loop_ == nullptr) {
    return;
  }

  // Remove any existing stream.
  stop();

  {
    WriteLock lock(mutex_);
    port_ = IONotificationPortCreate(kIOMasterPortDefault);
    // Get a run loop source from the created IOKit notification port.
    auto run_loop_source = IONotificationPortGetRunLoopSource(port_);
    CFRunLoopAddSource(run_loop_, run_loop_source, kCFRunLoopDefaultMode);
  }

  publisher_started_ = false;
  for (const auto& class_name : device_classes) {
    // Service matching is USB for now, must find a way to get more!
    // Can provide a "IOPCIDevice" here too.
    auto matches = IOServiceMatching(class_name->c_str());

    // Register attach/detaches (could use kIOPublishNotification).
    // Notification types are defined in IOKitKeys.
    IOReturn result = kIOReturnSuccess + 1;
    {
      WriteLock lock(mutex_);
      result = IOServiceAddMatchingNotification(
          port_,
          kIOFirstMatchNotification,
          matches,
          (IOServiceMatchingCallback)deviceAttach,
          this,
          &iterator_);
    }
    if (result == kIOReturnSuccess) {
      deviceAttach(this, iterator_);
    }
  }
  publisher_started_ = true;
}
Esempio n. 26
0
/*! Registers the daemon with the kernel to receive power events
 *  (e.g., sleep/wake notifications).
 *  @return true if the daemon was successfully registered. */
bool iSCSIDRegisterForPowerEvents()
{
    powerPlaneRoot = IORegisterForSystemPower(NULL,
                     &powerNotifyPortRef,
                     iSCSIDHandlePowerEvent,
                     &powerNotifier);

    if(powerPlaneRoot == 0)
        return false;

    CFRunLoopAddSource(CFRunLoopGetMain(),
                       IONotificationPortGetRunLoopSource(powerNotifyPortRef),
                       kCFRunLoopDefaultMode);
    return true;
}
Esempio n. 27
0
HostPowerServiceDarwin::~HostPowerServiceDarwin()
{
    /* Jump out of the run loop. */
    CFRunLoopStop(mRunLoop);
    /* Remove the sleep notification port from the application runloop. */
    CFRunLoopRemoveSource(CFRunLoopGetCurrent(),
                          IONotificationPortGetRunLoopSource(mNotifyPort),
                          kCFRunLoopCommonModes);
    /* Deregister for system sleep notifications. */
    IODeregisterForSystemPower(&mNotifierObject);
    /* IORegisterForSystemPower implicitly opens the Root Power Domain
     * IOService so we close it here. */
    IOServiceClose(mRootPort);
    /* Destroy the notification port allocated by IORegisterForSystemPower */
    IONotificationPortDestroy(mNotifyPort);
}
Esempio n. 28
0
void *RunLoop(void * arg)
{

    runLoopSource = IONotificationPortGetRunLoopSource(gNotifyPort);
    
    gRunLoop = CFRunLoopGetCurrent();
    CFRunLoopAddSource(gRunLoop, runLoopSource, kCFRunLoopDefaultMode);      

    // Start the run loop. Now we'll receive notifications.
    CFRunLoopRun();

    // We should never get here
    fprintf(stderr, "Unexpectedly back from CFRunLoopRun()!\n");

    return NULL;
}
void SystemEventsManager::runLoop() {
    void* refCon = nullptr;
    
    rootPort = IORegisterForSystemPower(refCon,
                                        &notifyPortRef,
                                        systemEventCallback,
                                        &notifierObject);
    if (rootPort != 0)
    {
        systemEventLoopRunning = true;
        CFRunLoopAddSource(CFRunLoopGetCurrent(),
                           IONotificationPortGetRunLoopSource(notifyPortRef),
                           kCFRunLoopCommonModes);
        CFRunLoopRun();
    }
}
Esempio n. 30
0
static PyObject *pypowerobserver_run(PyPowerObserver *self,
				     PyObject *args,
				     PyObject *kwargs)
{
    if (!PyArg_ParseTuple(args, ":run"))
        return NULL;

    self->runLoop = CFRunLoopGetCurrent();
    CFRunLoopAddSource (self->runLoop, IONotificationPortGetRunLoopSource(self->notificationPort), kCFRunLoopDefaultMode);

    Py_BEGIN_ALLOW_THREADS
        CFRunLoopRun();
    Py_END_ALLOW_THREADS

    Py_INCREF(Py_None);
    return Py_None;
}