Racing Robots Session

Dependencies:   m3pi mbed

Fork of racing_robots by Nico De Witte

xbee.cpp

Committer:
sillevl
Date:
2015-06-03
Revision:
10:c67825bf5f6b
Parent:
8:597ce8a7d34b

File content as of revision 10:c67825bf5f6b:

#include "xbee.h"
#include "MbedJSONValue.h"

Xbee::Xbee(PinName tx, PinName rx){
    xbee = new Serial(tx, rx);
    xbee->baud(115200);
    xbee->attach(this, &Xbee::received, Serial::RxIrq);
    run = false;
    printf("xbee constructor\r\n");
    rst = new DigitalOut(p26);
    reset();
    setCode(-1);
}

void Xbee::reset(){
    rst->write(0);
    wait_ms(1);
    rst->write(1);
    wait_ms(1);
}

void Xbee::setCode(int code){
    if( code < 0 && code >= 1000){
        error("Code must be between 0 and 999."); 
    }   
    this->code = code;
}

int Xbee::hasCode(){
    return code != -1;
}

int Xbee::running(){
    return run;
}

int Xbee::stopped(){
    return !running();
}

void Xbee::received(){
    char c;
    while(xbee->readable()){
        c = xbee->getc();
        putc(c, stdout);
        buffer[buffer_pos] = c;
        buffer_pos++;
        if(c == '\n'){
            buffer[buffer_pos] = '\0';
            
            printf("buffer: %s\r\n", buffer);

            buffer_pos = 0;
            MbedJSONValue json;
            parse(json, buffer);
            
            int code = -1;
            if(json.hasMember("start")){
                code = json["start"].get<int>();
            } else if(json.hasMember("stop")){
                code = json["stop"].get<int>();
            } else {
                break;   
            }
            
            printf("code: %d\r\n", code);

            if(json.hasMember("start") && code == this->code){
                run = true;   
                printf("start\r\n");
            } else if(code == this->code){
                run = false;
                printf("stop\r\n");
            }   
        }
    }
}