listen serial input and react by callback registered.

Dependents:   Interference_Simple StrCommandHandler_Demo SerialInputReactionHandler_DEMO

Revision:
0:ec916055f0dd
Child:
1:fd211f137803
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SerialInputReactionHandler.h	Tue Nov 12 01:10:29 2019 +0000
@@ -0,0 +1,59 @@
+#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;
+};
+
+inline int SerialInputReactionHandler::echoCommand (char const * const arg_str)
+{
+    printf("%s", arg_str);
+    return 0;
+}
+
+#endif