#include "sensor_commands.h" namespace sensor_commands { const uint8_t MAX_CALLBACKS = 20; uint8_t callbacks_count = 0; // A callback contains both a function and a pointer to arbitrary data // that will be passed as argument to the function. struct Callback { Callback(const char *s = 0, void (*f)(void*) = 0, void *d = 0) : name(s), function(f), data(d) { } const char *name; void (*function)(void*); void *data; }; Callback callbacks[MAX_CALLBACKS]; void defineCallback(const char *n, void (*f)(void*), void *d) { if (callbacks_count < MAX_CALLBACKS) { callbacks[callbacks_count] = Callback(n, f, d); callbacks_count++; } else { Serial.println(F("Too many callbacks have been defined.")); } } bool startsWith(const char *a, const char *b) { if (strncmp(a, b, strlen(b)) == 0) return 1; return 0; } void run(const char *command) { Serial.print(F("Received command : '")); Serial.print(command); Serial.println("'"); // Test all the callbacks. for (uint8_t i = 0; i < callbacks_count; i++) { if (startsWith(command, callbacks[i].name)) { Serial.print("OHHHH YES!!!"); } Serial.print("Trying '"); Serial.print(callbacks[i].name); Serial.println("'"); callbacks[i].function(callbacks[i].data); } Serial.println("Done."); } }