Macro.cpp

mail@pastecode.io avatar
unknown
c_cpp
24 days ago
2.5 kB
1
Indexable
Never
#include <Macro.h>

LinkedList<NormalMacro> normal[BUTTON_LENGTH];
LinkedList<RepeatedMacro> repeated[BUTTON_LENGTH];
ButtonData buttonData[BUTTON_LENGTH];
byte previousButtonStates = 0;
long lastUpdateTimeMicros = micros();

void operator delete(void* ptr, size_t size){
  free(ptr);
}

void operator delete[](void* ptr, size_t size){
  free(ptr);
}


void registerNormalMacro(NormalMacroFunction fn, byte button, MacroData data) {
  normal[button].add(NormalMacro(fn, data));
}
void registerRepeatedMacro(RepeatedMacroFunction fn, byte button, MacroData data) {
  repeated[button].add(RepeatedMacro(fn, data));
}

void registerNormalMacro(NormalMacroFunction fn, byte button) {
  registerNormalMacro(fn, button, MacroData());
}
void registerRepeatedMacro(RepeatedMacroFunction fn, byte button) {
  registerRepeatedMacro(fn, button, MacroData());
}

template<typename CustomData>
CustomData* registerNormalMacro(NormalMacroFunction fn, byte button) {
  CustomData* customData = (CustomData*) malloc(sizeof(CustomData));
  registerNormalMacro(fn, button, MacroData(customData));

  return customData;
}
template<typename CustomData>
CustomData* registerRepeatedMacro(RepeatedMacroFunction fn, byte button) {
  CustomData* customData = (CustomData*) malloc(sizeof(CustomData));
  registerRepeatedMacro(fn, button, MacroData(customData));

  return customData;
}

void updateMacros(byte buttonStates) {
  long deltaTimeMicros = micros()-lastUpdateTimeMicros;
  lastUpdateTimeMicros = micros();
  for (uint8_t i = 0; i < BUTTON_LENGTH; i++) {
    if (bitRead(buttonStates, i)) {
      for (uint8_t j = 0; j < repeated[i].size(); j++) {
        RepeatedMacro* macro = repeated[i].get(j);
        macro->data.currentRun++;

        RepeatedMacroEvent event = RepeatedMacroEvent(&macro->data, millis()-buttonData[i].pressedStartTimeMillis, deltaTimeMicros, buttonData[i].hits); 
        macro->fn(&event);
      }
    }
    if (bitRead(buttonStates, i) && !bitRead(previousButtonStates, i)) {
      if (bitRead(buttonStates, i)) buttonData[i].hits++;
      buttonData[i].pressedStartTimeMillis = millis();
      
      for (uint8_t j = 0; j < normal[i].size(); j++) {
        NormalMacro* macro = normal[i].get(j);
        macro->data.currentRun++;

        NormalMacroEvent event = NormalMacroEvent(&macro->data);
        macro->fn(&event);
      }
    } else if (!bitRead(buttonStates, i)) buttonData[i].pressedStartTimeMillis = 0;
  }
  previousButtonStates = buttonStates;
}
Leave a Comment