//
//  main.c
//  BrainStem2Example
//
//  Created by Acroname Inc. on 1/16/15.
//  Copyright (c) 2015 Acroname Inc. All rights reserved.
//

#include "BrainStem2/BrainStem-C.h" //aTime_MSSleep
#include "BrainStem2_CCA/CCA_All.h"
#include <stdio.h>      // standard input / output functions

#define SYSTEM_INDEX (0U)

int main(int argc, const char * argv[]) {
    
    unsigned int id = 0; //Stem ID. Will be assigned by the module_createStem call.
    struct Result result;
    
    //- If autoNetworking is True then moduleAddress has no meaning. Set it to 0
    //- If model is set and the serial number in discoverAndConnect is 0 then
    //  connection will only occur if the model matches the one provided.
    //  We use 0 here for simplicity.
    module_createStem(&id, &result, 0, true, 0);
    
    //- linkType of 1 is used for USB.
    //- If serialNumber = 0 a connection will be made to the first device that is
    //  found which has a matching model (unless model is 0).
    //- Special care should be taken when working with multiple stems to ensure
    //  you are connected to the one you expect.
    module_discoverAndConnect(&id, &result, 1, 0);
    if(result.error) {
        printf("Error trying to connect - Error: %d\n", result.error);
        return 1;
    }
    
    system_getSerialNumber(&id, &result, SYSTEM_INDEX);
    if(aErrNone == result.error) {
        printf("Serial Number: 0x%08X\n", result.value);
    }
    
    printf("Toggling the user LED\n");
    static const uint8_t TOGGLES = 10;
    for(uint8_t x = 0; x < TOGGLES; x++) {
        system_getLED(&id, &result, 0);
        if(aErrNone == result.error ) {
            printf("Loop: %d/%d - Current LED State: %d - Changing to %d\n", x+1, TOGGLES, result.value, !result.value);
        }
        
        system_setLED(&id, &result, SYSTEM_INDEX, !result.value);
        
        aTime_MSSleep(1000);
    }
    
    system_getInputVoltage(&id, &result, 0);
    if(aErrNone == result.error) {
        printf("System Voltage: %.2fVDC\n", result.value/1000000.0);
    }
    
    //Disconnect and cleanup memory.
    module_disconnectAndDestroyStem(&id, &result);
    
    return 0;
}


