// static
void QextSerialEnumerator::scanPortsOSX(QList<QextPortInfo> & infoList)
{
    io_iterator_t serialPortIterator = 0;
    kern_return_t kernResult = KERN_FAILURE;
    CFMutableDictionaryRef matchingDictionary;

    // first try to get any serialbsd devices, then try any USBCDC devices
    if( !(matchingDictionary = IOServiceMatching(kIOSerialBSDServiceValue) ) ) {
        qWarning("IOServiceMatching returned a NULL dictionary.");
        return;
    }
    CFDictionaryAddValue(matchingDictionary, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));

    // then create the iterator with all the matching devices
    if( IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDictionary, &serialPortIterator) != KERN_SUCCESS ) {
        qCritical() << "IOServiceGetMatchingServices failed, returned" << kernResult;
        return;
    }
    iterateServicesOSX(serialPortIterator, infoList);
    IOObjectRelease(serialPortIterator);
    serialPortIterator = 0;

    if( !(matchingDictionary = IOServiceNameMatching("AppleUSBCDC")) ) {
        qWarning("IOServiceNameMatching returned a NULL dictionary.");
        return;
    }

    if( IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDictionary, &serialPortIterator) != KERN_SUCCESS ) {
        qCritical() << "IOServiceGetMatchingServices failed, returned" << kernResult;
        return;
    }
    iterateServicesOSX(serialPortIterator, infoList);
    IOObjectRelease(serialPortIterator);
}
Exemplo n.º 2
0
CFStringRef lookup_mac_address(const char* serviceName)
{
    unsigned char macaddrBytes[6];
    CFStringRef res = NULL;

    io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching(serviceName));
    
    if(service)
    {
        CFDataRef macData = IORegistryEntryCreateCFProperty(service, CFSTR("local-mac-address"), kCFAllocatorDefault, 0);
        if(macData != NULL)
        {
            CFDataGetBytes(macData, CFRangeMake(0,6), macaddrBytes);
    
            res = CFStringCreateWithFormat(kCFAllocatorDefault,
                                        NULL,
                                        CFSTR("%02x:%02x:%02x:%02x:%02x:%02x"),
                                        macaddrBytes[0],
                                        macaddrBytes[1],
                                        macaddrBytes[2],
                                        macaddrBytes[3],
                                        macaddrBytes[4],
                                        macaddrBytes[5]);
            CFRelease(macData);
        }
        IOObjectRelease(service);
    }
    return res;
}
Exemplo n.º 3
0
CFStringRef copy_device_imei() {
    CFMutableDictionaryRef matching;
    io_service_t service;
    CFDataRef imeiData;
    const void *imeiDataPtr;
    CFStringRef imeiString;
    
    matching = IOServiceNameMatching("baseband");
    service = IOServiceGetMatchingService(kIOMasterPortDefault, matching);
    
    if(!service) {
        return NULL;
    }
    
    imeiData = IORegistryEntryCreateCFProperty(service, CFSTR("device-imei"), kCFAllocatorDefault, 0);
    if(!imeiData) {
        printf("unable to find device-imei property\n");
        IOObjectRelease(service);
        return NULL;
    }
    
    imeiDataPtr = CFDataGetBytePtr(imeiData);
    imeiString = CFStringCreateWithCString(kCFAllocatorDefault, imeiDataPtr, kCFStringEncodingUTF8);
    
    CFRelease(imeiData);
    IOObjectRelease(service);
    
    return imeiString;
}
io_connect_t    connectSmartBatteryManager(uint32_t options, IOReturn *outret)
{
    io_service_t            smartbattman_entry = MACH_PORT_NULL;
    io_connect_t            manager_connect = MACH_PORT_NULL;
    IOReturn                ret;

    smartbattman_entry = IOServiceGetMatchingService( MACH_PORT_NULL,
                            IOServiceNameMatching(kBatteryManagerName) );


    if (MACH_PORT_NULL == smartbattman_entry) {
        return MACH_PORT_NULL;
    }

    ret = IOServiceOpen( smartbattman_entry,            /* service */
                         mach_task_self(),              /* owning task */
                         options,                       /* type - kBatteryExclusiveAccessType or not*/
                         &manager_connect);             /* connect */


    if (outret) *outret = ret;

    if(kIOReturnSuccess != ret) {
        return MACH_PORT_NULL;
    }
    
    IOObjectRelease(smartbattman_entry);
    return manager_connect;
}
Exemplo n.º 5
0
CFStringRef copy_bluetooth_mac_address() {
    io_service_t service;
    CFDataRef macaddrData;
    CFStringRef macaddr;
    unsigned char macaddrBytes[6];
    
    service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching("bluetooth"));
    if(!service) {
        printf("unable to find bluetooth service\n");
        return NULL;
    }
    
    macaddrData= IORegistryEntryCreateCFProperty(service, CFSTR("local-mac-address"), kCFAllocatorDefault, 0);
    if(macaddrData == NULL) {
        printf("bluetooth local-mac-address not found\n");
        IOObjectRelease(service);
        return NULL;
    }
    CFDataGetBytes(macaddrData, CFRangeMake(0,6), macaddrBytes);
    
    macaddr = CFStringCreateWithFormat(kCFAllocatorDefault,
                                        NULL,
                                        CFSTR("%02x:%02x:%02x:%02x:%02x:%02x"),
                                        macaddrBytes[0],
                                        macaddrBytes[1],
                                        macaddrBytes[2],
                                        macaddrBytes[3],
                                        macaddrBytes[4],
                                        macaddrBytes[5]);

    return macaddr;
}
Exemplo n.º 6
0
int
main(void)
{
    kern_return_t          kr;
    io_iterator_t          io_hw_sensors;
    io_service_t           io_hw_sensor;
    CFMutableDictionaryRef sensor_properties;
    CFStringEncoding       systemEncoding = CFStringGetSystemEncoding();
   
    kr = IOServiceGetMatchingServices(kIOMasterPortDefault,
             IOServiceNameMatching("IOHWSensor"), &io_hw_sensors);
   
    while ((io_hw_sensor = IOIteratorNext(io_hw_sensors))) {
        kr = IORegistryEntryCreateCFProperties(io_hw_sensor, &sensor_properties,
                 kCFAllocatorDefault, kNilOptions);
        if (kr == KERN_SUCCESS)
            printTemperatureSensor(sensor_properties, systemEncoding);
   
        CFRelease(sensor_properties);
        IOObjectRelease(io_hw_sensor);
    }
   
    IOObjectRelease(io_hw_sensors);
   
    exit(kr);
}
Exemplo n.º 7
0
CFMutableDictionaryRef
fake_IOServiceNameMatching(
  const char *  name )
{
  CFMutableDictionaryRef ret = IOServiceNameMatching(name);
  printf("IOServiceNameMatching(name=%s) ret: %p\n", name, ret);
  return ret;
}
 virtual_hid_device_client(spdlog::logger& logger,
                           const connected_callback& connected_callback) : logger_(logger),
                                                                           connected_callback_(connected_callback),
                                                                           service_(IO_OBJECT_NULL),
                                                                           connect_(IO_OBJECT_NULL) {
   if (auto matching_dictionary = IOServiceNameMatching(pqrs::karabiner_virtual_hid_device::get_virtual_hid_root_name())) {
     service_observer_ = std::make_unique<service_observer>(logger_,
                                                            matching_dictionary,
                                                            std::bind(&virtual_hid_device_client::matched_callback, this, std::placeholders::_1),
                                                            std::bind(&virtual_hid_device_client::terminated_callback, this, std::placeholders::_1));
     CFRelease(matching_dictionary);
   }
 }
