Implimented a callback approach to processing functions

This commit is contained in:
2024-09-23 22:50:37 -04:00
parent f3c9aea558
commit 59bafb2549
3 changed files with 132 additions and 42 deletions

View File

@@ -0,0 +1,43 @@
#include "CommandHandler.h"
CommandHandler::CommandHandler(){
for(uint32_t i = 0; i < MAX_COMMAND_SIZE; i++){
commandCallbacks[i] = nullptr;
commandCallbackIDs[i] = 0;
}
}
bool CommandHandler::RegisterCommand(uint32_t commandID, CommandCallback callback){
for(uint32_t i = 0; i < MAX_COMMAND_SIZE; i++){
if(commandCallbacks[i] == nullptr){
commandCallbacks[i] = callback;
commandCallbackIDs[i] = commandID;
return true;
}
}
return false;
}
bool CommandHandler::RemoveCommand(uint32_t commandID){
for(uint32_t i = 0; i < MAX_COMMAND_SIZE; i++){
if(commandCallbackIDs[i] == commandID){
commandCallbacks[i] = nullptr;
commandCallbackIDs[i] = -1;
return true;
}
}
return false;
}
CommandHandler::CommandStatus CommandHandler::ProcessCommand(uint32_t * command, uint32_t commandSize){
uint32_t commandID{command[0]};
// get a pointer to the second element in the array because the first element is the command ID
uint32_t * args{&(command[1])};
for(uint32_t i = 0; i < MAX_COMMAND_SIZE; i++){
if(commandCallbacks[i] != nullptr && commandCallbackIDs[i] == commandID){
return commandCallbacks[i](args, commandSize-1);
}
}
return CommandStatus::INVALID;
}

View File

@@ -0,0 +1,49 @@
#pragma once
#include <cstdint>
class CommandHandler{
public:
// create an enum for command return values
enum CommandStatus{
SUCCESS,
FAILURE,
INVALID
};
// create a typedef for a command callback function which takes an array pointer and an array size as an argument and returns a CommandStatus
typedef CommandStatus (*CommandCallback)(uint32_t * command, uint32_t commandSize);
CommandHandler();
~CommandHandler() = default;
/**
* @brief Register a command callback function to a command ID
* @param commandID The command ID to register the callback to
* @param callback The callback function to register
* @return true if the callback was registered successfully, false otherwise
*/
bool RegisterCommand(uint32_t commandID, CommandCallback callback);
/**
* @brief Remove a command callback function from a command ID
* @param commandID The command ID to remove the callback from
* @return true if the callback was removed successfully, false otherwise
*/
bool RemoveCommand(uint32_t commandID);
/**
* @brief Process a command
* @param command The command to process
*/
CommandStatus ProcessCommand(uint32_t * command, uint32_t commandSize);
private:
static constexpr uint32_t MAX_COMMAND_SIZE{10};
// pointer to the head of the command array
uint32_t * command{nullptr};
// an array of command callbacks
CommandCallback commandCallbacks[MAX_COMMAND_SIZE];
// an array of command callback IDs
uint32_t commandCallbackIDs[MAX_COMMAND_SIZE];
};