#include <Arduino.h>
typedef void(*function_cb)();
enum {BOOL, NUMBER, FLOAT, STRING};
class TestClass
{
struct Cmd {
function_cb fn = nullptr;
char cmd_tag[3];
uint8_t type = 255;
void* var;
};
private:
Cmd cmds[10];
int m_last = 0;
public:
inline void AddCmd(const char* cmd, function_cb foo) {
strcpy (cmds[m_last].cmd_tag, cmd);
cmds[m_last].fn = foo;
m_last++;
}
template<typename T>
inline void AddCmd(const char* cmd, uint8_t type, T& myVar) {
strcpy (cmds[m_last].cmd_tag, cmd);
cmds[m_last].fn = nullptr;
cmds[m_last].type = type;
cmds[m_last].var = &myVar;
m_last++;
}
inline void ReadSer() {
if(Serial.available()) {
String line = Serial.readStringUntil('\n');
for(int i=0; i<m_last; i++) {
if (line.indexOf(cmds[i].cmd_tag) > -1) {
if (cmds[i].fn != nullptr) {
cmds[i].fn();
}
switch (cmds[i].type) {
case BOOL:
{
*(bool*)cmds[i].var = (line.substring(2).toInt() == 1);
Serial.print("Bool val: ");
Serial.println(*(bool*)cmds[i].var);
break;
}
case NUMBER:
{
*(int*)cmds[i].var = line.substring(2).toInt();
Serial.print("Int val: ");
Serial.println(*(int*)cmds[i].var);
break;
}
}
}
}
}
}
};
TestClass myClass;
void dummy() {
Serial.println("dummy function fired");
}
bool bVar1 = false;
bool bVar2 = true;
int iVar1 = 9999;
int iVar2 = 8888;
void setup() {
Serial.begin(115200);
myClass.AddCmd("1B", BOOL, bVar1);
myClass.AddCmd("2B", BOOL, bVar1);
// Es: 1I2500 imposta iVar1 == 2500
myClass.AddCmd("1I", NUMBER, iVar1);
myClass.AddCmd("2I", NUMBER, iVar1);
// Lo stesso comando usato per impostare il valore di bVar1
// esegue anche la funzione di callback void dummy()
myClass.AddCmd("1B", dummy);
Serial.println("-------------\n");
}
void loop() {
myClass.ReadSer();
// bVar1 diventa true se invio sulla seriale "1B1"
if (bVar1) {
Serial.println("bVar1 variable == true");
bVar1 = false;
}
}