Exemplo n.º 9
0
void
setupAndRun(void)
{
    CFMutableDictionaryRef hidMatchDictionary = NULL;
    io_service_t           hidService = (io_service_t)0;
    io_object_t            hidDevice = (io_object_t)0;
    IOHIDDeviceInterface **hidDeviceInterface = NULL;
    IOReturn               ioReturnValue = kIOReturnSuccess;
    cookie_struct_t        cookies;
    
    hidMatchDictionary = IOServiceNameMatching("AppleIRController");
    hidService = IOServiceGetMatchingService(kIOMasterPortDefault,
                                             hidMatchDictionary);

    if (!hidService) {
        fprintf(stderr, "Apple Infrared Remote not found.\n");
        exit(1);
    }

    hidDevice = (io_object_t)hidService;

    createHIDDeviceInterface(hidDevice, &hidDeviceInterface);
    cookies = getHIDCookies((IOHIDDeviceInterface122 **)hidDeviceInterface);
    ioReturnValue = IOObjectRelease(hidDevice);
    print_errmsg_if_io_err(ioReturnValue, "Failed to release HID.");

    if (hidDeviceInterface == NULL) {
        fprintf(stderr, "No HID.\n");
        exit(1);
    }

    ioReturnValue = (*hidDeviceInterface)->open(hidDeviceInterface, 0);

    doRun(hidDeviceInterface, cookies);

    if (ioReturnValue == KERN_SUCCESS)
        ioReturnValue = (*hidDeviceInterface)->close(hidDeviceInterface);

    (*hidDeviceInterface)->Release(hidDeviceInterface);
}
Exemplo n.º 10
0
static void initializeDisplayNotifications (void)
{
	io_service_t		displayWrangler;
	IONotificationPortRef	notificationPort;
	io_object_t		notifier;

	displayWrangler = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching("IODisplayWrangler"));
	if (! displayWrangler) {
		message (LOG_ERR, "IOServiceGetMatchingService failed\n");
		exit (1);
	}
	notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
	if (! notificationPort) {
		message (LOG_ERR, "IONotificationPortCreate failed\n");
		exit (1);
	}
	if (IOServiceAddInterestNotification(notificationPort, displayWrangler, kIOGeneralInterest,
		displayCallback, NULL, &notifier) != kIOReturnSuccess) {
		message (LOG_ERR, "IOServiceAddInterestNotification failed\n");
		exit (1);
	}
	CFRunLoopAddSource (CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode);
	IOObjectRelease (displayWrangler);
}
/*
  Create matching dictionaries for the devices we want to get notifications for,
  and add them to the current run loop.  Invoke the callbacks that will be responding
  to these notifications once to arm them, and discover any devices that
  are currently connected at the time notifications are setup.
*/
void QextSerialEnumerator::setUpNotificationOSX( )
{
    kern_return_t kernResult;
    mach_port_t masterPort;
    CFRunLoopSourceRef notificationRunLoopSource;
    CFMutableDictionaryRef classesToMatch;
    CFMutableDictionaryRef cdcClassesToMatch;
    io_iterator_t portIterator;

    kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
    if (KERN_SUCCESS != kernResult) {
        qDebug() << "IOMasterPort returned:" << kernResult;
        return;
    }

    classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
    if (classesToMatch == NULL)
        qDebug("IOServiceMatching returned a NULL dictionary.");
    else
        CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));

    if( !(cdcClassesToMatch = IOServiceNameMatching("AppleUSBCDC") ) ) {
        qWarning("couldn't create cdc matching dict");
        return;
    }

    // Retain an additional reference since each call to IOServiceAddMatchingNotification consumes one.
    classesToMatch = (CFMutableDictionaryRef) CFRetain(classesToMatch);
    cdcClassesToMatch = (CFMutableDictionaryRef) CFRetain(cdcClassesToMatch);

    notificationPortRef = IONotificationPortCreate(masterPort);
    if(notificationPortRef == NULL) {
        qDebug("IONotificationPortCreate return a NULL IONotificationPortRef.");
        return;
    }

    notificationRunLoopSource = IONotificationPortGetRunLoopSource(notificationPortRef);
    if (notificationRunLoopSource == NULL) {
        qDebug("IONotificationPortGetRunLoopSource returned NULL CFRunLoopSourceRef.");
        return;
    }

    CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, classesToMatch,
                                                  deviceDiscoveredCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return;
    }

    // arm the callback, and grab any devices that are already connected
    deviceDiscoveredCallbackOSX( this, portIterator );

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, cdcClassesToMatch,
                                                  deviceDiscoveredCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return;
    }

    // arm the callback, and grab any devices that are already connected
    deviceDiscoveredCallbackOSX( this, portIterator );

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, classesToMatch,
                                                  deviceTerminatedCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return;
    }

    // arm the callback, and clear any devices that are terminated
    deviceTerminatedCallbackOSX( this, portIterator );

    kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, cdcClassesToMatch,
                                                  deviceTerminatedCallbackOSX, this, &portIterator);
    if (kernResult != KERN_SUCCESS) {
        qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
        return;
    }

    // arm the callback, and clear any devices that are terminated
    deviceTerminatedCallbackOSX( this, portIterator );
}
Exemplo n.º 12
0
static void get_via_generic_iokit (double *ret_charge, /* {{{ */
		double *ret_current,
		double *ret_voltage)
{
	kern_return_t   status;
	io_iterator_t   iterator;
	io_object_t     io_obj;

	CFDictionaryRef bat_root_dict;
	CFArrayRef      bat_info_arry;
	CFIndex         bat_info_arry_len;
	CFIndex         bat_info_arry_pos;
	CFDictionaryRef bat_info_dict;

	double temp_double;

	status = IOServiceGetMatchingServices (kIOMasterPortDefault,
			IOServiceNameMatching ("battery"),
			&iterator);
	if (status != kIOReturnSuccess)
	{
		DEBUG ("IOServiceGetMatchingServices failed.");
		return;
	}

	while ((io_obj = IOIteratorNext (iterator)))
	{
		status = IORegistryEntryCreateCFProperties (io_obj,
				(CFMutableDictionaryRef *) &bat_root_dict,
				kCFAllocatorDefault,
				kNilOptions);
		if (status != kIOReturnSuccess)
		{
			DEBUG ("IORegistryEntryCreateCFProperties failed.");
			continue;
		}

		bat_info_arry = (CFArrayRef) CFDictionaryGetValue (bat_root_dict,
				CFSTR ("IOBatteryInfo"));
		if (bat_info_arry == NULL)
		{
			CFRelease (bat_root_dict);
			continue;
		}
		bat_info_arry_len = CFArrayGetCount (bat_info_arry);

		for (bat_info_arry_pos = 0;
				bat_info_arry_pos < bat_info_arry_len;
				bat_info_arry_pos++)
		{
			bat_info_dict = (CFDictionaryRef) CFArrayGetValueAtIndex (bat_info_arry, bat_info_arry_pos);

			if (*ret_charge == INVALID_VALUE)
			{
				temp_double = dict_get_double (bat_info_dict,
						"Capacity");
				if (temp_double != INVALID_VALUE)
					*ret_charge = temp_double / 1000.0;
			}

			if (*ret_current == INVALID_VALUE)
			{
				temp_double = dict_get_double (bat_info_dict,
						"Current");
				if (temp_double != INVALID_VALUE)
					*ret_current = temp_double / 1000.0;
			}

			if (*ret_voltage == INVALID_VALUE)
			{
				temp_double = dict_get_double (bat_info_dict,
						"Voltage");
				if (temp_double != INVALID_VALUE)
					*ret_voltage = temp_double / 1000.0;
			}
		}
		
		CFRelease (bat_root_dict);
	}

	IOObjectRelease (iterator);
} /* }}} void get_via_generic_iokit */
Exemplo n.º 13
0
int main(int argc, const char* argv[]) {
  if (getuid() != 0) {
    std::cerr << "post_keyboard_event_example requires root privilege." << std::endl;
  }

  kern_return_t kr;
  io_connect_t connect = IO_OBJECT_NULL;
  auto service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching(pqrs::karabiner_virtual_hid_device::get_virtual_hid_root_name()));
  if (!service) {
    std::cerr << "IOServiceGetMatchingService error" << std::endl;
    goto finish;
  }

  kr = IOServiceOpen(service, mach_task_self(), kIOHIDServerConnectType, &connect);
  if (kr != KERN_SUCCESS) {
    std::cerr << "IOServiceOpen error" << std::endl;
    goto finish;
  }

  for (int i = 0; i < 12; ++i) {
    pqrs::karabiner_virtual_hid_device::keyboard_event keyboard_event;

    switch (i % 6) {
    case 0:
      keyboard_event.event_type = pqrs::karabiner_virtual_hid_device::event_type::key_down;
      keyboard_event.key = 0; // a
      break;
    case 1:
      keyboard_event.event_type = pqrs::karabiner_virtual_hid_device::event_type::key_up;
      keyboard_event.key = 0; // a
      break;
    case 2:
      keyboard_event.event_type = pqrs::karabiner_virtual_hid_device::event_type::key_down;
      keyboard_event.key = 1; // s
      break;
    case 3:
      keyboard_event.event_type = pqrs::karabiner_virtual_hid_device::event_type::key_up;
      keyboard_event.key = 1; // s
      break;
    case 4:
      keyboard_event.event_type = pqrs::karabiner_virtual_hid_device::event_type::flags_changed;
      keyboard_event.key = 0x3b; // left control
      keyboard_event.flags = 0x40001;
      break;
    case 5:
      keyboard_event.event_type = pqrs::karabiner_virtual_hid_device::event_type::flags_changed;
      keyboard_event.key = 0x3b; // left control
      keyboard_event.flags = 0;
      break;
    }

    kr = pqrs::karabiner_virtual_hid_device_methods::post_keyboard_event(connect, keyboard_event);
    if (kr != KERN_SUCCESS) {
      std::cerr << "post_keyboard_event error" << std::endl;
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(100));
  }

