/*
 * slip_hal.cpp
 *
 *  Created on: 1 нояб. 2018 г.
  *      Author: alexrayne <alexraynepe196@gmail.com>
  ------------------------------------------------------------------------
    Copyright (c) alexrayne

   All rights reserved.
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
   - Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
   - Neither the name of ARM nor the names of its contributors may be used
     to endorse or promote products derived from this software without
     specific prior written permission.
   *
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE. *
  ------------------------------------------------------------------------
 * */
#include <cassert>
#include <string.h>
#include <OsTime.h>
#include "slip_hal.h"

SLIP_Device::SLIP_Device(SLIP_Device::io_t* aio)
: rx( (aio)? &(aio->rx) : NULL )
{
    _io = aio;
    aio->handle_rx_over(rx_over_event, this);
}

void SLIP_Device::init(){
    rx.reset();
}


bool SLIP_Device::put_frame(){
    return io()->putChar(slip_t::END) == 1;
}

bool SLIP_Device::put_frame( const void* str, unsigned len ){
    io_t::GuardPut io_guard(io());
    if (put_frame())
    if (putData(str, len) == len)
    if (put_frame())
        return true;
    return false;
}

PTResult SLIP_Device::wait_frame(unsigned to){
    if (have_frame() >= 0){
        if (ostimeout_active(&wait_to))
            ostimeout_stop(&wait_to);
        return ptOK;
    }
    if (!ostimeout_active(&wait_to)){
        // перед запуском таймаута, пропарсю текущее содержимое буффера
        if ( rx.on_receive_refresh() > 0)
            return ptOK;
        ostimeout_init(&wait_to, to);
    }
    while ( !ostimeout_expired(&wait_to) ){
        PTResult res = io()->rx_wait(ostimeout_least(&wait_to));
        if ( PT_SCHEDULE(res) )
            return ptWAITING;
        if ( rx.on_receive_refresh() > 0){
            ostimeout_stop(&wait_to);
            return ptOK;
        }
    }
    ostimeout_stop(&wait_to);
    return ptNOK;
}

// checkout buffers, and reports like have_fame
// \return frame size
int SLIP_Device::refresh_frame(){
    rx.on_receive_refresh();
    return have_frame();
}


// очистка буффера приемника
void SLIP_Device::rx_drop(){
    io()->rx_drop();
    rx.reset();
}

//* блокирующая печать
//virtual
int SLIP_Device::putChar(int ch){
    u8 buf[2];
    unsigned len = rx.encode(buf, ch);
    if (len == 1)
        return io()->putChar(ch);
    else
        return io()->putData(buf, len);
}

//virtual
int SLIP_Device::puts( const char* str){
    unsigned len = strlen(str);
    return putData(str, len);
}

//*  \return - длинна отправленного участка
//virtual
int SLIP_Device::putData ( const void* str, unsigned len){
    u8  buf[32];
    const unsigned buf_chars = sizeof(buf)/2-2;
    const char* s = (const char*)str;
    for (; len > 0; ){
        unsigned good_len = rx.strcspn(s, len);
        if (good_len > 0)
            io()->putData(s, good_len);
        s += good_len;
        len -= good_len;
        if (len == 0)
            break;
        if (len > buf_chars)
            good_len = buf_chars;
        else
            good_len = len;
        unsigned buf_len = rx.encode(buf, s, good_len);
        io()->putData(buf, buf_len);
        s += good_len;
        len -= good_len;
    }
    return (s- (const char*)str);
}

//*  неблокирующая печать
//virtual
int SLIP_Device::postData ( const void* str, unsigned len){
    u8  buf[32];
    const unsigned buf_chars = sizeof(buf)/2-2;
    const char* s = (const char*)str;
    unsigned send_len =0 ;
    for (; len > 0; ){
        unsigned good_len = rx.strcspn(s, len);
        if (good_len > 0)
            send_len = io()->postData(str, good_len);
        s += send_len;
        len -= send_len;
        if (send_len < good_len)
            break;
        if (len == 0)
            break;
        if (len > buf_chars)
            good_len = buf_chars;
        else
            good_len = len;
        send_len = io()->tx.FreeSpaceSize()/2;
        if (send_len <= 2)
            // cant post any escaped simbol
            break;
        send_len -= 2;
        if (good_len > send_len)
            good_len = send_len;
        unsigned buf_len = rx.encode(buf, s, good_len);
        send_len = io()->postData(buf, buf_len);
        //assert(send_len == good_len);
        if (send_len < good_len){
            //violated sending!
            return -1;
        }
        s += good_len;
        len -= good_len;
    }
    return (s- (const char*)str);
}

//virtual
int SLIP_Device::put_wait(unsigned to){
    int len = io()->tx.FreeSpaceSize()/2;

    if (len == 0) {
        len = io()->put_wait(to)/2;
    }

    if (len > 2)
        return len-2;
    return len;
};

//static
void SLIP_Device::rx_over_event(void* arg, UART_BUFDevice* uart, unsigned c){
    SLIP_Device* self = (SLIP_Device*)arg;
    assert(self->io() == uart);
    self->on_rx_over(c);
}

void SLIP_Device::on_rx_over(unsigned ch){
    if (rx.have_frame()){
        ;//если в буфере распаршен фрейм, то не трогаю его.
    }
    else{
        //переполненый буфер означает утрату фреймов, потому просто оброшу
        //  все что имею.
        io()->rx_drop();
        rx.reset();
    }
}



