github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/sleep/darwin.h (about)

     1  #include <ctype.h>
     2  #include <stdlib.h>
     3  #include <stdio.h>
     4  
     5  #include <mach/mach_port.h>
     6  #include <mach/mach_interface.h>
     7  #include <mach/mach_init.h>
     8  
     9  #include <IOKit/pwr_mgt/IOPMLib.h>
    10  #include <IOKit/IOMessage.h>
    11  
    12  io_connect_t root_port; // a reference to the Root Power Domain IOService
    13  // notification port allocated by IORegisterForSystemPower
    14  IONotificationPortRef notifyPortRef;
    15  // notifier object, used to deregister later
    16  io_object_t notifierObject;
    17  // this parameter is passed to the callback
    18  void *refCon;
    19  CFRunLoopRef runLoop;
    20  
    21  void SleepCallBack(void *refCon, io_service_t service, natural_t messageType, void *messageArgument)
    22  {
    23      switch (messageType)
    24      {
    25      case kIOMessageSystemWillSleep:
    26          NotifySleep();
    27          IOAllowPowerChange(root_port, (long)messageArgument);
    28          break;
    29      case kIOMessageSystemWillPowerOn:
    30          NotifyWake();
    31          break;
    32      case kIOMessageSystemHasPoweredOn:
    33          break;
    34      default:
    35          break;
    36      }
    37  }
    38  
    39  void registerNotifications()
    40  {
    41      root_port = IORegisterForSystemPower(refCon, &notifyPortRef, SleepCallBack, &notifierObject);
    42      if (root_port == 0)
    43      {
    44          printf("IORegisterForSystemPower failed\n");
    45      }
    46  
    47      CFRunLoopAddSource(CFRunLoopGetCurrent(),
    48                         IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes);
    49  
    50      runLoop = CFRunLoopGetCurrent();
    51      CFRunLoopRun();
    52  }
    53  
    54  void unregisterNotifications()
    55  {
    56      CFRunLoopRemoveSource(runLoop,
    57                            IONotificationPortGetRunLoopSource(notifyPortRef),
    58                            kCFRunLoopCommonModes);
    59  
    60      IODeregisterForSystemPower(&notifierObject);
    61  
    62      IOServiceClose(root_port);
    63  
    64      IONotificationPortDestroy(notifyPortRef);
    65  
    66      CFRunLoopStop(runLoop);
    67  }