#import <Foundation/Foundation.h>
#import <CoreMIDI/CoreMIDI.h>

NSString *getName(MIDIObjectRef object)
{
    // Returns the name of a given MIDIObjectRef as an NSString
    CFStringRef name = nil;
    if (noErr != MIDIObjectGetStringProperty(object, kMIDIPropertyName, &name))
        return nil;
    return (__bridge NSString *)name;
}

int main(int argc, char *argv[])
{
    while(true){
        sleep(2);
        // How many MIDI devices do we have?
        ItemCount deviceCount = MIDIGetNumberOfSources();
        
        NSLog(@"Number of source devices: %lu", deviceCount);
        // Iterate through all MIDI devices
        for (ItemCount i = 0 ; i < deviceCount ; ++i) {
            
            // Grab a reference to current device
            MIDIDeviceRef device = MIDIGetSource(i);
            NSLog(@"Device: %@", getName(device));
            
            // Is this device online? (Currently connected?)
            SInt32 isOffline = 0;
            MIDIObjectGetIntegerProperty(device, kMIDIPropertyOffline, &isOffline);
            NSLog(@"Device is online: %s", (isOffline ? "No" : "Yes"));
            
            NSLog(@"------");
        }
    }
}