maskedw
7/24/2018 - 1:55 AM

mbed async putc

mbed async putc

extern "C" {
int Putc(int c)
{
    static osThreadId threadIds[3] = { 0 };
    static std::vector<char> buffers[3];
    static int countIds = 0;
    static AAsyncSerialOut* aout;

    const osThreadId thisId = Thread::gettid();
    int index = -1;
    for (int i = 0; i < countIds; i++)
    {
        if (threadIds[i] == thisId)
        {
            index = i;
            break;
        }
    }

    if (index == -1)
    {
        X_ASSERT(countIds < X_COUNT_OF(threadIds));
        {
            CriticalSectionLock
            threadIds[countIds] = thisId;
            index = countIds++;
        }
        std::vector<char>* v = &buffers[index];
        v->reserve(AAsyncSerialOut::BLOCK_SZ);
    }

    std::vector<char>* v = &buffers[index];
    v->push_back(c);

    if (c == '\n' || (v->size() == (AAsyncSerialOut::BLOCK_SZ - 1)))
    {
        v->push_back('\0');
        aout->putString(v->data());
        v->clear();
    }

    return c;
}