tttapa / Control-Surface

Arduino library for creating MIDI controllers and other MIDI devices.
GNU General Public License v3.0
1.19k stars 134 forks source link

Add MIDIAddressable and MIDIAddressableUnsafe abstract classes #971

Open gwilherm opened 8 months ago

gwilherm commented 8 months ago

Hello, Here is a change I made for a need I have. I have a project of control surface with a set of push buttons. I wanted to make them configurable (via SysEx) The two properties I want to configure is the CC address and whether it a latch or simple push button. For that I needed an interface to call setAddressUnsafe() either for latch or simple button indifferently.

Of course I could use an array of MIDIOutputElements and cast CCButton/CCButtonLatched but it looks dirty to me. See an example

The modification I made:

Feel free to close if you think it is irrelevant ;-)

tttapa commented 8 months ago

Thanks, I'll have a look.

As a side note, even without a common base class, you can always do something like this:

#include <Control_Surface.h>

struct Addressable {
  virtual ~Addressable() = default;
  virtual MIDIAddress getAddress() const = 0;
  virtual void setAddressUnsafe(MIDIAddress address) = 0;
};

template <class T, class... Args>
Addressable *make_addressable(Args &&... args) {
  struct AddressableT : Addressable, T {
    AddressableT(Args &&... args) : T(std::forward<Args>(args)...) {}
    MIDIAddress getAddress() const override { return T::getAddress(); }
    void setAddressUnsafe(MIDIAddress address) override { T::setAddressUnsafe(address); }
  };
  return new AddressableT(std::forward<Args>(args)...);
}

Addressable *buttons[2];

void setup() {
  buttons[0] = make_addressable<CCButton>(2, 0x00);
  buttons[1] = make_addressable<CCButtonLatched>(3, 0x01);
  buttons[0]->setAddressUnsafe(buttons[0]->getAddress() + 0x10);
  buttons[1]->setAddressUnsafe(buttons[1]->getAddress() + 0x10);
  Control_Surface.begin();
}

void loop() {
  Control_Surface.loop();
}
gwilherm commented 8 months ago

Thank you for that cleaner solution ! It's great to meet people as invested as you, you're awesome, don't change !