finish:
  if (connect) {
    IOServiceClose(connect);
  }
  if (service) {
    IOObjectRelease(service);
  }

  return 0;
}
Exemplo n.º 14
0
static int as_read (void)
{
	kern_return_t   status;
	io_iterator_t   iterator;
	io_object_t     io_obj;
	CFMutableDictionaryRef prop_dict;
	CFTypeRef       property;

	char   type[128];
	char   inst[128];
	int    value_int;
	double value_double;
	int    i;

	if (!io_master_port || (io_master_port == MACH_PORT_NULL))
		return (-1);

	status = IOServiceGetMatchingServices (io_master_port,
		       	IOServiceNameMatching("IOHWSensor"),
		       	&iterator);
	if (status != kIOReturnSuccess)
       	{
		ERROR ("IOServiceGetMatchingServices failed: %s",
				mach_error_string (status));
		return (-1);
	}

	while ((io_obj = IOIteratorNext (iterator)))
	{
		prop_dict = NULL;
		status = IORegistryEntryCreateCFProperties (io_obj,
				&prop_dict,
				kCFAllocatorDefault,
				kNilOptions);
		if (status != kIOReturnSuccess)
		{
			DEBUG ("IORegistryEntryCreateCFProperties failed: %s",
					mach_error_string (status));
			continue;
		}

		/* Copy the sensor type. */
		property = NULL;
		if (!CFDictionaryGetValueIfPresent (prop_dict,
					CFSTR ("type"),
					&property))
			continue;
		if (CFGetTypeID (property) != CFStringGetTypeID ())
			continue;
		if (!CFStringGetCString (property,
					type, sizeof (type),
					kCFStringEncodingASCII))
			continue;
		type[sizeof (type) - 1] = '\0';

		/* Copy the sensor location. This will be used as `instance'. */
		property = NULL;
		if (!CFDictionaryGetValueIfPresent (prop_dict,
					CFSTR ("location"),
					&property))
			continue;
		if (CFGetTypeID (property) != CFStringGetTypeID ())
			continue;
		if (!CFStringGetCString (property,
					inst, sizeof (inst),
					kCFStringEncodingASCII))
			continue;
		inst[sizeof (inst) - 1] = '\0';
		for (i = 0; i < 128; i++)
		{
			if (inst[i] == '\0')
				break;
			else if (isalnum (inst[i]))
				inst[i] = (char) tolower (inst[i]);
			else
				inst[i] = '_';
		}

		/* Get the actual value. Some computation, based on the `type'
		 * is neccessary. */
		property = NULL;
		if (!CFDictionaryGetValueIfPresent (prop_dict,
					CFSTR ("current-value"),
					&property))
			continue;
		if (CFGetTypeID (property) != CFNumberGetTypeID ())
			continue;
		if (!CFNumberGetValue (property,
				       	kCFNumberIntType,
				       	&value_int))
			continue;

		/* Found e.g. in the 1.5GHz PowerBooks */
		if (strcmp (type, "temperature") == 0)
		{
			value_double = ((double) value_int) / 65536.0;
			sstrncpy (type, "temperature", sizeof (type));
		}
		else if (strcmp (type, "temp") == 0)
		{
			value_double = ((double) value_int) / 10.0;
			sstrncpy (type, "temperature", sizeof (type));
		}
		else if (strcmp (type, "fanspeed") == 0)
		{
			value_double = ((double) value_int) / 65536.0;
			sstrncpy (type, "fanspeed", sizeof (type));
		}
		else if (strcmp (type, "voltage") == 0)
		{
			/* Leave this to the battery plugin. */
			continue;
		}
		else if (strcmp (type, "adc") == 0)
		{
			value_double = ((double) value_int) / 10.0;
			sstrncpy (type, "fanspeed", sizeof (type));
		}
		else
		{
			DEBUG ("apple_sensors: Read unknown sensor type: %s",
					type);
			value_double = (double) value_int;
		}

		as_submit (type, inst, value_double);

		CFRelease (prop_dict);
		IOObjectRelease (io_obj);
	} /* while (iterator) */

	IOObjectRelease (iterator);

	return (0);
} /* int as_read */
Exemplo n.º 15
0
int main(int argc, char *argv[]) {
    io_connect_t    manager_connect = IO_OBJECT_NULL;
    io_connect_t    manager[kMaxSimultaneousConnections];

    uint32_t    openfailure = 0;
    uint32_t    closefailure = 0;
    uint32_t    ucOpenedCount = 0;
    uint32_t    ucExclusiveOpenedCount = 0;
    IOReturn    connectreturn = 0;
    kern_return_t kernreturn = 0;
    CFAbsoluteTime      start_time = 0.0;
    CFAbsoluteTime      end_time = 0.0;
    CFTimeInterval      elapsed_time = 0.0;
    io_registry_entry_t IOREG_SmartBattery = IO_OBJECT_NULL;
    int                 simultaneousCount = 0;
    
    PMTestInitialize("SmartBatteryUserClient repetition test", "com.apple.iokit.smartbattery.repeater");

/* 
 * Make sure we can open a few simultaneous user clients
 */    
    for(simultaneousCount=0; simultaneousCount < kMaxSimultaneousConnections; simultaneousCount++) {
    
        manager[simultaneousCount] = connectSmartBatteryManager(0, &connectreturn);
        if (kIOReturnSuccess != connectreturn) {
            manager[simultaneousCount] = 0;
            PMTestFail("Failed to open non-exclusive user client #%d of %d. Status = 0x%08x", 
                simultaneousCount, kMaxSimultaneousConnections, connectreturn);
        } else {
            PMTestPass("Opened non-exclusive user client depth %d", simultaneousCount);
        }
    }
    
    IOREG_SmartBattery = IOServiceGetMatchingService( MACH_PORT_NULL,
                            IOServiceNameMatching(kBatteryManagerName) );
    if (IO_OBJECT_NULL == IOREG_SmartBattery) {
        PMTestLog("This machine does not support batteries. Skipping battery tests.");
        exit(0);
    }
    IOObjectRelease(IOREG_SmartBattery);
    
    for (simultaneousCount = kMaxSimultaneousConnections-1; simultaneousCount >= 0; simultaneousCount--)
    {
        if (!manager[simultaneousCount]) {
            PMTestLog("ODDITY: Trying to close connection %d - but NULL connection ID", simultaneousCount);
            continue;
        }
        connectreturn = IOServiceClose(manager[simultaneousCount]);
        if (kIOReturnSuccess != connectreturn) {
            PMTestFail("Failed to CLOSE non-exclusive user client #%d of %d. Status = 0x%08x", 
                    simultaneousCount, kMaxSimultaneousConnections, connectreturn);
        } else {
            PMTestPass("Closed user client at depth %d", simultaneousCount);
        }
    }
    
    while ( (ucOpenedCount < kUCIterationsCount) && (ucExclusiveOpenedCount < kUCExclusiveIterationsCount))
    {
/* 
 * Regular user client
 */    
        if (ucOpenedCount < kUCIterationsCount)
        {
            /* OPEN REGULAR */
            start_time = CFAbsoluteTimeGetCurrent();
            manager_connect = connectSmartBatteryManager(0, &connectreturn);
            if (MACH_PORT_NULL == manager_connect) 
            {
                PMTestFail("IOServiceOpen error 0x%08x opening %s", connectreturn, kBatteryManagerName);
                openfailure++;
            } else {
                end_time = CFAbsoluteTimeGetCurrent();
                
                elapsed_time = end_time - start_time;
                PMTestPass("User client opened successfully in %d.%02d seconds", (int)elapsed_time, (int)(100.0 * elapsed_time)%100);
                if (elapsed_time > kMaxSecondsUCOperation) {
                    PMTestFail("Error - opening user client took %d.%02d, exceeding %d.%02d", 
                                    (int)elapsed_time, (int)(100.0 * elapsed_time)%100,
                                    (int)kMaxSecondsUCOperation, (int)(100.0*kMaxSecondsUCOperation)%100);
                }
                
                /* CLOSE REGULAR */
                start_time = CFAbsoluteTimeGetCurrent();
                kernreturn = IOServiceClose(manager_connect);
                if (KERN_SUCCESS != kernreturn) {
                    PMTestFail("IOServiceClose error %d closing user client.", kernreturn);
                    closefailure++;
                } else {
                    end_time = CFAbsoluteTimeGetCurrent();
                    
                    elapsed_time = end_time - start_time;
                    PMTestPass("User client closed successfully in %d.%02d seconds", (int)elapsed_time, (int)(100.0 * elapsed_time)%100);
                    if (elapsed_time > kMaxSecondsUCOperation) {
                        PMTestFail("Error - closing user client took %d.%02d, exceeding %d.%02d", 
                                        (int)elapsed_time, (int)(100.0 * elapsed_time)%100,
                                        (int)kMaxSecondsUCOperation, (int)(100.0*kMaxSecondsUCOperation)%100);
                    }
                }
            }
            ucOpenedCount++;
        }

/*
 * Exclusive
 */
        
        if (ucExclusiveOpenedCount < kUCExclusiveIterationsCount)
        {
            /* OPEN EXCLUSIVE */
            start_time = CFAbsoluteTimeGetCurrent();
            manager_connect = connectSmartBatteryManager(kBatteryExclusiveAccessType, &connectreturn);
            if (MACH_PORT_NULL == manager_connect) 
            {
                //PMTestFail
                PMTestLog("IOServiceOpen error 0x%08x opening exclusive %s (This test requires root privileges; this may be a failure)", connectreturn, kBatteryManagerName);
                openfailure++;
            } else {
                end_time = CFAbsoluteTimeGetCurrent();
                
                elapsed_time = end_time - start_time;
                PMTestPass("User client EXCLUSIVE opened successfully in %d.%02d seconds", (int)elapsed_time, (int)(100.0 * elapsed_time)%100);
                if (elapsed_time > kMaxSecondsUCOperation) {
                    PMTestFail("Error - opening EXCLUSIVE user client took %d.%02d, exceeding %d.%02d", 
                                    (int)elapsed_time, (int)(100.0 * elapsed_time)%100,
                                    (int)kMaxSecondsUCOperation, (int)(100.0*kMaxSecondsUCOperation)%100);
                }
                /* CLOSE EXCLUSIVE */
                start_time = CFAbsoluteTimeGetCurrent();
                kernreturn = IOServiceClose(manager_connect);
                if (KERN_SUCCESS != kernreturn) {
                    PMTestFail("IOServiceClose error %d closing user client.", kernreturn);
                    closefailure++;
                } else {
                    end_time = CFAbsoluteTimeGetCurrent();
                    
                    elapsed_time = end_time - start_time;
                    PMTestPass("User client EXCLUSIVE closed successfully in %d.%02d seconds", (int)elapsed_time, (int)(100.0 * elapsed_time)%100);
                    if (elapsed_time > kMaxSecondsUCOperation) {
                        PMTestFail("Error - closing EXCLUSIVE user client took %d.%02d, exceeding %d.%02d", 
                                        (int)elapsed_time, (int)(100.0 * elapsed_time)%100,
                                        (int)kMaxSecondsUCOperation, (int)(100.0*kMaxSecondsUCOperation)%100);
                    }
                }
            }
            ucExclusiveOpenedCount++;
        }
        
    }

    PMTestLog("SmartBatteryUserClient test completed: opened %d clients and %d exclusive clients", 
                                        ucOpenedCount, ucExclusiveOpenedCount);

    if (openfailure == 0 && closefailure == 0)
    {
        PMTestLog("Success.");
    } else {
        if (openfailure) {
            PMTestLog("Test completed with %d failures opening the user client.", openfailure);
        }
        if (closefailure) {
            PMTestLog("Test completed with %d failures closing the user client.", closefailure);
        }
    }

    PMTestLog("The test is over.");

    return 0;
}
Exemplo n.º 16
0
int main(int argc, const char* argv[]) {
  if (getuid() != 0) {
    std::cerr << "virtual_keyboard_example requires root privilege." << std::endl;
  }

  kern_return_t kr;
  io_connect_t connect = IO_OBJECT_NULL;
  auto service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching(pqrs::karabiner_virtual_hid_device::get_virtual_hid_root_name()));
  if (!service) {
    std::cerr << "IOServiceGetMatchingService error" << std::endl;
    goto finish;
  }

  kr = IOServiceOpen(service, mach_task_self(), kIOHIDServerConnectType, &connect);
  if (kr != KERN_SUCCESS) {
    std::cerr << "IOServiceOpen error" << std::endl;
    goto finish;
  }

  kr = pqrs::karabiner_virtual_hid_device_methods::initialize_virtual_hid_keyboard(connect);
  if (kr != KERN_SUCCESS) {
    std::cerr << "initialize_virtual_hid_keyboard error" << std::endl;
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(100));

  for (int i = 0; i < 12; ++i) {
    pqrs::karabiner_virtual_hid_device::hid_report::keyboard_input report;
    switch (i % 6) {
    case 0:
      report.keys[0] = 0x04; // a
      break;
    case 1:
      report.keys[0] = 0x05; // b
      break;
    case 2:
      report.keys[0] = 0x06; // c
      break;
    case 3:
      report.keys[0] = 0x07; // d
      break;
    case 4:
      report.keys[0] = 0x08; // e
      break;
    case 5:
      // Send empty report
      break;
    }

    kr = pqrs::karabiner_virtual_hid_device_methods::post_keyboard_input_report(connect, report);
    if (kr != KERN_SUCCESS) {
      std::cerr << "post_keyboard_input_report error" << std::endl;
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(100));
  }

  kr = pqrs::karabiner_virtual_hid_device_methods::reset_virtual_hid_keyboard(connect);
  if (kr != KERN_SUCCESS) {
    std::cerr << "reset_virtual_hid_keyboard error" << std::endl;
  }

finish:
  if (connect) {
    IOServiceClose(connect);
  }
  if (service) {
    IOObjectRelease(service);
  }

  return 0;
}