//
//  ViewController.m
//  IOSArduino
//
//  Autor: Martin Evans, 21/01/2012.
//  Copyright (c) 2012 __MyCompanyName__. Wszelkie prawa zastrzeżone
//

#import "ViewController.h"

@implementation ViewController
@synthesize distance;
@synthesize moveSlider;
@synthesize toggleSwitch;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Zwolnienie wszystkich nie używanych podręcznych danych, obrazów, itp.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	rscMgr = [[RscMgr alloc] init];//#1
    [rscMgr setDelegate:self];//#2
}

- (void)viewDidUnload
{
    [self setToggleSwitch:nil];
    [self setMoveSlider:nil];
    [self setDistance:nil];
    [super viewDidUnload];
    // Zwolnienie wszystkich zachowanych podwidoków głównego widoku
    // np. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Zwrócenie YES dla obsługiwanych orientacji
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}


- (IBAction)toggleLED:(id)sender {
    txBuffer[0] = [sender tag];
    txBuffer[1] = [(UISwitch *)sender isOn];
    [rscMgr write:txBuffer Length:2]; 
    
}

- (IBAction) brightnessLED:(id)sender {
    
    int brightness = (int)[(UISlider *)sender value];
    txBuffer[0] = [sender tag];
    txBuffer[1] = brightness;
    [rscMgr write:txBuffer Length:2];    
}



#pragma mark - metody RscMgrDelegate

- (void) cableConnected:(NSString *)protocol {
    [rscMgr setBaud:9600];
    [rscMgr open];
}

- (void) cableDisconnected {
    
}

- (void) portStatusChanged {
    
}

- (void) readBytesAvailable:(UInt32)numBytes {
    NSString *string = nil;
    [rscMgr read:rxBuffer Length:numBytes];
    for (int i=0; i < numBytes; ++i){
        if (string) {
            string = [NSString stringWithFormat:@"%@%c", string, rxBuffer[i]];
        } else {
            string = [NSString stringWithFormat:@"%c", rxBuffer[i]];
        }
       self.distance.text = string;
    }
        
}
        

- (BOOL) rscMessageReceived:(UInt8 *)msg TotalLength:(int)len {
    return NO;
}

- (void) didReceivePortConfig {
}

- (IBAction)switchOnOff:(id)sender {
}
- (IBAction)controlSlider:(id)sender {
}
@end
