DA14580 Bluetooth Smart IC writer library

Dependents:   11u35_usbLocalFilesystem

DA14580.cpp

Committer:
k4zuki
Date:
2016-03-04
Revision:
6:db0ae78150a3
Parent:
5:45e9f3723a08
Child:
7:5f0fe36be5b3

File content as of revision 6:db0ae78150a3:

/*
@file DA14580.cpp
*/
//#include "mbed.h"
#include "DA14580.h"

DA14580::DA14580( PinName TX, PinName RX, PinName RESET ) : _ble(TX,RX), _reset(RESET)
{
    _ble.baud(57600);
    init();
}

DA14580::DA14580( RawSerial &ble, PinName RESET ) : _ble(ble), _reset(RESET)
{
    _ble.baud(57600);
    init();
}

DA14580::~DA14580()
{
}

void DA14580::init()
{

    _crc = 0x00;
    _recieve = 0;
    _read = 0;
    _filesize = 0;
    _reset.write(_RESET);
    _timeout = _TIMEOUT;
    _status = SUCCESS;
}

int DA14580::load()
{

    _status = SUCCESS;
    _fp = fopen(TARGET_FILE, "rb" );
    if (_fp) {
        _filesize = file_size(_fp);
    } else {
        _status = E_FILE_NOT_FOUND;
    }
    if(_status == SUCCESS) {
        _reset.write(_BOOT);
        wait_us(1);
        while(1) {
            while( _ble.readable() ) {
                _recieve = _ble.getc();
            }
            if(_recieve == STX) {
                _ble.putc(SOH);
                _ble.putc(_filesize & 0xff);
                _ble.putc( (_filesize >> 8) & 0xff);
                break;
            }
        }

        while(1) {
            _recieve = _ble.getc();
            if(_recieve == ACK) {
                break;
            } else {
                _status = E_ACK_NOT_RETURNED;
                break;
            }
        }

        if(_status == SUCCESS) {
            for(int i = 0; i < _filesize; i++) {
                _read = getc(_fp);
                _ble.putc(_read);
                _crc = _crc ^ _read;
            }
            while(1) {
                _recieve = _ble.getc();
                if(_recieve == _crc) {
                    _ble.putc(ACK);
                    break;
                } else {
                    _status = E_CRC_MISMATCH;
                    break;
                }
            }
        }
    }
    fclose(_fp);
#if defined(__MICROLIB) && defined(__ARMCC_VERSION) // with microlib and ARM compiler
#warning "free(_fp)"
    free(_fp);
#endif
    return _status;

}

int DA14580::file_size( FILE *fp )
{
    int     size;

    fseek( fp, 0, SEEK_END ); // seek to end of file
    size    = ftell( fp );    // get current file pointer
    fseek( fp, 0, SEEK_SET ); // seek back to beginning of file

    return size;
}