Independent subtates in a state machine - spring

I need some suggestions. I am trying to implement an online order process through Spring state machine and am trying to construct a state diagram before I get to work. Now say my order can be canceled by three different admin users CanceledByAdmin1,CanceledByAdmin2 and CanceledByAdmin3. Should I make them substate of Cancel state or create three different states? Keeping in mind that all canceled states are the final states and independent of each other, I don't know if making substates does anything other than simplifying the paper diagram. Any help would be appreciated.

What comes for Spring Statemachine we can have only one terminate state and trying to make that as collection of substates is a bit awkward because once you enter it, state machine should stop all processing. Thought this area is something what I've probably overlooked and could try to enhance things.
While you could probably have a state S1 having three substates S11/S11E,S12/S12E andS13/S13E with triggerless transition from S11 to S11E and same with other substates, even this feels a bit weird because none of those would actually terminate root state machine.
I guess question is what you're trying to accomplish?
If you only want to keep that information around who/which cancelled the order, could you use a simple single terminate state and during a transition to that terminate state, add/modify extended state variables with this info.
Extended state variables are usually used to overcome these problems of suddenly having astronomical count of states to keep arbitrary information around. I know that in this example you only have three, but what about if you have 10, or 100? If you actually need to add even one more, you need to change state machine configuration and recompile. With extended state variables you would not need to do that.

Related

How to cleanly tell a task to die in FreeRTOS

