Last active
May 12, 2017 11:40
-
-
Save nuald/6b256aab4e4be3b6e0239809f67d00db to your computer and use it in GitHub Desktop.
Waiting for the named USB device in macos.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def APPLICATION_GROUP = 'Application' | |
ext { | |
device = 'Cruzer' | |
program = 'wait' | |
} | |
task compile(type: Exec) { | |
group APPLICATION_GROUP | |
description 'Compiles the native program.' | |
def src = 'wait.c' | |
inputs.files src | |
outputs.files program | |
commandLine 'clang', '-framework', 'IOKit', src, '-o', program | |
} | |
task runSimple(type: Exec, dependsOn: compile) { | |
group APPLICATION_GROUP | |
description 'Waits for the device.' | |
commandLine "./$program", device | |
} | |
task run(type: Exec, dependsOn: compile) { | |
group APPLICATION_GROUP | |
description 'Waits for the device using the line-buffered mode.' | |
commandLine 'script', '-q', '/dev/null', "./$program", device | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <IOKit/IOKitLib.h> | |
#include <IOKit/usb/IOUSBLib.h> | |
int main(int argc, const char *argv[]) { | |
if (argc < 2) { | |
printf("Please specify the device name.\n"); | |
return 1; | |
} | |
const char* requiredName = argv[1]; | |
size_t length = strlen(requiredName); | |
printf("Waiting for %s\n", requiredName); | |
CFMutableDictionaryRef matchingDict; | |
bool found = false; | |
while (!found && (matchingDict = IOServiceMatching(kIOUSBDeviceClassName))) { | |
io_iterator_t iter; | |
io_service_t device; | |
bool iterIsValid = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter) == KERN_SUCCESS; | |
unsigned counter = 0; | |
while (!found && iterIsValid && (device = IOIteratorNext(iter))) { | |
io_name_t devName; | |
counter++; | |
bool nameIsValid = IORegistryEntryGetName(device, devName) == KERN_SUCCESS; | |
found = nameIsValid && !strncmp(devName, requiredName, length); | |
IOObjectRelease(device); | |
} | |
printf("Got %d connected devices. %s\n", counter, found ? "Found!" : "Still waiting..."); | |
iterIsValid && IOObjectRelease(iter); | |
!found && sleep(1); | |
} | |
return !found; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment