B4R Question B4R state-machine code example

peacemaker

Expert
Licensed User
Longtime User
Hi, All
Maybe do we have any B4R example code to use the sketch like a state-machine ?
Where there are long algorithm of actions according to the previous actions results...

Say, one scenario:
The data1 should be sent to the server only after:
  • Internet is connected
    • Command1 is requested from the server (https)
      • and the response is received
        • and parsed.
          • Data1 is measured from a Sensor1
            • The power of Sensor1 is switched on before measuring.

And each action needs time to execute, timeout to wait for result - and can be at least true\false resulted.

It's good to have some state-machine module or class or ....
 

hatzisn

Expert
Licensed User
Longtime User
It is quite easy to make.
You start at first with designing the states in a tool like this:


It will help you visualize what you want to do. Afterwards you create a main sub named StateSelector. It will be like this:

B4X:
Sub StateSelector(u as byte)
Select Case u
    Case 1
      CallSubPlus("State1", 10, 0)
    Case 2
      CallSubPlus("State2", 10, 0)
    Case 3
      CallSubPlus("State3", 10, 0)
'   .
'   .
'   .
'   .
'   .
End Select
End Sub

Each Sub Executes Code based on what you want it to do and according to the available ways out from it in relation to values you CallSubPlus("StateSelector", 10, x) where x is the number of the state you want to go.
If you make a call to an external service with httpUtils you continue to the code you want from JobDone again with CallSubPlus("StateSelector", 10, y).

CallSubPlus is used so that you do not end up going from state to state in an endless stack. With CallSubPlus the Sub is called after T milliseconds and the state machine is able to exit the calling sub before the new sub is called.
 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…