dwhall / farc

Framework for state machines with run-to-completion concurrency using asyncio. Python 3.4 or later
MIT License
28 stars 6 forks source link

call Framework.run() as soon as possible when an event is posted to A… #6

Closed maxpeng closed 5 years ago

maxpeng commented 5 years ago

First, I would like to thank you for creating this useful python package.

Problem

I implement a simple on-off switch using farc. After state machine is started, I post a flick event after 2 seconds. However, the flick event will not be executed by the state machine. Refer the attached file on-off-switch.zip about the example.

Log before change:

[2019-08-28 06:33:35.497][on-off-switch            ][L#0019] _initial() - OnOffSwitch _initial
[2019-08-28 06:33:35.497][on-off-switch            ][L#0034] off() - <off> enter
[2019-08-28 06:33:35.498][on-off-switch            ][L#0069] postFlickEvent() - post FLICK event
[2019-08-28 06:33:39.500][on-off-switch            ][L#0069] postFlickEvent() - post FLICK event

Change

Framework.run() is implemented with run-to-completion execution model. Framework.run() will exit if there is event in the queue. In order to make Framework.run() to be executed again, I need to call Framework._event_loop.call_soon_threadsafe(Framework.run) when an event is posted.

Log after change:

[2019-08-28 06:50:50.259][on-off-switch            ][L#0019] _initial() - OnOffSwitch _initial
[2019-08-28 06:50:50.260][on-off-switch            ][L#0034] off() - <off> enter
[2019-08-28 06:50:52.261][on-off-switch            ][L#0069] postFlickEvent() - post FLICK event
[2019-08-28 06:50:52.261][on-off-switch            ][L#0037] off() - <off> flick
[2019-08-28 06:50:52.261][on-off-switch            ][L#0040] off() - <off> exit
[2019-08-28 06:50:52.261][on-off-switch            ][L#0056] on() - <on> enter - turn light on
dwhall commented 5 years ago

Thank you for this feedback. I don't think I've used postFIFO() or postLIFO() yet in my own use of this framework, so I haven't run into this problem. I will want to make a regression test for this issue, so do I have permission to copy into this project some/all of the code from the attached example (I will attribute your github userid and apply the MIT license to it) ?

maxpeng commented 5 years ago

Sure, you have the permission to use the sample as you want.

By the way, the example just implements the first statechart depicted here - A simple on-off statechart - Statecharts.

Thanks!