listen serial input and react by callback registered.

Dependents:   Interference_Simple StrCommandHandler_Demo SerialInputReactionHandler_DEMO

SerialInputReactionHandler.h

Committer:
aktk
Date:
2019-11-12
Revision:
1:fd211f137803
Parent:
0:ec916055f0dd
Child:
2:4718a4eaf340

File content as of revision 1:fd211f137803:

#ifndef SERIAL_INPUT_REACTION_HANDLER_H
#define SERIAL_INPUT_REACTION_HANDLER_H

#include "mbed.h"
#include <string>

class SerialInputReactionHandler
{
public:
    enum InputMode {KB_SINGLE_INPUT = 0, KB_TILL_ENTER, NUMBEROFMODES};
    static char const * const ARROW_UP;
    static char const * const ARROW_DOWN;
    static char const * const ARROW_RIGHT;
    static char const * const ARROW_LEFT;

    SerialInputReactionHandler(
        Callback<int (char const * const)> arg_callback_onCommand = &echoCommand
    );
    
    void attach(Callback<int (char const * const)> arg_callback_onCommand);
    void startReception(Serial * arg_serial_socket, InputMode arg_mode = KB_SINGLE_INPUT);
    void quit();

    void changeMode(InputMode arg_mode);

private:
    void commonProcedure();
    void listenKBSingleInput();
    void listenKBTillEnter();
    void discardBuffer();

    void (SerialInputReactionHandler::*funcIfInput[NUMBEROFMODES])();

    /** Wrapper function that executes commonProcedure() and a function
     *  listed in funcIfInput[]()
     *
     *  This function is supposed to be used as callback attached to such like
     *  Serial.attach(), so that it is called evrey a key input thry keyboard
     *  or a byte written thru communication with like PCs.
     */
    void sig_bind();
    
    Callback<int (char const * const)> callback_onCommand;
    static int echoCommand (char const * const);

    Serial * m_serial_socket;

    InputMode m_input_mode;
    uint8_t m_buffer_c;
    string  m_buffer_s;
    
    bool isArrowSymbol();
};

inline int SerialInputReactionHandler::echoCommand (char const * const arg_str)
{
    printf("%s", arg_str);
    return 0;
}
inline void SerialInputReactionHandler::discardBuffer()
{
    m_buffer_c = '\0';
    m_buffer_s = "";
}

#endif