// // HostScanner.m // Sensornet // // Created by Chris Karr on 9/22/08. // Copyright 2008 Northwestern University. All rights reserved. // #import "HostScanner.h" #define HOSTNAME @"Hostname" #define PORT @"Port" #define VISIBLE @"Visible" #define ENABLED @"Enabled" #define KEY @"Key" #define COLOR @"Color" @implementation HostScanner - (NSString *) machineName { CFStringRef nameRef; NSString * computerName; nameRef = CSCopyMachineName (); computerName = [NSString stringWithString:(NSString *) nameRef]; CFRelease (nameRef); return computerName; } - (void) awakeFromNib { NSTimer * timer = [[NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(update:) userInfo:nil repeats:YES] retain]; [timer fire]; } - (void) update:(NSTimer *) theTimer { NSNetServiceBrowser * bonjour = [[NSNetServiceBrowser alloc] init]; [bonjour setDelegate:self]; for (NSMutableDictionary * host in [hosts arrangedObjects]) { [host setValue:[NSNumber numberWithBool:NO] forKey:VISIBLE]; [host setObject:[NSArchiver archivedDataWithRootObject:[NSColor redColor]] forKey:COLOR]; } [bonjour searchForServicesOfType:@"_pennyworth._tcp." inDomain:@"local"]; } - (void) netServiceBrowser:(NSNetServiceBrowser *) netServiceBrowser didFindService:(NSNetService *) netService moreComing:(BOOL) moreServicesComing { [netService retain]; [netService setDelegate:self]; [netService resolveWithTimeout:1.0]; if (!moreServicesComing) [netServiceBrowser release]; } - (void) netServiceDidResolveAddress:(NSNetService *) netService { NSMutableDictionary * hostDict = [NSMutableDictionary dictionary]; [hostDict setValue:[netService hostName] forKey:HOSTNAME]; [hostDict setValue:[NSNumber numberWithInt:[netService port]] forKey:PORT]; [hostDict setValue:[NSNumber numberWithBool:YES] forKey:VISIBLE]; [hostDict setObject:@"" forKey:KEY]; [hostDict setObject:[NSNumber numberWithBool:NO] forKey:ENABLED]; [hostDict setObject:[NSArchiver archivedDataWithRootObject:[NSColor blackColor]] forKey:COLOR]; BOOL found = NO; for (NSMutableDictionary * host in [hosts arrangedObjects]) { if ([[host valueForKey:HOSTNAME] isEqual:[hostDict valueForKey:HOSTNAME]] && [[host valueForKey:PORT] isEqual:[hostDict valueForKey:PORT]]) { found = YES; [host setValue:[NSNumber numberWithBool:YES] forKey:VISIBLE]; [host setObject:[NSArchiver archivedDataWithRootObject:[NSColor blackColor]] forKey:COLOR]; } } if (!found) [hosts addObject:hostDict]; [netService release]; } @end