uint32_t lastDccCommandMillis = 0;
int lastDccAddress = 0;
bool lastDccOn = false;

void handleAddressCommand(const char* source, int address, bool on) {
  if (address < 1 || address > 2044) return;

  if (handleRandomDccAddress(address, on)) {
    FastLED.show();
    return;
  }

  bool found = false;

  for (int s = 0; s < MAX_STRIPS; s++) {
    for (int i = 0; i < ledCount[s]; i++) {
      if (config[s][i].dccAddress == address) {
        found = true;

        if (on) {
          ledState[s][i] = true;
          nextEffectUpdate[s][i] = 0;
          applyLedMode(s, i);

          Serial.print(source);
          Serial.print(" ");
          Serial.print(address);
          Serial.print(" -> Baand ");
          Serial.print(stripName(s));
          Serial.print(" LED ");
          Serial.print(i + 1);
          Serial.println(" ON");
        } else {
          ledState[s][i] = false;
          leds[s][i] = CRGB::Black;

          Serial.print(source);
          Serial.print(" ");
          Serial.print(address);
          Serial.print(" -> Baand ");
          Serial.print(stripName(s));
          Serial.print(" LED ");
          Serial.print(i + 1);
          Serial.println(" OFF");
        }
      }
    }
  }

  if (found) {
    FastLED.show();
  }
}

void handleDccAddress(int cs2Addr, int direction, int power) {
  if (power == 0) return;
  if (inputMode == 2) return; // kun MQTT

  lastDccCommandMillis = millis();
  lastDccAddress = cs2Addr;
  lastDccOn = (direction != 0);
  handleAddressCommand("DCC", cs2Addr, direction != 0);
}

void notifyDccMsg(DCC_MSG *Msg) {
  if (Msg->Size != 3) return;

  byte b1 = Msg->Data[0];
  byte b2 = Msg->Data[1];

  if ((b1 & 0x80) == 0) return;
  if ((b2 & 0x80) == 0) return;

  int addrLow  = b1 & 0x3F;
  int addrHigh = ((~b2) >> 4) & 0x07;

  int decoderAddr = addrLow + (addrHigh << 6) + 1;

  int outputPair = (b2 >> 1) & 0x03;
  int direction  = b2 & 0x01;
  int power      = (b2 >> 3) & 0x01;

  int turnoutAddr = (decoderAddr - 1) * 4 + outputPair + 1;

  int cs2Addr = turnoutAddr - 4;

  handleDccAddress(cs2Addr, direction, power);
}
