tinkerspy / Automaton

Reactive State Machine Framework for Arduino
https://github.com/tinkerspy/Automaton/wiki
MIT License
374 stars 63 forks source link

'Test for lambda' - allow calllback to real lambda functions #61

Closed euphi closed 5 years ago

euphi commented 5 years ago

Please note: This PR works for me but has not yet been tested extensively. For now, it is just a proposal for discussion

The connector mechanism ("onPush") does not allow to use a lamba-function that capture [this]. So you can't callback a method. (it works for lambdas that don't catch anything).

To solve this, I added a typedef std::function<void (int idx, int v, int up)> atm_cb_lambda_t; and extended the logic in Machine and atm_connector to support callback to this type.

Unfortunately this cannot be stored in the union together with the C-style function pointers, so it takes some additional space. (Maybe someone with more C++ experience can help here?)

You can find a usage example in https://github.com/euphi/ESP_HomieRollerShutter , especially https://github.com/euphi/ESP_HomieRollerShutter/blob/master/src/HomieRollershutter.cpp , line 30/31.

There are multiple instances of the HomieRollershutter class, so capturing [this] is necessary for correct logic.

tinkerspy commented 5 years ago

I have to confess that my c++ knowledge is lacking in some areas. I wanted to do this but I couldn't figure out how :-( I'll certainly look at this and if other people can contribute that would be great! Do you think this could cause any backward compatibilty issues for code already based on Automaton?

This looks like a big improvement!

euphi commented 5 years ago

It has no direct impact on function, but it will increase size in memory for the atm_connector objects. Furthermore, code size will increase due to using std::function.

So it could be a problem with small arduino devices.

I'm using it on ESP8266 where size is not that problematic. I'll test it with a small Arduino soon.

tinkerspy commented 5 years ago

Attiny's are definitely a challenge. In early versions of Automaton I had a 'Tiny Machine' class to accommodate them. Can you quantify the memory (RAM) increase per connector?