1
0
Fork 0
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ddwrt_monitor/DDWRT_MonitorAppDelegate.m

497 lines
14 KiB

//
// DDWRT_MonitorAppDelegate.m
// DDWRT-Monitor
//
// Created by Matthieu Lalonde on 11-05-27.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "DDWRT_MonitorAppDelegate.h"
@implementation DDWRT_MonitorAppDelegate
//@synthesize window;
//- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
- (void) awakeFromNib
{
// Insert code here to initialize your application
[self showMenubar];
_wrtReachable = false;
defaults = [NSUserDefaults standardUserDefaults];
// check if the app is configured yet
if (![defaults boolForKey:@"configured"])
{
[self initDefaults];
}
NSLog(@"Reading defaults...");
[self readDefaults];
// initialize the client
wrt_client = [[WRTStatusClient alloc] initWithHostname:hostname port:port username:username password:password];
//_readTimer = [NSTimer scheduledTimerWithTimeInterval:[[NSUserDefaults standardUserDefaults] integerForKey:@"refreshTime"] target:self selector:@selector(updateThroughput:) userInfo:nil repeats:YES];
//[_readTimer fire];
[self updateThroughput];
//WRTRequest *wrtr = [[WRTRequest alloc] init];
//[wrtr doRequest:self requestSelector:@selector(doUpdateStatus:) uri:@"Status_Router.live.asp"];
}
- (void) dealloc {
//[_readTimer invalidate];
[AppMenu release];
[_appMenu release];
[ConfigPanel release];
[BandwidthViewer release];
[modalWindow release];
[super dealloc];
}
- (void) initDefaults
{
NSLog(@"Creating new user defaults");
// do any other initialization you want to do here - e.g. the starting default values.
[defaults setValue:@"192.168.1.1" forKey:@"hostname"];
[defaults setInteger:80 forKey:@"port"];
[defaults setValue:@"" forKey:@"username"];
[defaults setValue:@"" forKey:@"password"];
[defaults setBool:YES forKey:@"showMenuIcon"];
[defaults setBool:YES forKey:@"useBytes"];
[defaults setInteger:4 forKey:@"refreshTime"];
// sync the defaults to disk
//[defaults registerDefaults:appDefaults];
[defaults synchronize];
// TODO: Add modal alert "First launch" here...
[self showConfigPanel:self];
}
- (void) readDefaults
{
hostname = [defaults valueForKey:@"hostname"];
port = [defaults integerForKey:@"port"];
username = [defaults valueForKey:@"username"];
password = [defaults valueForKey:@"password"];
showMenuIcon = [defaults boolForKey:@"showMenuIcon"];
useBytes = [defaults boolForKey:@"useBytes"];
refreshTime = [defaults integerForKey:@"refreshTime"];
}
- (void) terminate:(id)sender {
[[NSUserDefaults standardUserDefaults] synchronize];
[self dealloc];
[[NSApplication sharedApplication] terminate:self];
}
- (void) showMenubar
{
NSLog(@"Showing Menu Item");
NSStatusBar* bar = [NSStatusBar systemStatusBar];
_appMenu = [bar statusItemWithLength:NSVariableStatusItemLength];
[_appMenu retain];
//[self setMenubarText:@"000KB/s\n000KB/s"];
//BOOL showIcon = [[NSUserDefaults standardUserDefaults] boolForKey:@"showMenuIcon"];
//if (showIcon == true) {
[self showMenubarIcon:false];
//}
[_appMenu setHighlightMode:YES];
[_appMenu setMenu:AppMenu];
}
- (void) hideMenubar
{
[_appMenu release];
_appMenu = nil;
[AppMenu release];
AppMenu = nil;
}
- (void) showMenubarIcon:(BOOL)enabled
{
NSImage* icon = [NSImage imageNamed:(enabled == true ? @"MenuIcon" : @"MenuIconDisabled")];
[_appMenu setImage:icon];
[_appMenu setAlternateImage:nil];
[icon release];
}
- (void) hideMenubarIcon
{
[_appMenu setImage:nil];
[_appMenu setAlternateImage:nil];
}
- (void) setMenubarText:(NSString *)menubarText
{
// Todo set proper line height
NSFontManager *fontManager = [NSFontManager sharedFontManager];
NSFont *menuFont = [fontManager fontWithFamily:@"Lucida Grande" traits:NSBoldFontMask weight:10 size:8];
NSDictionary *titleAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:menuFont, NSFontAttributeName,
[NSColor blackColor], NSForegroundColorAttributeName, nil];
NSAttributedString *menuTitle = [[NSAttributedString alloc] initWithString:menubarText attributes:titleAttributes];
[_appMenu setAttributedTitle:menuTitle];
[fontManager release];
[menuFont release];
[menuTitle release];
}
- (void) showConfigPanel:(id)sender
{
[configFieldShowIcon setState:([[NSUserDefaults standardUserDefaults] boolForKey:@"showMenuIcon"] ? 1 : 0)];
[configFieldUseBytes setState:([[NSUserDefaults standardUserDefaults] boolForKey:@"useBytes"] ? 1 : 0)];
NSString *hostname = [[NSUserDefaults standardUserDefaults] stringForKey:@"hostname"];
if (hostname != nil) {
[configFieldHostname setStringValue:hostname];
}
[configFieldPort setIntValue:[[NSUserDefaults standardUserDefaults] integerForKey:@"port"]];
[configFieldRefresh setIntegerValue:[[NSUserDefaults standardUserDefaults] integerForKey:@"refreshTime"]];
[configLabelRefresh setStringValue:[NSString stringWithFormat:@"%d s", ([[NSUserDefaults standardUserDefaults] integerForKey:@"refreshTime"] + 1)]];
[ConfigPanel makeKeyAndOrderFront:nil];
}
- (void) hideConfigPanel:(id)sender
{
NSString *hostname = [[NSUserDefaults standardUserDefaults] stringForKey:@"hostname"];
if (hostname == nil && [[sender title] isEqualToString:@"Cancel"]) {
// TODO: Add modal alert "will quit if not configured"
[self terminate:nil];
}
[ConfigPanel orderOut:nil];
}
- (void) showBandwidthViewer:(id)sender
{
// NSString *urlAddress = [NSString stringWithFormat:@"https://%@:%d/graph_if.svg?ppp1",
// [[NSUserDefaults standardUserDefaults] stringForKey:@"hostname"],
// [[NSUserDefaults standardUserDefaults] integerForKey:@"port"]];
// NSLog(@"%@", urlAddress);
//
[BandwidthViewer makeKeyAndOrderFront:nil];
NSURLRequest *request = [[wrt_client requestForBandwidthViewerForInterface:@"vlan2"] retain];
[ [BandwidthViewerWebView mainFrame] loadRequest: request ];
}
- (void) hideBandwidthViewer:(id)sender
{
[BandwidthViewer orderOut:nil];
}
- (void) setConfigHostname:(id)sender
{
NSLog(@"%@", [sender title]);
}
- (IBAction) setConfigProtocol:(id)sender
{
NSLog(@"%@", [sender title]);
if ([sender state] == NSOnState) {
NSLog(@"Yes");
//NSLog(@"%s", [sender title]);
} else {
NSLog(@"No");
//NSLog(@"%s", [sender title]);
}
}
- (void) setConfigPort:(id)sender
{
}
- (void) setConfigRefresh:(id)sender
{
[configLabelRefresh setStringValue:[NSString stringWithFormat:@"%u s", ([sender integerValue] + 1)]];
}
- (void) setConfigWan:(id)sender
{
}
- (void) setConfigBytes:(id)sender
{
}
- (void) setConfigIcon:(id)sender
{
}
- (void) saveConfig:(id)sender
{
[configStateStatus startAnimation:nil];
[configStateStatus setHidden:false];
//WRTRequest *wrtr = [[WRTRequest alloc] init];
//[wrtr doRequest:self requestSelector:@selector(configSaveRequestCallback:) uri:@"Status_Router.live.asp"];
}
-(NSString *)getKey:(NSString *)stringData key:(NSString *)key
{
NSString *keyString = [NSString stringWithFormat:@"%@::", key];
NSString *returnData;
NSRange formatValid = [stringData rangeOfString:@"}"];
if (formatValid.location != NSNotFound) {
NSRange startRange = [stringData rangeOfString:keyString];
if (startRange.location != NSNotFound) {
returnData = [NSString stringWithString:stringData];
returnData = [returnData substringFromIndex:(startRange.location + [keyString length])];
returnData = [returnData substringToIndex:[returnData rangeOfString:@"}"].location];
}
returnData = [returnData stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
//[keyString release];
return returnData;
}
-(void)configSaveRequestCallback:(NSData *)data
{
// TODO check that the request is actually successful
NSString *hostname = [configFieldHostname stringValue];
[[NSUserDefaults standardUserDefaults] setObject:hostname forKey:@"hostname"];
NSString *port = [configFieldPort stringValue];
[[NSUserDefaults standardUserDefaults] setObject:port forKey:@"port"];
NSLog(@"Got %@", hostname);
//NSLog(@"%@", [configFieldProtocol str]);
[[NSUserDefaults standardUserDefaults] setInteger:[configFieldRefresh integerValue] forKey:@"refreshTime"];
[[NSUserDefaults standardUserDefaults] setBool:([configFieldUseBytes state] == 1 ? true: false) forKey:@"useBytes"];
if ([configFieldShowIcon state] == NSOffState && [[NSUserDefaults standardUserDefaults] boolForKey:@"showMenuIcon"] == true) {
[self hideMenubarIcon];
} else if ([configFieldShowIcon state] == NSOnState && [[NSUserDefaults standardUserDefaults] boolForKey:@"showMenuIcon"] == false) {
[self showMenubarIcon:false];
}
[[NSUserDefaults standardUserDefaults] setBool:([configFieldShowIcon state] == 1 ? true: false) forKey:@"showMenuIcon"];
[configStateStatus stopAnimation:nil];
[configStateStatus setHidden:true];
[self doUpdateStatus:data];
[self hideConfigPanel:nil];
}
- (void) updateThroughput
{
//WRTRequest *wrtr = [[WRTRequest alloc] init];
//[wrtr doRequest:self requestSelector:@selector(throughputCallback:) uri:@"fetchif.cgi?ppp1"];
}
- (void) throughputCallback:(NSData *)data
{
NSDate *start = [NSDate date];
NSTimeInterval timeInterval = [start timeIntervalSinceNow];
NSLog(@"%f", timeInterval);
NSString *stringData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
stringData = [stringData substringFromIndex:([stringData rangeOfString:@":"].location + 1)];
NSArray *listItems = [stringData componentsSeparatedByString:@" "];
NSLog(@"%@", [listItems objectAtIndex:0]);
unsigned long long ifIn = [NSNumber numberWithString:[listItems objectAtIndex:0]];
unsigned long long ifOut = [NSNumber numberWithString:[listItems objectAtIndex:8]];
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
}
-(void)doUpdateStatus:(NSData *)data
{
NSString *stringData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSString *ipconn = [self getKey:stringData key:@"ip_conntrack"];
NSString *wanip = [self getKey:stringData key:@"ipinfo"];
wanip = [wanip substringFromIndex:([wanip rangeOfString:@" "].location+1)];
NSString *uptime = [self getKey:stringData key:@"uptime"];
NSString *loadSplit = @", load average: ";
NSString *load = [uptime substringFromIndex:[uptime rangeOfString:loadSplit].location+[loadSplit length]];
uptime = [uptime substringToIndex:[uptime rangeOfString:@", load"].location]; // Cut the load
uptime = [uptime substringFromIndex:[uptime rangeOfString:@" "].location+1]; // Trim
uptime = [uptime stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[uptime substringToIndex:1] uppercaseString]]; // UCFirst
[menuWanIP setTitle:wanip];
[menuUptime setTitle:uptime];
[menuLoad setTitle:load];
[menuLoad setHidden:false];
[menuConnections setTitle:[NSString stringWithFormat:@"Connections: %@", ipconn]];
}
- (void) refreshMenu:(id)sender
{
}
- (void) refreshSystemMenu:(id)sender
{
}
- (void) refreshWanMenu:(id)sender
{
NSLog(@"Refreshing Wan Menu");
//WRTRequest *wrtr = [[WRTRequest alloc] init];
//[wrtr doRequest:self requestSelector:@selector(wanRequestCallback:) uri:@"Status_Internet.live.asp"];
}
- (void) wanRequestCallback:(NSData *)data
{
NSString *stringData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSString *wanStatus = [self getKey:stringData key:@"wan_status"];
NSString *wanName = [self getKey:stringData key:@"wan_shortproto"];
if ([wanName isEqualToString:@"pppoe"] == true) {
wanName = @"PPPoE";
} else if ([wanName isEqualToString:@"static"] == true) {
wanName = @"Static";
} else {
wanName = [wanName uppercaseString];
}
wanStatus = [wanStatus substringToIndex:[wanStatus rangeOfString:@"&"].location];
[menuWanStatus setTitle:[NSString stringWithFormat:@"%@ %@", wanName, wanStatus]];
if ([_appMenu image] != nil) {
[self showMenubarIcon:[wanStatus isEqualToString:@"Connected"]];
}
NSString *wanUptime = [self getKey:stringData key:@"wan_uptime"];
if ([wanStatus isEqualToString:@"Connected"] == true) {
[menuWanUptime setTitle:wanUptime];
[menuWanUptime setHidden:false];
[menuWanSeparator setHidden:false];
[menuWanBandwidthGraph setEnabled:true];
[menuWanTrafficIn setHidden:false];
[menuWanTrafficOut setHidden:false];
} else {
[menuWanUptime setHidden:true];
[menuWanSeparator setHidden:true];
[menuWanBandwidthGraph setEnabled:false];
[menuWanTrafficIn setHidden:true];
[menuWanTrafficOut setHidden:true];
}
NSString *trafficIn = [self getKey:stringData key:@"ttraff_in"];
NSString *trafficOut = [self getKey:stringData key:@"ttraff_out"];
trafficIn = [self stringFromFileSize:([trafficIn longLongValue] * 1024 * 1024)];
trafficOut = [self stringFromFileSize:([trafficOut longLongValue] * 1024 * 1024)];
[menuWanTrafficIn setTitle:[NSString stringWithFormat:@"In: %@", trafficIn]];
[menuWanTrafficOut setTitle:[NSString stringWithFormat:@"Out: %@", trafficOut]];
NSString *wanDNS0 = [self getKey:stringData key:@"wan_dns0"];
NSString *wanDNS1 = [self getKey:stringData key:@"wan_dns1"];
NSString *wanDNS2 = [self getKey:stringData key:@"wan_dns2"];
if ([wanDNS0 length] > 0) {
[menuWanDNS setEnabled:true];
[menuWanDNSItem0 setTitle: wanDNS0];
[menuWanDNSItem0 setHidden:false];
}
if ([wanDNS1 length] > 0) {
[menuWanDNS setEnabled:true];
[menuWanDNSItem1 setTitle: wanDNS1];
[menuWanDNSItem1 setHidden:false];
}
if ([wanDNS2 length] > 0) {
[menuWanDNS setEnabled:true];
[menuWanDNSItem2 setTitle: wanDNS2];
[menuWanDNSItem2 setHidden:false];
}
[stringData release];
}
- (void) refreshClientsMenu:(id)sender
{
[self updateThroughput];
}
- (NSString *) stringFromFileSize:(unsigned long long)theSize
{
double floatSize = theSize;
if (theSize<1023)
return([NSString stringWithFormat:@"%qx bytes",theSize]);
floatSize = floatSize / 1024;
if (floatSize<1023)
return([NSString stringWithFormat:@"%1.1f KiB",floatSize]);
floatSize = floatSize / 1024;
if (floatSize<1023)
return([NSString stringWithFormat:@"%1.1f MiB",floatSize]);
floatSize = floatSize / 1024;
if (floatSize<1023)
return([NSString stringWithFormat:@"%1.1f GiB",floatSize]);
floatSize = floatSize / 1024;
return([NSString stringWithFormat:@"%1.1f TiB",floatSize]);
}
- (void) connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSLog(@"Delegate Received: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
@end