I'm making a light with an ESP32 and the HomeKit library I chose uses FreeRTOS and esp-idf, which I'm not familiar with.
Currently, I have a function that's called whenever the colour of the light should be changed, which just changes it in a step. I'd like to have it fade between colours instead, which will require a function that runs for a second or two. Having this block the main execution of the program would obviously make it quite unresponsive, so I need to have it run as a task.
The issue I'm facing is that I only want one copy of the fading function to be running at a time, and if it's called a second time before it's finished, the first copy should exit(without waiting for the full fade time) before starting the second copy.
I found vTaskDelete, but if I were to just kill the fade function at an arbitrary point, some variables and the LEDs themselves will be in an unknown state. To get around this, I thought of using a 'kill flag' global variable which the fading function will check on each of its loops.
Here's the pseudocode I'm thinking of:
update_light {
kill_flag = true
wait_for_fade_to_die
xTaskCreate fade
}
fade {
kill_flag = false
loop_1000_times {
(fading code involving local and global variables)
.
.
if kill_flag, vTaskDelete(NULL)
vTaskDelay(2 / portTICK_RATE_MS)
}
}
My main questions are:
Is this the best way to do this or is there a better option?
If this is ok, what is the equivalent of my wait_for_fade_to_die? I haven't been able to find anything from a brief look around, but I'm new to FreeRTOS.
I'm sorry to say that I have the impression that you are pretty much on the wrong track trying to solve your concrete problem.
You are writing that you aren't familiar with FreeRTOS and esp-idf, so I would suggest you first familiarize with freeRTOS (or with the idea of RTOS in general or with any other RTOS, transferring that knowledge to freeRTOS, ...).
In doing so, you will notice that (apart from some specific examples) a task is something completely different than a function which has been written for sequential "batch" processing of a single job.
Model and Theory
Usually, the most helpful model to think of when designing a good RTOS task inside an embedded system is that of a state machine that receives events to which it reacts, possibly changing its state and/or executing some actions whose starting points and payload depends on the the event the state machine received as well as the state it was in when the event is detected.
While there is no event, the task shall not idle but block at some barrier created by the RTOS function which is supposed to deliver the next relevant event.
Implementing such a task means programming a task function that consists of a short initialisation block followed by an infinite loop that first calls the RTOS library to get the next logical event (see right below...) and then the code to process that logical event.
Now, the logical event doesn't have to be represented by an RTOS event (while this can happen in simple cases), but can also be implemented by an RTOS queue, mailbox or other.
In such a design pattern, the tasks of your RTOS-based software exist "forever", waiting for the next job to perform.
How to apply the theory to your problem
You have to check how to decompose your programming problem into different tasks.
Currently, I have a function that's called whenever the colour of the light should be changed, which just changes it in a step. I'd like to have it fade between colours instead, which will require a function that runs for a second or two. Having this block the main execution of the program would obviously make it quite unresponsive, so I need to have it run as a task.
I hope that I understood the goal of your application correctly:
The system is driving multiple light sources of different colours, and some "request source" is selecting the next colour to be displayed.
When a different colour is requested, the change shall not be performed instantaneously but there shall be some "fading" over a certain period of time.
The system (and its request source) shall remain responsive even while a fade takes place, possibly changing the direction of the fade in the middle.
I think you didn't say where the colour requests are coming from.
Therefore, I am guessing that this request source could be some button(s), a serial interface or a complex algorithm (or random number generator?) running in background. It doesnt really matter now.
The issue I'm facing is that I only want one copy of the fading function to be running at a time, and if it's called a second time before it's finished, the first copy should exit (without waiting for the full fade time) before starting the second copy.
What you are essentially looking for is how to change the state (here: the target colour of light fading) at any time so that an old, ongoing fade procedure becomes obsolete but the output (=light) behaviour will not change in an incontinuous way.
I suggest you set up the following tasks:
One (or more) task(s) to generate the colour changing requests from ...whatever you need here.
One task to evaluate which colour blend shall be output currently.
That task shall be ready to receive
a new-colour request (changing the "target colour" state without changing the current colour blend value)
a periodical tick event (e.g., from a hardware or software timer)
that causes the colour blend value to be updated into the direction of the current target colour
Zero, one or multiple tasks to implement the colour blend value by driving the output features of the system (e.g., configuring GPIOs or PWMs, or transmitting information through a serial connection...we don't know).
If adjusting the output part is just assigning some registers, the "Zero" is the right thing for you here. Otherwise, try "one or multiple".
What to do now
I found vTaskDelete, but if I were to just kill the fade function at an arbitrary point, some variables and the LEDs themselves will be in an unknown state. To get around this, I thought of using a 'kill flag' global variable which the fading function will check on each of its loops.
Just don't do that.
Killing a task, even one that didn't prepare for being killed from inside causes a follow-up of requirements to manage and clean-up output stuff by your software that you will end up wondering why you even started using an RTOS.
I do know that starting to design and program in that way when you never did so is a huge endeavour, starting like a jump into cold water.
Please trust me, this way you will learn the basics how to design and implement great embedded systems.
Professional education companies offer courses about RTOS integration, responsive programming and state machine design for several thousands of $/€/£, which is a good indicator of this kind of working knowledge.
Good luck!
Along that way, you'll come across a lot of detail questions which you are welcome to post to this board (or find earlier answers on).

Spring State machine - reuse Submachine

I have difficulty in re-using a sub-machine diagram.
I have a need to Re-Use one State machine that I have linked to a state as a sub-machine, in another state as a sub-machine. But when I give the reference to it I get a null pointer exception.
Refer image
I Have added a submachine reference to GeneralTopup, I want to add the same to Register. But it seems impossible. Is this so?
This would not work as you need to have unique states in a whole machine and this would add same state multiple times. Having said that, it is a story what has been in my mind for a long time but I don't yet know how to implement it.

Retry and max attemps with state machine

I'm trying to make a state machine in which I want to build a retry and max attemps feature. Let me explain, so far I have this:
From SAVED, I want to go to VALIDATED, although if there is an error, it has to go to AWAITING_VALIDATION state. After 3 minutes, try again to VALIDATED state.
Did I have correctly set up retry mechanism?
After 3 attemps, I want to go back to SAVED state (and pause state machine). Is it possible to do that in a fancy waty (e.g using spring state machine) or do I have to do this manually using some kind of a cache?
Thanks for your help
There are probably many ways to do these things with different machine configurations but having said that, this is such a clearly presented guestion that I wanted to spend some time on it.
You are close and you missed some things(I'd say tricks) to make this happen. Answer is to use extended state variables to add memory into a machine. These variables are usually used to limit number of needed stated to represent what machine needs to do. You need 3 loops and you could probably create more states to represent each loop and transition(with specific guards) to those as needed. However this will simply explode state configuration if you need more loops like 10 or 20 or 100+.
I created an example in ssm-sample3 which is showing how extended state variables and different guards and actions can be used to drive this specific flow.
Unfortunately there is a bug in a current 1.1.1.RELEASE which prevents you to directly transition from a AWAITING_VALIDATION into HAS_ERROR junction and loop until you pause into VALID using an anonymous transition having a guard(that's why sample has a dummy TMP state which is not needed with 1.2.x).
This is probably something I'd like to add as an example or faq to our ref docs.
Lemmy know if this helps.

Create a StateMachineInterceptor to persist StateMachineContext

I'm struggling to persist my state machine following the recipes and examples available. I'm working with the master branch and my state machine uses Hierarchical States, Regions and Orthogonal states. The first example I followed is spring-statemachine-samples/persist but it seems to deal only with basic FSM. The second one I tried is LocalStateMachineInterceptor but id does not seem to be working with Hierarchical States. Also, I can't find any way to persist an history state via a StateMachinePersist.
Is there an example of a complex FSM with persistence anywhere?
I have to be honest that persistence is one relatively unknown topic for samples and docs when things gets more complicated. It is something I'm currently working on to make it easier because as a user you should not care as there should be a relatively clean API's to do it. So stay tuned for those.
Having said that, before we get code more clear on this;
StateMachinePersist leads to StateMachineContext and there is some code in tests, namely StateMachineResetTests which shows some ways to do these things. There was also a question gh127 where I wrote something about internals of resetting a machine which is what a persistence does.
History state, yes that's my bad, for some reason it has slipped from my radar. Thanks for pointing it out! Created an issue for it gh182.

What's the best erlang approach to being able to identify a processes identity from its process id?

When I'm debugging, I'm usually looking at about 5000 processes, each of which could be one of about 100 gen_servers, fsms, etc. If I want to know WHAT an erlang process is, I can do:
process_info(pid(0,1,0), initial_call).
And get a result like:
{initial_call,{proc_lib,init_p,5}}
...which is all but useless.
More recently, I hit upon the idea (brace yourselves) of registering each process with a name that told me WHO that process represented. For example, player_1150 is the player process that represents player 1150. Yes, I end up making a couple million atoms over the course of a week-long run. (And I would love to hear comments on the drawbacks of boosting the limit to 10,000,000 atoms when my system runs with about 8GB of real memory unused, if there are any.) Doing this meant that I could, at the console of a live system, query all processes for how long their message queue was, find the top offenders, then check to see if those processes were registered and print out the atom they were registered with.
I've hit a snag with this: I'm moving processes from one node to another. Now a player process can have 3 different names; player_1158, player_1158_deprecating, player_1158_replacement. And I have to make absolutely sure I register and unregister these names with precision timing to make sure that a process is always named and that the appropriate names always exist, AND that I don't try to register a name that some dying process already holds. There is some slop room, since this is only used for console debugging of a live system Nonetheless, the moment I started feeling like this mechanism was affecting how I develop the system (the one that moves processes around) I felt like it was time to do something else.
There are two ideas on the table for me right now. An ets tables that associates process ids with their description:
ets:insert(self(), {player, 1158}).
I don't really like that one because I have to manually keep the tables clean. When a player exits (or crashes) someone is responsible for making sure that his data are removed from the ets table.
The second alternative was to use the process dictionary, storing similar information. When my exploration of a live system led me to wonder who a process is, I could just look at his process dictionary using process_info.
I realize that none of these solutions is functionally clean, but given that the system itself is never, EVER the consumer of these data, I'm not too worried about it. I need certain debugging tools to work quickly and easily, so the behavior described is not open for debate. Are there any convincing arguments to go one way or another (other than the academic "don't use the _, it's evil" canned garbage?) I'd be happy to hear other suggestions and their justifications.
You should try out gproc, it's a very convenient application for keeping process metadata.
A process can be registered with several names and you can associate arbitrary properties to a process (where the key and value can be any erlang term). Also gproc monitors the registered processes and unregisters them automatically if they crash.
If you're debugging gen_servers and gen_fsms while they're still running, I would implement the handle_info functions for these behaviors. When you send each process a {get_info, ReplyPid} tuple, the process in question can send back a term describing its own state, what it is, etc. That way you don't have to keep track of this information outside of the process itself.
Isac mentions there is already a built in way to do this

Resources