/**
 * @file ntshell_task.c
 * @author Shinichiro Nakamura
 * @brief NT-Shellタスク。
 * @details
 */

/*
 * ===============================================================
 *  Natural Tiny Shell (NT-Shell)
 * ===============================================================
 * Copyright (c) 2010-2012 Shinichiro Nakamura
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 * ===============================================================
 */

#include <t_services.h>
#include "ntshell.h"
#include "ntshell_task.h"
#include "ntlibc.h"
#include "xprintf.h"

#define SERIAL_PORT_ID  (1)

static ntshell_t ntshell;

static int func_read(char *buf, int cnt, void *extobj)
{
    int i;
    for (i = 0; i < cnt; i++) {
        char c;
        syscall(serial_rea_dat(SERIAL_PORT_ID, &c, 1));
        buf[i] = c;
    }
    return cnt;
}

static int func_write(const char *buf, int cnt, void *extobj)
{
    int i;
    for (i = 0; i < cnt; i++) {
        char c = buf[i];
        syscall(serial_wri_dat(SERIAL_PORT_ID, &c, 1));

    }
    return cnt;
}

static void uxo(unsigned char c)
{
    syscall(serial_wri_dat(SERIAL_PORT_ID, &c, 1));
}

static unsigned char uxi(void)
{
    char c;
    syscall(serial_rea_dat(SERIAL_PORT_ID, &c, 1));
    return c;
}

void (*xfunc_out)(unsigned char) = uxo;
unsigned char (*xfunc_in)(void) = uxi;

static int func_callback(const char *text, void *extobj)
{
    if (ntlibc_strlen(text) > 0) {
        xprintf("User command is '%s'\r\n", text);
    }
    return 0;
}

void ntshell_task(VP_INT exinf)
{
    syscall(
            serial_ctl_por(SERIAL_PORT_ID,
                (IOCTL_CRLF | IOCTL_FCSND | IOCTL_FCRCV))
            );

    ntshell_init(&ntshell, func_read, func_write, func_callback, (void *)&ntshell);
    ntshell_set_prompt(&ntshell, "BlueTank>");
    ntshell_execute(&ntshell);
}

