StateMachine

The MARTe StateMachine components allows to associate the sending of Messages to events.

Each state contains one, or more, StateMachineEvent elements. The StateMachine can be in one (and only one) state at a given time.

The StateMachine is a key component which is used in many MARTe applications to synchronise the application state against the external environment.

Upon receiving of a Message, the StateMachine will verify if the Message function (see GetFunction) is equal to the name of any of the declared StateMachineEvent elements for the current StateMachine state. If it is, the StateMachine will change to the declared state and trigger any messages associated to this transition.

Note

If a state change requests arrives while the state is being changed, this request will be queued and served once the previous state transition is completed.

Configuration

Each state is declared as a ReferenceContainer of StateMachineEvent elements.

+StateMachine = {
   Class = StateMachine
   +STATE1 = {
      Class = ReferenceContainer
      +GOTOSTATE2 = {
         Class = StateMachineEvent
         ...
      }
      +ERROR = {
         Class = StateMachineEvent
         ...
      }
      ...
   }
   +STATE2 = {
      Class = ReferenceContainer
      +GOTOSTATE1 = {
         Class = StateMachineEvent
         ...
      }
      +ERROR = {
         Class = StateMachineEvent
         ...
      }
      ...
   }

Each StateMachineEvent contains the NextState (where to go), the NextStateError (where to go in case of any error while sending the messages) and one or more messages to be sent when the event is triggered.

+StateMachine = {
   Class = StateMachine
   +STATE1 = {
      Class = ReferenceContainer
      +GOTOSTATE2 = {
         Class = StateMachineEvent
         NextState = "STATE2"
         NextStateError = "ERROR"
         Timeout = 0
         +DoSomething = {
             Class = Message
             Destination = Receiver1
             Mode = ExpectsReply
             Function = Function1
             +Parameters = {
                 Class = ConfigurationDatabase
                 param1 = 2
                 param2 = 3.14
             }
         }
         +DoSomethingElse = {
             Class = Message
             Destination = Receiver1
             Mode = ExpectsReply
             Function = Function0
         }
      }
      +GOTOSTATE3 = {
         Class = StateMachineEvent
         NextState = "STATE3"
         NextStateError = "ERROR"
         Timeout = 0
         +DoSomething = {
             Class = Message
             Destination = Receiver1
             Mode = ExpectsReply
             Function = Function1
             +Parameters = {
                 Class = ConfigurationDatabase
                 param1 = 4
                 param2 = 5.312
             }
         }
      }
      ...

Note

The StateMachine is not compatible with the usage of the GAMBareScheduler for more than two states. The first state being the state started in and then the second being the next state. This is because the StartNextExecution function of the GAMBareScheduler is a non-returning infinite while loop and stalls the StateMachine at the state transition point while executing the second state.

The Timeout parameter sets the maximum amount of time allowed for the state transition (including waiting for all the requested replies to arrive). An infinite timeout is defined with a value of 0.

Note

The message replies can be used to guarantee that the state transitions only complete when given events occur/complete.

If an event named ENTER of type ReferenceContainer exists, all of its contained messages will be triggered when entering the state.

+StateMachine = {
   Class = StateMachine
   +STATE1 = {
      Class = ReferenceContainer
      +ENTER = {
          Class = ReferenceContainer
          +DoSomethingWhenEntering = {
             Class = Message
             Destination = Receiver1
             Mode = ExpectsReply
             Function = Function1
             +Parameters = {
                 Class = ConfigurationDatabase
                 param1 = 4
                 param2 = 5.312
             }
          }
          +DoSomethingElseWhenEntering = {
             Class = Message
             Destination = Receiver2
             Mode = ExpectsReply
             Function = Function1
             +Parameters = {
                 Class = ConfigurationDatabase
                 param1 = 8
                 param2 = -5.312
             }
          }
      }
      +GOTOSTATE2 = {
         Class = StateMachineEvent
         ...

Examples

The following is an example which shows how a state machine can be used to trigger remote function calls:

../../_images/StateMachineExample-1.png
Example of a StateMachine receiving and triggering messages.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/**
 * @file StateMachineExample1.cpp
 * @brief Source file for class StateMachineExample1
 * @date 25/04/2018
 * @author Andre Neto
 *
 * @copyright Copyright 2015 F4E | European Joint Undertaking for ITER and
 * the Development of Fusion Energy ('Fusion for Energy').
 * Licensed under the EUPL, Version 1.1 or - as soon they will be approved
 * by the European Commission - subsequent versions of the EUPL (the "Licence")
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
 *
 * @warning Unless required by applicable law or agreed to in writing, 
 * software distributed under the Licence is distributed on an "AS IS"
 * basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the Licence permissions and limitations under the Licence.

 * @details This source file contains the definition of all the methods for
 * the class StateMachineExample1 (public, protected, and private). Be aware that some
 * methods, such as those inline could be defined on the header file, instead.
 */
#define DLL_API
/*---------------------------------------------------------------------------*/
/*                         Standard header includes                          */
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
/*                         Project header includes                           */
/*---------------------------------------------------------------------------*/
#include "AdvancedErrorManagement.h"
#include "CLASSMETHODREGISTER.h"
#include "ConfigurationDatabase.h"
#include "ErrorLoggerExample.h"
#include "ObjectRegistryDatabase.h"
#include "RegisteredMethodsMessageFilter.h"
#include "StandardParser.h"
#include "StateMachine.h"

/*---------------------------------------------------------------------------*/
/*                           Static definitions                              */
/*---------------------------------------------------------------------------*/

namespace MARTe2Tutorial {

/**
 * @brief A MARTe::Object class that registers a set of RPC functions that can be called
 * with messages.
 */
class MessageReceiverEx1: public MARTe::Object, public MARTe::MessageI {
public:
    CLASS_REGISTER_DECLARATION()

    /**
     * @brief Install the RegisteredMethodsMessageFilter filter.
     */
MessageReceiverEx1    () : MARTe::Object(), MARTe::MessageI() {
        using namespace MARTe;
        filter = ReferenceT<RegisteredMethodsMessageFilter>(GlobalObjectsDatabase::Instance()->GetStandardHeap());
        filter->SetDestination(this);
        MessageI::InstallMessageFilter(filter);
        fun0Called = false;
        fun1Called = false;
        fun2Called = false;
        fun3Called = false;
    }

    virtual ~MessageReceiverEx1 () {
        if (GetName() != NULL) {
            REPORT_ERROR_STATIC(MARTe::ErrorManagement::Information, "No more references pointing at %s [%s]. "
                    "The Object will be safely deleted.", GetName(), GetClassProperties()->GetName());
        }
    }

    virtual void Purge(MARTe::ReferenceContainer &purgeList) {
        RemoveMessageFilter(filter);
    }

    MARTe::ErrorManagement::ErrorType Function0 () {
        REPORT_ERROR_STATIC(MARTe::ErrorManagement::Information, "Function0 called.");
        fun0Called = true;
        return MARTe::ErrorManagement::NoError;
    }

    MARTe::ErrorManagement::ErrorType Function1 (MARTe::uint32 a, MARTe::float32 b) {
        REPORT_ERROR_STATIC(MARTe::ErrorManagement::Information, "Received %u %f.", a, b);
        fun1Called = true;
        return MARTe::ErrorManagement::NoError;
    }

    MARTe::ErrorManagement::ErrorType Function2 (MARTe::int32 a, MARTe::float32 b, MARTe::uint32 c) {
        REPORT_ERROR_STATIC(MARTe::ErrorManagement::Information, "Received %u %f %u.", a, b,c);
        fun2Called = true;
        return MARTe::ErrorManagement::NoError;
    }

    MARTe::ErrorManagement::ErrorType Function3 (MARTe::StreamString a) {
        REPORT_ERROR_STATIC(MARTe::ErrorManagement::Information, "Received %s.", a.Buffer());
        fun3Called = true;
        return MARTe::ErrorManagement::NoError;
    }

    bool fun0Called;
    bool fun1Called;
    bool fun2Called;
    bool fun3Called;

private:
    MARTe::ReferenceT<MARTe::RegisteredMethodsMessageFilter> filter;
};

CLASS_REGISTER(MessageReceiverEx1, "")
CLASS_METHOD_REGISTER(MessageReceiverEx1, Function0)
CLASS_METHOD_REGISTER(MessageReceiverEx1, Function1)
CLASS_METHOD_REGISTER(MessageReceiverEx1, Function2)
CLASS_METHOD_REGISTER(MessageReceiverEx1, Function3)

}
/*---------------------------------------------------------------------------*/
/*                           Method definitions                              */
/*---------------------------------------------------------------------------*/

int main(int argc, char **argv) {
    using namespace MARTe;
    using namespace MARTe2Tutorial;
    SetErrorProcessFunction(&ErrorProcessExampleFunction);

    StreamString configurationCfg = ""
            "+Receiver1 = {\n"
            "    Class = MessageReceiverEx1\n"
            "}\n"
            "+Receiver2 = {\n"
            "    Class = MessageReceiverEx1\n"
            "}\n"
            "+StateMachineExample1 = {\n"
            "    Class = StateMachine\n"
            "    +STATE1 = {\n"
            "       Class = ReferenceContainer\n"
            "       +GOTOSTATE2 = {\n"
            "          Class = StateMachineEvent\n"
            "          NextState = \"STATE2\"\n"
            "          NextStateError = \"STATE1\"\n"
            "          Timeout = 0\n"
            "          +DoSomethingOnRec1 = {\n"
            "              Class = Message\n"
            "              Destination = Receiver1\n"
            "              Mode = ExpectsReply\n"
            "              Function = Function1\n"
            "              +Parameters = {\n"
            "                   Class = ConfigurationDatabase\n"
            "                   param1 = 2\n"
            "                   param2 = 3.14\n"
            "              }\n"
            "          }\n"
            "          +DoSomethingElseOnRec1 = {\n"
            "              Class = Message\n"
            "              Destination = Receiver1\n"
            "              Mode = ExpectsReply\n"
            "              Function = Function0\n"
            "          }\n"
            "       }\n"
            "       +GOTOSTATE3 = {\n"
            "          Class = StateMachineEvent\n"
            "          NextState = \"STATE3\"\n"
            "          NextStateError = \"STATE1\"\n"
            "          Timeout = 0\n"
            "          +DoSomethingOnRec2 = {\n"
            "              Class = Message\n"
            "              Destination = \"Receiver1\"\n"
            "              Mode = ExpectsReply\n"
            "              Function = Function1\n"
            "              +Parameters = {\n"
            "                   Class = ConfigurationDatabase\n"
            "                   param1 = 2\n"
            "                   param2 = 3.14\n"
            "              }\n"
            "          }\n"
            "          +DoSomethingElseOnRec2 = {\n"
            "              Class = Message\n"
            "              Destination = \"Receiver2\"\n"
            "              Mode = ExpectsReply\n"
            "              Function = Function0\n"
            "          }\n"
            "       }\n"
            "    }\n"
            "    +STATE2 = {\n"
            "       Class = ReferenceContainer\n"
            "       +GOTOSTATE1 = {\n"
            "          Class = StateMachineEvent\n"
            "          NextState = \"STATE1\"\n"
            "          NextStateError = \"STATE1\"\n"
            "          Timeout = 0\n"
            "          +DoSomethingOnRec1 = {\n"
            "              Class = Message\n"
            "              Destination = Receiver1\n"
            "              Mode = ExpectsReply\n"
            "              Function = Function3\n"
            "              +Parameters = {\n"
            "                   Class = ConfigurationDatabase\n"
            "                   param1 = \"BACKTOSTATE1!\"\n"
            "              }\n"
            "          }\n"
            "       }\n"
            "    }\n"
            "    +STATE3 = {\n"
            "       Class = ReferenceContainer\n"
            "       +ENTER = {\n"
            "           Class = ReferenceContainer\n"
            "           +DoSomethingOnRec1 = {\n"
            "              Class = Message\n"
            "              Destination = Receiver1\n"
            "              Mode = ExpectsReply\n"
            "              Function = Function2\n"
            "              +Parameters = {\n"
            "                   Class = ConfigurationDatabase\n"
            "                   param1 = 1"
            "                   param2 = 2"
            "                   param3 = 3"
            "              }\n"
            "          }\n"
            "       }"
            "       +GOTOSTATE2 = {\n"
            "          Class = StateMachineEvent\n"
            "          NextState = \"STATE2\"\n"
            "          NextStateError = \"STATE2\"\n"
            "          Timeout = 0\n"
            "          +DoSomethingOnRec2 = {\n"
            "              Class = Message\n"
            "              Destination = Receiver2\n"
            "              Mode = ExpectsReply\n"
            "              Function = Function3\n"
            "              +Parameters = {\n"
            "                   Class = ConfigurationDatabase\n"
            "                   param1 = \"BACKTOSTATE2!\"\n"
            "              }\n"
            "          }\n"
            "       }\n"
            "    }\n"
            "}\n";

    REPORT_ERROR_STATIC(ErrorManagement::Information, "Loading CFG:\n%s", configurationCfg.Buffer());
    ConfigurationDatabase cdb;
    StreamString err;
    //Force the string to be seeked to the beginning.
    configurationCfg.Seek(0LLU);
    StandardParser parser(configurationCfg, cdb, &err);
    bool ok = parser.Parse();
    ObjectRegistryDatabase *ord = ObjectRegistryDatabase::Instance();
    if (ok) {
        //After parsing the tree is pointing at the last leaf
        cdb.MoveToRoot();
        ok = ord->Initialise(cdb);
    }
    else {
        StreamString errPrint;
        errPrint.Printf("Failed to parse %s", err.Buffer());
        REPORT_ERROR_STATIC(ErrorManagement::ParametersError, errPrint.Buffer());
    }
    ReferenceT<MessageReceiverEx1> rec1 = ord->Find("Receiver1");
    ReferenceT<MessageReceiverEx1> rec2 = ord->Find("Receiver2");

    //Send a message to the state machine
    ReferenceT<Message> msg1(GlobalObjectsDatabase::Instance()->GetStandardHeap());
    ConfigurationDatabase msg1Cdb;
    msg1Cdb.Write("Destination", "StateMachineExample1");
    msg1Cdb.Write("Function", "GOTOSTATE3");
    msg1->Initialise(msg1Cdb);
    MessageI::SendMessage(msg1, NULL);

    while (!rec2->fun0Called) {
        Sleep::Sec(0.1);
    }

    ReferenceT<Message> msg2(GlobalObjectsDatabase::Instance()->GetStandardHeap());
    ConfigurationDatabase msg2Cdb;
    msg2Cdb.Write("Destination", "StateMachineExample1");
    msg2Cdb.Write("Function", "GOTOSTATE2");
    msg2->Initialise(msg2Cdb);
    MessageI::SendMessage(msg2, NULL);

    while (!rec2->fun3Called) {
        Sleep::Sec(0.1);
    }

    ReferenceT<Message> msg3(GlobalObjectsDatabase::Instance()->GetStandardHeap());
    ConfigurationDatabase msg3Cdb;
    msg3Cdb.Write("Destination", "StateMachineExample1");
    msg3Cdb.Write("Function", "GOTOSTATE1");
    msg3->Initialise(msg3Cdb);
    MessageI::SendMessage(msg3, NULL);

    while (!rec1->fun3Called) {
        Sleep::Sec(0.1);
    }
    //Purge all the Objects!
    ObjectRegistryDatabase::Instance()->Purge();
    return 0;
}

Instructions on how to compile and execute the examples can be found here.