Bender Robotics / Mbed 2 deprecated PLAUCI_full

Dependencies:   FatFileSystemCpp mbed PowerControl USBHostLite

wifi.cpp

Committer:
legwinskij
Date:
2015-10-22
Revision:
15:baa2672a9b38
Parent:
12:e3cb430ec051
Child:
17:ca53e6d36163

File content as of revision 15:baa2672a9b38:

#include "wifi.h"
#include "utils.h"

#define BAUDR 1100000
#define SEND_SIZE 1024

Wifi::Wifi (PinName tx, PinName rx, PinName rts, PinName cts, PinName reset): 
        wifi_(tx, rx) {    
    wifi_.set_flow_control(SerialBase::RTSCTS, rts, cts);
    wifi_.baud(BAUDR);
}

/*
* Format: (int) -1 (int) -1 (int) swimmer_id
*   many times (int) count 3*(short) acc 3*(float)gyro
*         (int) -1 (int) -1    up to 1023 zeros   
*/
//int Wifi::sendFile(const char *fname, int swimmer_id)
int Wifi::sendFile(FILE *file, const char *fname, int swimmer_id)
{
    char c;
    int last = 1;

    //FILE *f = fopen(fname, "rb");
    freopen(fname, "rb", file);
    if (file == NULL) {
        printf("\r\nUnable to open %s", fname);
        return -1;
    }
    in_buf = 0;
    while (fread(&c, sizeof(char), 1, file) != 0) {
        if ((last = bufferSendVerify(c)) == -1) {
            fclose(file);
            return -1;
        }
    }

    //fill the last data to SEND_SIZE with zeros
    if (last == 1) {
        while (bufferSendVerify(0x00) != 0)
            ;    
    }

    fclose(file); 
    return 0;
}

/*
 * Returns 0 if no command was recieved
 * or the command
 */
char Wifi::getCmd(void)
{
    // Needs to be done properly
    //if (wifi_.readable() || wifi_.getc() == '#');
    if (wifi_.readable() && wifi_.getc() == '#')
    {
        wifi_.putc('#');
        wifi_.putc('A');
        return wifi_.getc();
    }
    else
    {
        return 'N';
    }
}

/* ********************************
 * private
 * *******************************/
void Wifi::bufferSend(char *buffer, size_t size)
{
    int i;
    for (i = 0; i < size; i++) {
        wifi_.putc(buffer[i]);
    }
}

int Wifi::bufferSendVerify(char c)
{
    static char buffer[SEND_SIZE];
    int counter = 0;
    
    buffer[in_buf] = c;
    in_buf++;
        
    if (in_buf != SEND_SIZE)
        return 1;
    
    in_buf = 0;
    while (counter++ < 10) {
        bufferSend(buffer, SEND_SIZE);
        
        while (!wifi_.readable())
            ;
        if (wifi_.getc() == 'A')
            break;
    }
    if (counter >= 10)
        return -1;
    return 0;
}