Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 8af234d516a1115912ace6b16b9c88bf6acf7d88 (plain) (blame)
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704

h1. eTrice Overview

h2. What is eTrice?

eTrice provides an implementation of the ROOM modeling language (Real Time Object Oriented Modeling) together with editors, code generators for Java, C++ and C code and exemplary target middleware.

The model is defined in textual form (Xtext) with graphical editors (Graphiti) for the structural and behavioral (i.e. state machine) parts.  

h2. Reduction of Complexity

eTrice is all about the reduction of complexity:

* structural complexity
** by explicit modeling of hierarchical Actor containment, layering and inheritance
* behavioral complexity
** by hierachical statemachines with inheritance
* teamwork complexity
** because loosely coupled Actors provide a natural way to structure team work
** since textual model notation allows simple branching and merging
* complexity of concurrent & distributed systems
** because loosely coupled Actors are deployable to threads, processes, nodes
* complexity of variant handling and reuse (e.g. for product lines)
** by composition of existing Actors to new structures
** since Protocols and Ports make Actors replaceable
** by inheritance for structure, behavior and Protocols
** by making use of model level libraries
* complexity of debugging
** model level debugging: state machine animation, data inspection and manipulation, message injection, generated message sequence charts
** model checking easier for model than for code (detect errors before they occur)


h1. Introduction to the ROOM Language

h2. Scope of ROOM

This chapter will give a rough overview of what ROOM (*R* eal time *O* bject *O* riented *M* odeling) is and what it is good for. It will try to answer the following questions:
* Where does it come from?
* Which kind of SW-Systems will be addressed?
* What is the relation between OOP and ROOM?
* What are the benefits of ROOM?
* Which consequences must be taken into account?

h3. Where does it come from?

Room was developed in the 1990th on the background of the upcoming mobile applications with the goal to manage the complexity of such huge SW-Systems. From the very beginning ROOM has focused on a certain type of SW-Systems and is, in contrast to the UML, well suited for this kind of systems. In this sense, ROOM is a DSL (Domain Specific Language) for distributed, event driven, real time systems. 

Bran Selic, Garth Gullekson and Paul T. Ward have published the concepts 1994 in the book *Real-Time Object-Oriented Modeling*. The company _object time_ (TM) developed a ROOM tool which was taken over by _Rational SW_ (TM) and later on by _IBM_ (TM). 
The company _Protos Software Gmbh_ (TM) also developed a ROOM tool called _Trice_ (TM) for control software for production machines and automotive systems. _Trice_ (TM) is the predecessor of eTrice (see Introduction to eTrice). 
 
From our point of view ROOM provides still the clearest, simplest, most complete and best suited modeling concepts for the real time domain. All later proposals like the UML do not fit as well to this kind of problems.
 

h3. Which kind of SW-Systems will be addressed?

As mentioned before ROOM addresses distributed, event driven, real time systems. But what is a *real time system*? ROOM defines a set of properties which are typical for a real time system. These properties are:
* Timeliness
* Dynamic internal structure
* Reactiveness
* Concurrency
* Distribution
* Reliability

Each of these properties has potential to make SW development complex. If a given system can be characterized with a combination of or all of these properties, ROOM might be applied to such a system.  

As an example take a look at a washing machine. The system has to react on user interactions, has to handle some error conditions like a closed water tap or a defective lye pump. It has to react simultaneously to all these inputs. It has to close the water valve in a certain time to avoid flooding the basement. 
So, the system can be characterized as timely, concurrent and reactive. As long as the washing machine does not transform to a laundry drier by itself, the system has no dynamic internal structure and as long as all functions are running on a single micro controller the (SW)-system is not distributed. 
ROOM fits perfect to such a system.

A SW system which mainly consists of data transformations like signal/image processing or a loop controller (e.g. a PID controller) cannot be characterized with any of the above mentioned properties. However, in the real world most of the SW systems will be a combination of both. ROOM can be combined with such systems, so that for example an actor provides a *run to completion* context for calculating an image processing algorithm or a PID controller.  

h3. What is the relation between OOP and ROOM?

The relation between classical object oriented programming and ROOM is comparable to the relation between assembler programming and C programming. It provides a shift of the object paradigm. As the picture shows, the classic object paradigm provides some kind of information hiding. Attributes can be accessed via access methods. Logical higher level methods provide the requested behavior to the user.   

!images/010-RoomIntroduction01.png!

As the figure illustrates, the classical object paradigm does not care about concurrency issues. The threads of control will be provided by the underlying operating system and the user is responsible to avoid access violations by using those operating system mechanisms directly (semaphore, mutex).

!images/010-RoomIntroduction02.png!

ROOM provides the concept of a logical machine (called actor) with its own thread of control. It provides some kind of cooperative communication infrastructure with *run to completion* semantic. That makes developing of business logic easy and safe (see basic concepts). The logical machine provides an encapsulation shell including concurrency issues (see chapter *Run to completion*). 

!images/010-RoomIntroduction03.png!

This thinking of an object is much more general than the classic one.  

h3. What are the benefits of ROOM?

ROOM has a lot of benefits and it depends on the users point of view which is the most important one. From a general point of view the most important benefit is, that ROOM allows to create SW systems very efficient, robust and safe due to the fact that it provides some abstract, high level modeling concepts combined with code generation and a small efficient runtime environment.  

In detail:
* ROOM models contain well defined interfaces (protocols), which makes it easy to reuse components in different applications or e.g. in a test harness. 
* Graphical modeling makes it easy to understand, maintain and share code with other developers
* Higher abstraction in combination with automated code generation provides very efficient mechanisms to the developer. 
* ROOM provides graphical model execution, which makes it easy to understand the application or find defects in a very early phase. 

h3. Which consequences must be taken into account?

Generating code from models will introduce some overhead in terms of memory footprint as well as performance. For most systems the overhead will be negligible. However, the decision for using ROOM should be made explicitly and it is always a trade off between development costs, time to market and costs in terms of a little bit more of memory and performance. Thanks to the powerful component model, ROOM is especially well suited for the development of software product lines with their need for reusable core assets.  
  
Care must be taken during the introduction of the new methodology. Due to the fact that ROOM provides a shift of the object paradigm, developers and teams need a phase of adaption. Every benefit comes at a price.

h2. Basic Concepts

h3. Actor, Port, Protocol

The basic elements of ROOM are the actors with their ports and protocols. The protocol provides a formal interface description. The port is an interaction point where the actor interacts with its outside world. Each port has exactly one protocol attached. The sum of all ports builds up the complete interface of an actor. Each port can receive messages, with or without data, which are defined in the attached protocol. Each message will be handled by the actors behavior (state machine) or will be delegated to the actors internal structure.

<table title="Actor and Protocol Example">
	<tr>
		<td>!images/040-ActorClass.png!</td>
		<td>!images/040-ProtocolClassTextualNotation.png!</td>
	</tr>
	<tr>
		<td align="center">*Actor with Subactors*</td>
		<td align="center">*Protocol Definition*</td>
	</tr>
</table>

The actor provides access protection for its own attributes (including complex types (classical objects)), including concurrency protection. An actor has neither public attributes nor public operations. The only interaction with the outside world takes place via interface ports. This ensures a high degree of reusability on actor level and provides an effective and safe programming model to the developer. 

Receiving a message via a port will trigger the internal state machine. A transition will be executed depending on the message and the current state. Within this transition, detail level code will be executed and response messages can be sent.

"video: receiving a message":http://eclipse.org/etrice/images/010-room-introduction01.avi

With this model, a complex behavior can be divided into many relatively simple, linked actors. To put it the other way round: The complex behavior will be provided by a network of relatively simple components which are communicating with each other via well defined interfaces.


h3. Hierarchy in Structure and Behavior

ROOM provides two types of hierarchy. Behavioral hierarchy and structural hierarchy. Structural hierarchy means that actors can be nested to arbitrary depth. Usually you will add more and more details to your application with each nesting level. That means you can focus yourself on any level of abstraction with always the same element, the actor. Structural hierarchy provides a powerful mechanism to divide your problem in smaller pieces, so that you can focus on the level of abstraction you want to work on. 

The actor's behavior will be described with a state machine. A state in turn may contain sub states. This is another possibility to focus on an abstraction level. Take the simple FSM from the blinky actor from the blinky tutorial. 
   
Top level:
!images/020-Blinky15.png!

_blinking_ Sub machine:
!images/020-Blinky151.png!

From an abstract point of view there is a state _blinking_. But a simple LED is not able to blink autonomously. Therefore you have to add more details to your model to make a LED blinking, but for the current work it is not of interest how the blinking is realized. This will be done in the next lower level of the hierarchy. 

This simple example might give an idea how powerful this mechanisms is.

The hierarchical FSM provides a rich tool box to describe real world problems (see *room concepts*).

h3. Layering

Layering is another well known form of abstraction to reduce complexity in the structure of systems. ROOM is probably the only language that supports Layering directly as language feature.
Layering can be expressed in ROOM by Actors with specialized Ports, called Service Access Points (*SAP*) and Service Provision Points (*SPP*).

The Actor that provides a service implements an SPP and the client of that service implements an SAP. The Layer Connection connects all SAPs of a specific Protocol within an Actor hierarchy with an SPP that implements the service. From the Actors point of view, SAPs and SPPs behave almost like regular ports.

!images/010-LayerExample.png!

The Example shows a layered model. The Layer Connections define e.g. that the _ApplicationLayer_ can only use the services of the _ServiceLayer_ and the _CommunicationLayer_. Actors inside the _ApplicationLayer_ that implement an SAP for those services are connected directly to the implementation of the services. 
Layering and actor hierarchies with port to port connections can be mixed on every level of granularity. 

h3. Run to Completion

*Run to completion* (RTC) is a very central concept of ROOM. It enables the developer to concentrate on the functional aspects of the system. The developer doesn't have to care about concurrency issues all the time. This job is concentrated to the system designer in a very flexible way.
What does *run to completion* mean:
RTC means that an actor, which is processing a message, can not receive the next message as long as the processing of the current message has been finished. Receiving of the next message will be queued from the underlying run time system.

Note: It is very important not to confuse run to completion and preemption. Run to completion means that an actor will finish the processing of a message before he can receive a new one (regardless of its priority). That does not mean that an actor cannot be preempted from an higher priority thread of control. But even a message from this higher prior thread of control will be queued until the current processing has been finished. 

With this mechanism all actor internal attributes and data structures are protected. Due to the fact that multiple actors share one thread of control, all objects are protected which are accessed from one thread of control but multiple actors. This provides the possibility to decompose complex functionality to several actors without the risk to produce access violations or dead locks.

h2. Execution Models

Since from ROOM models executable code can be generated, it is important to define the way the actors are executed and communicate with each other. The combination of communication and execution is called the Execution Model.
Currently the eTrice tooling only supports the *message driven* and parts of the *data driven* execution model. In future releases more execution models will be supported, depending on the requirements of the community.

h3. Communication Methods

* *message driven* (asynchronous, non blocking, no return value): Usually the message driven communication is implemented with message queues. Message queues are inherently asynchronous and enable a very good decoupling of the communicating parties.
* *data driven* (asynchronous, non blocking, no return value): In data driven communication sender and receiver often have a shared block of data. The sender writes the data and the receiver polls the data.
* *function call* (synchronous, blocking, return value): Regular function call as known in most programming languages.

h3. Execution Methods

* *execution by receive event*: The message queue or the event dispatcher calls a *receive event* function of the message receiver an thereby executes the processing of the event.
* *polled execution*: The objects are processed by a cyclic *execute* call
* *execution by function call*: The caller executes the called object via function call

h3. Execution Models

In todays embedded systems in most cases one or several of the following execution models are used:

h4. message driven

The message driven execution model is a combination of message driven communication and execution by receive event.
This model allows for distributed systems with a very high throughput.
It can be deterministic but the determinism is hard to proof.
This execution model is often found in telecommunication systems and high performance automation control systems.

h4. data driven

The data driven execution model is a combination of data driven communication and polled execution.
This model is highly deterministic and very robust, but the polling creates a huge performance overhead.
The determinism is easy to proof (simple mathematics). 
The execution model is also compatible with the execution model of control software generated by Tools like Matlab(TM) and LabView(TM).
This model is usually used for systems with requirements for safety, such as automotive and avionic systems.

h4. synchronous

The synchronous execution model could also be called *simple function calls*. 
This model is in general not very well suited to support the *run to completion* semantic typical for ROOM models, but could also be generated from ROOM models. 
With this execution model also lower levels of a software system, such as device drivers, could be generated from ROOM models.



h1. Working with the eTrice Tutorials

The eTrice Tutorials will help you to learn and understand the eTrice tool and concepts. ETrice supports several target languages. The concepts will not be explained for each language. 

Most of the common concepts will be described for Java as target language. To start with a new language the first steps to setup the workspace and to generate and run the first model will be described also. Target language specific aspects will be described as well.

Therefore the best way to start with eTrice is to follow the Java Tutorials and after that switch to your target language.  

h1. Setting up the Workspace for Java Projects

ETrice generates code out of ROOM models. The code generator and the generated code relies on a runtime framework and on some ready to use model parts. This parts provide services like:

* messaging
* logging
* timing

Additionally some tutorial models will be provided to make it easy to start with eTrice. All this parts must be available in our workspace before you can start working. After installation of eclipse (juno) and the eTrice plug in, your workspace should look like this:  

!images/013-SetupWorkspace01.png!

Just the _eTrice_ menu item is visible from the eTrice tool.
From the _File_ menu select _File->New->Project_

!images/013-SetupWorkspace02.png!

Open the _eTrice_ tab and select _eTrice Java Runtime_

Press _Next_ and _Finish_ to install the Runtime into your workspace.

!images/013-SetupWorkspace03.png!

Do the same steps for _eTrice Java Modellib_ and _eTrice Java Tutorials_. To avoid temporary error markers you should keep the proposed order of installation. The resulting workspace should look like this:

!images/013-SetupWorkspace04.png!

Now workspace is set up and you can perform the tutorials or start with your work.

The tutorial models are available in the _org.eclipse.etrice.tutorials_ project. All tutorials are ready to generate and run without any changes. To start the code generator simply run *gen_org.eclipse.etrice.tutorials.launch* as *gen_org.eclipse.etrice.tutorials.launch*: 

!images/013-SetupWorkspace05.png!

After generation for each tutorial a java file called *SubSystem_ModelnameRunner.java* is generated. To run the model simply run this file as a java application:

!images/013-SetupWorkspace06.png!

To stop the application type _quit_ in the console window.
 
!images/013-SetupWorkspace07.png!

Performing the tutorials will setup an dedicated project for each tutorial. Therefore there are some slight changes especially whenever a path must be set (e.g. to the model library) within your own projects. All this is described in the tutorials.

h1. Tutorial HelloWorld for Java

h2. Scope

In this tutorial you will build your first very simple eTrice model. The goal is to learn the work flow of eTrice and to understand a few basic features of ROOM. You will perform the following steps:

# create a new model from scratch
# add a very simple state machine to an actor
# generate the source code
# run the model
# open the message sequence chart

Make sure that you have set up the workspace as described in _Setting up the workspace_.

"video hello world":http://eclipse.org/etrice/images/015-HelloWorld01.avi

h2. Create a new model from scratch

The easiest way to create a new eTrice Project is to use the eclipse project wizard. From the eclipse file menu select _File->New->Project_ and create a new eTrice project and name it _HelloWorld_

!images/015-HelloWorld10.png!

The wizard creates everything that is needed to create, build and run an eTrice model. The resulting project should look like this:

!images/015-HelloWorld11.png!

Within the model directory the model file _HelloWorld.room_ was created. Open the _HelloWorld.room_ file and delete the contents of the file. Open the content assist with Ctrl+Space and select _model skeleton_.

!images/015-HelloWorld12.png!   

Edit the template variables by typing the new names and jumping with Tab from name to name.

The resulting model code should look like this:

bc.. 
RoomModel HelloWorld {

    LogicalSystem System_HelloWorld {
        SubSystemRef subsystem : SubSystem_HelloWorld
    }

    SubSystemClass SubSystem_HelloWorld {
        ActorRef application : HelloWorldTop
    }

    ActorClass HelloWorldTop {
    }
} 
bq. 

The goal of eTrice is to describe distributed systems on a logical level. In the current version not all elements will be used. But as prerequisite for further versions the following elements can be defined:
* the _LogicalSystem_ (currently optional)
* at least one _SubSystemClass_ (mandatory)
* at least one _ActorClass_ (mandatory)

The _LogicalSystem_ represents the complete distributed system and contains at least one _SubSystemRef_. The _SubSystemClass_ represents an address space and contains at least one _ActorRef_. The _ActorClass_ is the building block of which an application will be built of. It is in general a good idea to define a top level actor that can be used as reference within the subsystem.

The outline view of the textual ROOM editor shows the main modeling elements in an easy to navigate tree.


!images/015-HelloWorld02.png!


h2. Create a state machine

We will implement the Hello World code on the initial transition of the _HelloWorldTop_ actor. Therefore open the state machine editor by right clicking the _HelloWorldTop_ actor in the outline view and select _Edit Behavior_.

!images/015-HelloWorld03.png!

The state machine editor will be opened. Drag and drop an _Initial Point_ from the tool box to the diagram into the top level state. Drag and drop a _State_ from the tool box to the diagram. Confirm the dialogue with _ok_. Select the _Transition_ in the tool box and draw the transition from the _Initial Point_ to the State. Open the transition dialogue by double clicking the transition arrow and fill in the action code.

bc. System.out.println("Hello World !");
 
The result should look like this:

!images/015-HelloWorld04.png!

Save the diagram and inspect the model file. Note that the textual representation was created after saving the diagram.

!images/015-HelloWorld05.png!


h2. Build and run the model

Now the model is finished and source code can be generated. The project wizard has created a launch configuration that is responsible for generating the source code. From _HelloWorld/_ right click *gen_HelloWorld.launch* and run it as gen_HelloWorld. All model files in the model directory will be generated.

!images/015-HelloWorld06.png!

The code will be generated to the src-gen directory. The main function will be contained in *SubSystem_HelloWorldRunner.java*. Select this file and run it as Java application.

!images/015-HelloWorld07.png!


The Hello World application starts and the string will be printed on the console window. To stop the application the user must type _quit_ in the console window.

!images/015-HelloWorld08.png!

h2. Open the Message Sequence Chart

During runtime the application produced a MSC and wrote it to a file. Open HelloWorld/tmp/log/SubSystem_HelloWorld_Async.seq using Trace2UML (it is open source and can be obtained from  http://trace2uml.tigris.org/). You should see something like this:

!images/015-HelloWorld09.png!


h2. Summary

Now you have generated your first eTrice model from scratch. You can switch between diagram editor and model (.room file) and you can see what will be generated during editing and saving the diagram files. 
You should take a look at the generated source files to understand how the state machine is generated and the life cycle of the application. The next tutorials will deal with more complex hierarchies in structure and behavior.
 

h1. Tutorial Blinky (Java)

h2. Scope

This tutorial describes how to use the _TimingService_, how to combine a generated model with manual code and how to model a hierarchical state machine. The idea of the tutorial is to switch a LED on and off. The behavior of the LED should be: blinking in a one second interval for 5 seconds, stop blinking for 5 seconds, blinking, stop,...  
For this exercise we will use a little GUI class that will be used in more sophisticated tutorials too. The GUI simulates a pedestrian traffic crossing. For now, just a simple LED simulation will be used from the GUI. 

After the exercise is created you must copy the GUI to your src directory (see below).

The package contains four java classes which implements a small window with a 3-light traffic light which simulates the signals for the car traffic and a 2-light traffic light which simulates the pedestrian signals.

The GUI looks like this:

!images/020-Blinky08.png!

Within this tutorial we will just toggle the yellow light.

You will perform the following steps:

# create a new model from scratch
# define a protocol
# create an actor structure
# create a hierarchical state machine
# use the predefined _TimingService_
# combine manual code with generated code
# build and run the model
# open the message sequence chart

h2. Create a new model from scratch

Remember the exercise _HelloWorld_.
Create a new eTrice project and name it _Blinky_

To use the GUI please copy the package _org.eclipse.etrice.tutorials.PedLightGUI_ from _org.eclipse.etrice.tutorials/src_ to your *src* directory _Blinky/src_. For this tutorial you must remove the error markers by editing the file _PedestrianLightWndNoTcp.java_. Appropriate comments are provided to remove the error markers for this turorial.

Open the _Blinky.room_ file and copy the following code into the file or use content assist to create the model.

bc.. 
RoomModel Blinky {

    LogicalSystem System_Blinky {
        SubSystemRef subsystem : SubSystem_Blinky
    }

    SubSystemClass SubSystem_Blinky {
        ActorRef application : BlinkyTop
    }

    ActorClass BlinkyTop {
    }
}
bq. 

h2. Add two additional actor classes

Position the cursor outside any class definition and right click the mouse within the editor window. From the context menu select _Content Assist_  

!images/020-Blinky02.png!

Select _ActorClass - actor class skeleton_ and name it _Blinky_.

!images/020-Blinky01.png! 

Repeat the described procedure and name the new actor _BlinkyController_.

With Ctrl+Shift+F you can beautify the model code. 

Save the model and visit the outline view.

h2. Create a new protocol

With the help of _Content Assist_ create a _ProtocolClass_ and name it _BlinkyControlProtocol_.
Inside the brackets use the _Content Assist_ (CTRL+Space) to create two incoming messages called _start_ and _stop_.

The resulting code should look like this:

!images/020-Blinky03.png! 

With Ctrl-Shift+F or selecting _Format_ from the context menu you can format the text. Note that all elements are displayed in the outline view.

h2. Import the Timing Service

Switching on and off the LED is timing controlled. The timing service is provided from the model library and must be imported before it can be used from the model.

This is the first time you use an element from the modellib. Make sure that your Java Build Path has the appropriate entry to the modellib. Otherwise the jave code, which will be generated from the modellib, can not be referenced.
(right click to _Blinky_ and select properties. Select the _Java Build Path_ tab) 
  
!images/020-Blinky16.png! 

After the build path is set up return to the model and navigate the cursor at the beginning of the model and import the timing service: 

bc.. 
RoomModel Blinky {
    
    import room.basic.service.timing.* from "../../org.eclipse.etrice.modellib/models/TimingService.room" 
    
    LogicalSystem System_Blinky {
        SubSystemRef subsystem: SubSystem_Blinky
    }
}
...     
bq. 

Make sure that the path fits to your folder structure. The original tutorial code is different due to the folder structure.  

Now it can be used within the model. Right click to *SubSystem_Blinky* within the outline view. Select _Edit Structure_. The _application_ is already referenced in the subsystem. Drag and Drop an _ActorRef_ to the *SubSystem_Blinky* and name it _timingService_. From the actor class drop down list select _room.basic.service.timing.ATimingService_. Draw a _LayerConnection_ from _application_ to each service provision point (SPP) of the _timingService_. The resulting structure should look like this:

!images/020-Blinky06.png! 

The current version of eTrice does not provide a graphical element for a service access point (SAP). Therefore the SAPs to access the timing service must be added in the .room file. Open the _Blinky.room_ file and navigate to the _Blinky_ actor. Add the following line to the structure of the actor:

bc. SAP timer: room.basic.service.timing.PTimeout

Do the same thing for _BlinkyController_.

The resulting code should look like this:

!images/020-Blinky07.png!


h2. Finish the model structure

From the outline view right click to _Blinky_ and select _Edit Structure_. Drag and Drop an _Interface Port_ to the boarder of the _Blinky_ actor. Note that an interface port is not possible inside the actor. Name the port _ControlPort_ and select _BlinkyControlProtocol_ from the drop down list. Uncheck _Conjugated_ and _Is Relay Port_. Click _ok_. The resulting structure should look like this:


!images/020-Blinky04.png!

Repeat the above steps for the _BlinkyController_. Make the port _Conjugated_

Keep in mind that the protocol defines _start_ and _stop_ as incoming messages. _Blinky_ receives this messages and therefore _Blinky_'s _ControlPort_ must be a regular port and _BlinkyController_'s _ControlPort_ must be a conjugated port.


From the outline view right click _BlinkyTop_ and select _Edit Structure_.

Drag and Drop an _ActorRef_ inside the _BlinkyTop_ actor. Name it _blinky_. From the actor class drop down list select _Blinky_. Do the same for _controller_. Connect the ports via the binding tool. The resulting structure should look like this:

!images/020-Blinky05.png!

h2. Implement the Behavior

The application should switch on and off the LED for 5 seconds in a 1 second interval, then stop blinking for 5 seconds and start again. To implement this behavior we will implement two FSMs. One for the 1 second interval and one for the 5 second interval. The 1 second blinking should be implemented in _Blinky_. The 5 second interval should be implemented in _BlinkyController_. First implement the Controller.

Right click to _BlinkyController_ and select _Edit Behavior_.
Drag and Drop the _Initial Point_ and two _States_ into the top state. Name the states _on_ and _off_. 
Use the _Transition_ tool to draw transitions from _init_ to _on_ from _on_ to _off_ and from _off_ to _on_.

Open the transition dialog by double click the arrow to specify the trigger event and the action code of each transition. Note that the initial transition does not have a trigger event.

The transition dialog should look like this:

!{width=500px}images/020-Blinky09.png! 

The defined ports will be generated as a member attribute of the actor class from type of the attached protocol. So, to send e message you must state _port.message(param);_. In this example _ControlPort.start()_ sends the _start_ message via the _ControlPort_ to the outside world. Assuming that _Blinky_ is connected to this port, the message will start the one second blinking FSM. It is the same thing with the _timer_. The SAP is also a port and follows the same rules. So it is clear that _timer.Start(5000);_ will send the _Start_ message to the timing service. The timing service will send a _timeoutTick_ message back after 5000ms.

Within each transition the timer will be restarted and the appropriate message will be sent via the _ControlPort_. 

The resulting state machine should look like this:
(Note that the arrows peak changes if the transition contains action code.)

!images/020-Blinky10.png!

Save the diagram and inspect the _Blinky.room_ file. The _BlinkyController_ should look like this:

!images/020-Blinky11.png! 
 
Now we will implement _Blinky_. Due to the fact that _Blinky_ interacts with the GUI class a view things must to be done in the model file.

Double click _Blinky_ in the outline view to navigate to _Blinky_ within the model file.
Add the following code:
(type it or simply copy it from the tutorial project)

!images/020-Blinky12.png! 

_usercode1_ will be generated at the beginning of the file, outside the class definition. _usercode2_ will be generated within the class definition. The code imports the GUI class and instantiates the window class. Attributes for the carLights and pedLights will be declared to easily access the lights in the state machine.
The Operation _destroyUser()_ is a predefined operation that will be called during shutdown of the application. Within this operation, cleanup of manual coded classes can be done.
 
Now design the FSM of _Blinky_. Remember, as the name suggested _blinking_ is a state in which the LED must be switched on and off. We will realize that by an hierarchical FSM in which the _blinking_ state has two sub states.

Open the behavior diagram of _Blinky_ by right clicking the _Blinky_ actor in the outline view. Create two states named _blinking_ and _off_. Right click to _blinking_ and create a subgraph.

!images/020-Blinky13.png!

Create the following state machine. The trigger events between _on_ and _off_ are the _timeoutTick_ from the _timer_ port. 

!images/020-Blinky14.png!

Create entry code for both states by right clicking the state and select _Edit State..._

Entry code of _on_ is:

bc..  
timer.Start(1000);
carLights.setState(TrafficLight3.YELLOW); 
bq. 

 
Entry code  of _off_ is:

bc.. 
timer.Start(1000);
carLights.setState(TrafficLight3.OFF);
bq. 

Navigate to the Top level state by double clicking the _/blinking_ state. Create the following state machine:

!images/020-Blinky15.png!

The trigger event from _off_ to _blinking_ is the _start_ event from the _ControlPort_.The trigger event from _blinking_ to _off_ is the _stop_ event from the _ControlPort_.
Note: The transition from _blinking_ to _off_ is a so called group transition. This is a outgoing transition from a super state (state with sub states) without specifying the concrete leave state (state without sub states). An incoming transition to a super state is called history transition.   

Action code of the init transition is:

bc.. 
carLights = light.getCarLights();
pedLights = light.getPedLights();
carLights.setState(TrafficLight3.OFF);
pedLights.setState(TrafficLight2.OFF);
bq. 

Action code from _blinking_ to _off_ is:

bc.. 
timer.Kill();
carLights.setState(TrafficLight3.OFF); 
bq. 

The model is complete now. You can run and debug the model as described in getting started. Have fun.

The complete model can be found in /org.eclipse.etrice.tutorials/model/Blinky.

h2. Summary

Run the model and take a look at the generated MSCs. Inspect the generated code to understand the runtime model of eTrice. Within this tutorial you have learned how to create a hierarchical FSM with group transitions and history transitions and you have used entry code. You are now familiar with the basic features of eTrice. The further tutorials will take this knowledge as a precondition.


h1. Tutorial Sending Data (Java)

h2. Scope

This tutorial shows how data will be sent in a eTrice model. Within the example you will create two actors (MrPing and MrPong). MrPong will simply loop back every data it received.
MrPing will send data and verify the result.   

You will perform the following steps:

# create a new model from scratch
# create a data class
# define a protocol with attached data
# create an actor structure
# create two simple state machines
# build and run the model

h2. Create a new model from scratch

Remember exercise _HelloWorld_.
Create a new eTrice project and name it _SendingData_
Open the _SendingData.room_ file and copy the following code into the file or use content assist to create the model.


bc.. 
RoomModel SendingData {
    LogicalSystem SendingData_LogSystem {
        SubSystemRef SendingDataAppl:SendingData_SubSystem 
    }
    SubSystemClass SendingData_SubSystem {
        ActorRef SendigDataTopRef:SendingDataTop 
    }
    ActorClass SendingDataTop {
    }
}
bq. 

h2. Add a data class

Position the cursor outside any class definition and right click the mouse within the editor window. From the context menu select _Content Assist_ (or Ctrl+Space).  

!images/025-SendingData01.png!

Select _DataClass - data class skeleton_ and name it _DemoData_.
Remove the operations and add the following Attributes:

bc.. 
DataClass DemoData {
    Attribute int32Val: int32 = "4711"
    Attribute int8Array [ 10 ]: int8 = "{1,2,3,4,5,6,7,8,9,10}"
    Attribute float64Val: float64 = "0.0"
    Attribute stringVal: string = "\"empty\""
}
bq. 

Save the model and visit the outline view.
Note that the outline view contains all data elements as defined in the model. 

h2. Create a new protocol

With the help of _Content Assist_ create a _ProtocolClass_ and name it _PingPongProtocol_. Create the following messages:

bc.. 
ProtocolClass PingPongProtocol {
    incoming {
        Message ping(data: DemoData)
        Message pingSimple(data:int32)
    }
    outgoing {
        Message pong(data: DemoData)
        Message pongSimple(data:int32)
    }
}    
bq. 

h2. Create MrPing and MrPong Actors

With the help of _Content Assist_ create two new actor classes and name them _MrPing_ and _MrPong_. The resulting model should look like this:

bc.. 
RoomModel SendingData {

    LogicalSystem SendingData_LogSystem {
        SubSystemRef SendingDataAppl: SendingData_SubSystem
    }

    SubSystemClass SendingData_SubSystem {
        ActorRef SendigDataTopRef: SendingDataTop
    }

    ActorClass SendingDataTop { }

    DataClass DemoData {
        Attribute int32Val: int32 = "4711"
        Attribute int8Array [ 10 ]: int8 = "{1,2,3,4,5,6,7,8,9,10}"
        Attribute float64Val: float64 = "0.0"
        Attribute stringVal: string = "\"empty\""
    }

    ProtocolClass PingPongProtocol {
        incoming {
            Message ping(data: DemoData)
            Message pingSimple(data: int32)
        }
        outgoing {
            Message pong(data: DemoData)
            Message pongSimple(data: int32)
        }
    }

    ActorClass MrPing {
        Interface { }
        Structure { }
        Behavior { }
    }

    ActorClass MrPong {
        Interface { }
        Structure { }
        Behavior { }
    }
} 

bq.  

The outline view should look like this:

!images/025-SendingData03.png!

h2. Define Actor Structure and Behavior

Save the model and visit the outline view. Within the outline view, right click on the _MrPong_ actor and select _Edit Structure_. Select an _Interface Port_ from the toolbox and add it to MrPong. Name the Port _PingPongPort_ and select the _PingPongProtocol_

!images/025-SendingData02.png!

Do the same with MrPing but mark the port as _conjugated_

h3. Define MrPongs behavior

Within the outline view, right click MrPong and select _Edit Behavior_. Create the following state machine:

!images/025-SendingData04.png!

The transition dialogues should look like this:
For _ping_:

!images/025-SendingData05.png!

For _pingSimple_:

!images/025-SendingData06.png!


h3. Define MrPing behavior

Within the outline view double click MrPing. Navigate the cursor to the behavior of MrPing. With the help of content assist create a new operation.

!images/025-SendingData07.png!

Name the operation _printData_ and define the DemoData as a parameter.

Fill in the following code:

bc.. 
Operation printData(d: DemoData) : void {
            "System.out.printf(\"d.int32Val: %d\\n\",d.int32Val);"
            "System.out.printf(\"d.float64Val: %f\\n\",d.float64Val);"
            "System.out.printf(\"d.int8Array: \");"
            "for(int i = 0; i<d.int8Array.length; i++) {"
            "System.out.printf(\"%d \",d.int8Array[i]);}"
            "System.out.printf(\"\\nd.stringVal: %s\\n\",d.stringVal);"
}
bq. 

For MrPing create the following state machine:
(Remember that you can copy and paste the action code from the tutorial directory.)

!images/025-SendingData08.png!

The transition dialogues should look like this:

For _init_:

!images/025-SendingData09.png!

For _wait1_:

!images/025-SendingData10.png!

For _next_:

!images/025-SendingData11.png!

For _wait2_:

!images/025-SendingData12.png!

h2. Define the top level

Open the Structure from SendingDataTop and add MrPing and MrPong as a reference. Connect the ports.

!images/025-SendingData13.png!

The model is finished now and can be found in /org.eclipse.etrice.tutorials/model/SendingData.

h2. Generate and run the model

Generate the code by right click to *gen_SendingData.launch* and run it as *gen_SendingData*. Run the model. 
The output should look like this:

bq.. 
type 'quit' to exit
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPongSimple
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
data: 1
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPongSimple
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
data: 2
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPongSimple
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
data: 3
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPongSimple
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
data: 4
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPongSimple
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
data: 5
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPongSimple
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
data: 6
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPongSimple
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
data: 7
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPongSimple
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
data: 8
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPongSimple
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
data: 9
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPongSimple
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
data: 10
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPong
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
/SendingData_SubSystem/SendigDataTopRef/ref1 -> looping
d.int32Val: 4711
d.float64Val: 0,000000
d.int8Array: 1 2 3 4 5 6 7 8 9 10 
d.stringVal: empty
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPong
d.int32Val: 815
d.float64Val: 3,141234
d.int8Array: 100 101 102 103 104 105 106 107 108 109 
d.stringVal: some contents
/SendingData_SubSystem/SendigDataTopRef/ref0 -> waitForPong
quit
echo: quit
bq. 

h2. Summary

Within the first loop an integer value will be incremented by _MrPong_ and sent back to _MrPing_. As long as the guard is true _MrPing_ sends back the value.

Within the _next_ transition, _MrPing_ creates a data class and sends the default values. Then _MrPing_ changes the values and sends the class again. At this point you should note that during the send operation, a copy of the data class will be created and sent. Otherwise it would not be possible to send the same object two times, even more it would not be possible to send a stack object at all. This type of data passing is called _sending data by value_.
However, for performance reasons some applications requires _sending data by reference_. In this case the user is responsible for the life cycle of the object. In Java the VM takes care of the life cycle of an object. This is not the case for C/C++. Consider that a object which is created within a transition of a state machine will be destroyed when the transition is finished. The receiving FSM would receive an invalid reference. Therefore care must be taken when sending references.      

For sending data by reference you simply have to add the keyword _ref_ to the protocol definition.
 
bc. Message ping(data: DemoData ref)

Make the test and inspect the console output.

h1. Tutorial Pedestrian Lights (Java)

h2. Scope

The scope of this tutorial is to demonstrate how to receive model messages from outside the model. Calling methods which are not part of the model is simple and you have already done this within the blinky tutorial (this is the other way round: model => external code). Receiving events from outside the model is a very common problem and a very frequently asked question. Therefore this tutorial shows how an external event (outside the model) can be received by the model.

This tutorial is not like hello world or blinky. Being familiar with the basic tool features is mandatory for this tutorial. The goal is to understand the mechanism not to learn the tool features.

The idea behind the exercise is, to control a Pedestrian crossing light. We will use the same GUI as for the blinky tutorial but now we will use the _REQUEST_ button to start a FSM, which controls the traffic lights.

!images/020-Blinky08.png!

The _REQUEST_ must lead to a model message which starts the activity of the lights.

There are several possibilities to receive external events (e.g. TCP/UDP Socket, using OS messaging mechanism), but the easiest way is, to make a port usable from outside the model. To do that a few steps are necessary:
# specify the messages (within a protocol) which should be sent into the model
# model an actor with a port (which uses the specified protocol) and connect the port to the receiver 
# the external code should know the port (import of the port class)
# the external code should provide a registration method, so that the actor is able to allow access to this port
# the port can be used from the external code

h2. Setup the model

* Use the _New Model Wizzard_ to create a new eTrice project and name it _PedLightsController_.
* Copy the package _org.eclipse.etrice.tutorials.PedLightGUI_ to your _src_ directory (see blinky tutorial).
* In PedestrianLightWndNoTcp.jav uncomment line 15 (import), 36, 122 (usage) and 132-134 (registration). The error markers will disappear after the code is generated from the model.
* Copy the model from /org.eclipse.etrice.tutorials/model/PedLightsController to your model file, or run the model directly in the tutorial directory. 
* Adapt the import statement to your path.
bc.. 
import room.basic.service.timing.* from "../../org.eclipse.etrice.modellib/models/TimingService.room" 
bq. 

* Generate the code from the model.
* Add the org.eclipse.etrice.modellib to the Java Class Path of your project.
* All error markers should be disappeared and the model should be operable. 
* Arrange the Structure and the Statemachines to understand the model

!images/030-PedLights01.png!
The _GuiAdapter_ represents the interface to the external code. It registers its _ControlPort_ by the external code.

!images/030-PedLights02.png!
Visit the initial transition to understand the registration. The actor handles the incoming messages as usual and controls the traffic lights as known from blinky. 

!images/030-PedLights03.png!
The _Controller_ receives the _start_ message and controls the timing of the lights. Note that the _start_ message will be sent from the external code whenever the _REQUEST_ button is pressed.

*  Visit the model and take a closer look to the following elements:
# PedControlProtocol => notice that the start message is defined as usual
# Initial transition of the _GuiAdapter_ => see the registration
# The _Controller_ => notice that the _Controller_ receives the external message (not the _GuiAdapter_). The _GuiAdapter_ just provides its port and handles the incoming messages.
# Visit the hand written code => see the import statement of the protocol class and the usage of the port.

* Generate and test the model
* Take a look at the generated MSC => notice that the start message will shown as if the _GuiAdapter_ had sent it.

!images/030-PedLights04.png!

h2. Why does it work and why is it safe?

The tutorial shows that it is generally possible to use every port from outside the model as long as the port knows its peer. This is guaranteed by describing protocol and the complete structure (especially the bindings) within the model. 
The only remaining question is: Why is it safe and does not violate the *run to completion* semantic. To answer this question, take a look at the _MessageService.java_ from the runtime environment. There you will find the receive method which puts each message into the queue. 

bc.. 
    @Override
    public synchronized void receive(Message msg) {
        if (msg!=null) {
            messageQueue.push(msg);
            notifyAll(); // wake up thread to compute message
        }
    }
bq. 

This method is synchronized. That means, regardless who sends the message, the queue is secured. If we later on (e.g. for performance reasons in C/C++) distinguish between internal and external senders (same thread or not), care must be taken to use the external (secure) queue.




h1. Setting up the Workspace for C Projects
 
Before you can start with C, some preconditions must be fulfilled:

- A C compiler must be installed on your machine (all tests and tutorials are based on MinGW)
- The CDT-Eclipse plug in must be installed as the C development environment.

Once the CDT is installed, the C runtime and model library must be imported. 
(_File->New->Project->eTrice_ select _eTrice C runtime_ / _eTrice C modellib_)

The resulting workspace should look like this:


!images/032-SetupWorkspaceC01.png!


h2. Testing the environment

To verify the C tool chain you should generate and run the Hello World example program of the CDT.
 Activate the _C/C++_ perspective. 
 
!images/032-SetupWorkspaceC03.png!
 
From the main menu select _File->New->C Project_.
 
!images/032-SetupWorkspaceC02.png!

Name the project. Select an _Executable->Hello World ANSI C_ as project type, _MinGW GCC_ as tool chain and click _Finish_. 
 
!images/032-SetupWorkspaceC04.png! 

Select the new project and click the build button (or right click the project and select _Build Project_)

!images/032-SetupWorkspaceC05.png!

The binary should be generated. Run the binary as _Local C/C++ Application_

!images/032-SetupWorkspaceC06.png!

Verify the output.

!images/032-SetupWorkspaceC07.png!

Remember these steps. In the following Tutorials these steps will be referenced as _build and run_.


h2. Building the C runtime system

The C runtime system contains some basic functionalities to run the generated models. The so called runtime is common for all C projects. The requirements for several projects may differ depending on the functionality of the model or the resources of the different platforms. Therefore the runtime is configurable in terms of message queue size, frequency and memory alignment. The configuration file _etRuntimeConfig.h_ is located in _src/config_.

After changing the configuration, the runtime must be built.

Open the properties of the _org.eclipse.runtime.c_ project and select _C/C++ Build->Settings->Tool Settings_ and select _Includes_.

!images/032-SetupWorkspaceC08.png!

Verify the include paths

_src/config_
_src/common_
_src/platforms/generic_

Within the Setting dialog select the tab _Build Artefact_ and select _Static Library_

!images/032-SetupWorkspaceC09.png!

Build the runtime by clicking

!images/032-SetupWorkspaceC10.png!

The runtime library should be created.

!images/032-SetupWorkspaceC11.png!

For the tutorials one runtime library should be sufficient. For embedded projects it might be necessary to build project specific runtime libraries. In this case a separate project for the runtime should be created. Symbolic links to the sources might be used to avoid duplicate files. Just the configuration file must be duplicated. A specific library file must exist within the project. Such specific runtime libraries might be referenced from several applications.     

h1. Tutorial HelloWorld for C

h2. Scope

In this tutorial you will learn how to create a model for C from scratch. There are some more steps to do in C compared to Java. The goal is to get familiar with the additional steps. The Java tutorial is a prerequisite for the following explanations. 
You will perform the following steps:

# create a new model from scratch for C
# create structure and behavior similar to Java
# create a launch configuration for the C code generator
# setup the C environment
# generate the source code
# run the model

Make sure that you have set up the workspace as described in _Setting up the Workspace for C Projects_.


h2. Create a new model from scratch

Before you can create a new C-model, you have to create a new C project as described in _Setting up the Workspace for C Projects_.
Remember:
- select the _C/C++_ perspective
- From the main menue select _File->New->C Project_
- Name the project _HelloWorldC_
- Project type is _Executable / Empty C Project_
- Toolchain is _MinGW_

The workspace should look like this:

!images/034-HelloWorldC01.png!

The next step is to add the model folder:
Right click on the new project. Select _New->Folder_ and name it _model_.

!images/034-HelloWorldC02.png!

Add the model file to the folder. Right click on the new folder. Select _New->file_ and name it _HelloWorldC.room_.

!images/034-HelloWorldC03.png!

Due to the file ending _.room_, the tool will ask you to add the Xtext nature. Answer with _Yes_. 

!images/034-HelloWorldC04.png!

The workspace should look like this:

!images/034-HelloWorldC05.png!



h2. Create the HelloWorld model

Once the model file is created and the Xtext nature is added, you can create the model as you did it for Java.
Creating the model is not the focus of this tutorial. Therefore copy and paste the following code into your model file. Optionally you can open and layout the diagrams.  
Recognize the C specific parts:
- The action code contains C instead of Java. Later versions will contain a common action language, but for the moment the action language is target specific.
- The application must be shutdown on model level (see also _etRuntimeConfig.h_).  

bc.. 
RoomModel HelloWorldCModel {
	import room.basic.types.* from "../../org.eclipse.etrice.modellib.c/model/Types.room"
	SubSystemClass HelloWorldCSubSysClass {
		ActorRef HelloETriceTopRef:AHelloWorldCTop 
	}
	ActorClass AHelloWorldCTop {
		Structure { }
		Behavior {
			StateMachine {
				Transition init: initial -> state0 { }
				State state0 {
					entry {
						"printf(\"HelloWorldC !\\n\");"
						"SubSysClass_shutdown();"
						"\t\t\t\t\t\t"
					}
				}
			}
		}
	}	
}
bq. 

h2. Create a launch configuration to start the C code generator

Other than in Java a launch configuration for the C code generator must be created.

From the _Run_ menu select _Run Configurations_

!images/034-HelloWorldC06.png!

Within the dialog select _eTrice C Generator_ and click the _New_ button to create a new launch configuration.

!images/034-HelloWorldC07.png!

A new configuration should be created. Name it _gen_HelloWorldC_ and add the model via one of the _add_ buttons.

!images/034-HelloWorldC08.png!

In the _Refresh_ tab select _The entire workspace_ 

!images/034-HelloWorldC09.png!

In the _Common_ tab select _Shared file_ and add the _HelloWorldC_ project via the _Browse_ button.

!images/034-HelloWorldC10.png!

Apply your changes. The new configuration should now exist in your workspace.

!images/034-HelloWorldC11.png!


h2. Generate the code

Now you can generate the code as you know it from Java. Right click on the launch configuration and run it as _gen_HelloWorldC_.

!images/034-HelloWorldC12.png!

The code should be generated.

!images/034-HelloWorldC13.png!

h2. Setup the include path

Before you can build the application you must setup the include path for the runtime system. Right click the project and select _Properties_. Add the include path as described in _setting up the workspace_.

!images/034-HelloWorldC14.png!

Add the runtime library.

!images/034-HelloWorldC15.png!

Recognize the name of the library ("org.eclipse.etrice.runtime.c"). The library file on your disk is "liborg.eclipse.etrice.runtime.c.a". 

h2. Build and run the model

Now you can build the application. Click the build button to build the application.
Run the application as _Local C/C++ Application_.
Verify the output.

!images/034-HelloWorldC16.png!

h2. Summary

You are now familiar with all necessary steps to create, build and run an eTrice C model from scratch. You are able to create a launch configuration to start the code generator and to perform all necessary settings to compile and link the application.  

The next tutorial provides an exercise to get more familiar with these working steps.
 
h1. Tutorial Remove C-Comment ( C )

h2. Scope

In this tutorial you will create a more complex model. The model implements a simple parser that removes comments (block comments and line comments) from a C source file. Therefore we will create two actors. One actor is responsible to perform the file operations, whether the second actor implements the parser.

You will perform the following steps:

# create a new model from scratch for C
# define a protocol
# define your own data type
# create the structure and the behavior by yourself
# generate, build and run the model

Make sure that you have set up the workspace as described in _Setting up the Workspace for C Projects_.

h2. Create a new model from scratch

Remember the following steps from the previous tutorials:
- select the _C/C++_ perspective
- From the main menue select _File->New->C Project_
- Name the project _RemoveComment_
- Project type is _Executable / Empty C Project_
- Toolchain is _MinGW_
- Add the folder _model_
- Add the model file and name it _RemoveComment.room_
- Add the Xtext nature.

The workspace should look like this:

!images/036-RemoveCommentC01.png!

Create a launch configuration for the C generator and add the include path and library as described in _HelloWorldC_.

The workspace should look like this:

!images/036-RemoveCommentC02.png!

Now the model is created and all settings for the code generator, compiler and linker are done.


h2. Create your own data type

The planed application should read a C source file and remove the comments. Therefore we need a file descriptor which is not part of the basic C types. The type for the file descriptor for MinGW is _FILE_. To make this type available on the model level, you have to declare the type. 

Open the file _Types.room_ from _org.eclipse.modellib.c_ and take a look at the declaration of _string_ (last line) which is not a basic C type.

_PrimitiveType string:ptCharacter -> charPtr default "0"_

With this declaration, you make the _string_ keyword available on model level as a primitive type. This type will be translated to _charPtr_ in your C sources. _charPtr_ is defined in _etDatatypes.h_. This header file is platform specific (_generic_). With this mechanism you can define your own type system on model level and map the model types to specific target/platform types. 

To not interfere with other models, we will declare the type direct in the model.
Add the following line to your model:

bc.. 
RoomModel RemoveComment {
	import room.basic.types.* from "../../../org.eclipse.etrice.modellib.c/model/Types.room"
	
	PrimitiveType file:ptInteger -> FILE default "0"
bq. 

_FILE_ is the native type for MinGW. Therefore you don´t need a mapping within _etDatatypes.h_. If your model should be portable across different platforms you should not take this shortcut.
 
h2. Create the model

Due to the former tutorials you should be familiar with the steps to create the model with protocols, actors and state machines.

The basic idea of the exercise is to create a file reader actor, which is responsible to open, close and read characters from the source file. Another actor receives the characters and filters the comments (parser). The remaining characters (pure source code) should be print out. 

Remember the logical steps: 
- create the model by the help of content assist (CTRL Space)
- name the model, subsystem and top level actor
- define the protocol (in this case it should be able to send a char, and to request the next char from the file reader)
- create the structure (file reader and parser with an appropriate port, create the references and connect the ports)
- create the state machines

Try to create the model by yourself and take the following solution as an example.

Structure:

!images/036-RemoveCommentC04.png!

File reader FSM:

!images/036-RemoveCommentC05.png!

Parser FSM:

!images/036-RemoveCommentC06.png!

The complete model can be found in _org.eclipse.etrice.tutorials.c_

Take a look at the file attribute of the file reader. 

bc.. 
Attribute f:file ref
bq. 

_fopen_ expects a _FILE *_. _f:file ref_ declares a variable _f_ from type reference to _file_, which is a pointer to _FILE_.


h2. Generate, build and run the model

Before you can run the model you should copy one of the generated C source files into the project folder and name it _test.txt_. 

!images/036-RemoveCommentC07.png!

Generate, build and run the model.

Your output should start like this:

!images/036-RemoveCommentC08.png!


h2. Summary

This tutorial should help you to train the necessary steps to create a C model. By the way you have seen how to create your own type system for a real embedded project. An additional aspect was to show how simple it is to separate different aspects of the required functionality by the use of actors and protocols and make them reusable.


h1. ROOM Concepts

This chapter gives an overview over the ROOM language elements and their textual and graphical notation.
The formal ROOM grammar based on Xtext (EBNF) you can find here: "ROOM Grammar":http://git.eclipse.org/c/etrice/org.eclipse.etrice.git/tree/plugins/org.eclipse.etrice.core.room/src/org/eclipse/etrice/core/Room.xtext

h2. Actors

h3. Description
 
The actor is the basic structural building block for building systems with ROOM. An actor can be refined hierarchically and thus can be of arbitrarily large scope. Ports define the interface of an actor. An Actor can also have a behavior usually defined by a finite state machine.

h3. Motivation

* Actors enable the construction of hierarchical structures by composition and layering
* Actors have their own logical thread of execution
* Actors can be freely deployed
* Actors define potentially reusable blocks

h3. Notation

<table title="Actor Class Notation" frame="box" border="2" cellpadding="3" cellspacing="0" >
	<tr>
		<td align="center">*Element*</td>
		<td align="center">*Graphical Notation*</td>
		<td align="center">*Textual Notation*</td>
	</tr>
	<tr>
		<td>ActorClass</td>
		<td>!images/040-ActorClassNotation.png!</td>
		<td>!images/040-ActorClassTextualNotation.png!</td>
	</tr>
	<tr>
		<td>ActorRef</td>
		<td>!images/040-ActorReferenceNotation.png!</td>
		<td>!images/040-ActorReferenceTextualNotation.png!</td>
	</tr>
</table> 

h3. Details

h4.  Actor Classes, Actor References, Ports and Bindings

An *ActorClass* defines the type (or blueprint) of an actor. Hierarchies are built by ActorClasses that contain *ActorReferences* which have another ActorClass as type. The interface of an ActorClass is always defined by Ports. The ActorClass can also contain Attributes, Operations and a finite state machine. 

*External Ports* define the external interface of an actor and are defined in the *Interface* section of the ActorClass.

*Internal Ports* define the internal interface of an actor and are defined in the *Structure* section of the ActorClass.

*Bindings* connect Ports inside an ActorClass.

Example:

<table title="Actor Class Example" frame="box" border="2" cellpadding="3" cellspacing="0" >
	<tr>
		<td align="center">*Graphical Notation*</td>
		<td align="center">*Textual Notation*</td>
	</tr>
	<tr>
		<td>!images/040-ActorClass.png!</td>
		<td>!images/040-ActorClassExampleTextualNotation.png!</td>
	</tr>
</table> 

* _ActorClass1_ contains two ActorReferences (of ActorClass2 and ActorClass3)
* _port1_ is a *External End Port*. Since it connects external Actors with the behavior of the ActorClass, it is defined in the *Interface* section and the *Structure* section of the ActorClass.
* _port2_ and _port3_ are *Internal End Ports* and can only be connected to the ports of contained ActorReferences. Internal End Ports connect the Behavior of an ActorClass with its contained ActorReferences.
* _port4_ is a relay port and connects external Actors to contained ActorReferences. This port can not be accessed by the behavior of the ActorClass.
* _port5_ through _port9_ are Ports of contained ActorReferences. _port8_ and _port9_ can communicate without interference with the containing ActorClass.
* *Bindings* can connect ports of the ActorClass and its contained ActorReferences. 

h4.  Attributes

Attributes are part of the Structure of an ActorClass. They can be of a PrimitiveType or a DataClass.

Example:

!images/040-ActorClassAttributes.png!

h4.  Operations

Operations are part of the Behavior of an ActorClass.  Arguments and return values can be of a PrimitiveType or a DataClass. DataClasses can be passed by value (implicit) or by reference (keyword *ref*).

Example:

!images/040-ActorClassOperations.png!

h2. Protocols

h3. Description

A ProtocolClass defines a set of incoming and outgoing messages that can be exchanged between two ports.
The exact semantics of a message is defined by the execution model.

h3. Motivation

* ProtocolClasses provide a reusable interface specification for ports
* ProtocolClasses can optionally specify valid message exchange sequences

h3. Notation

ProtocolClasses have only textual notation. 
The example defines a ProtocolClass with 2 incoming and two outgoing messages. Messages can have data attached. The data can be of a primitive type (e.g. int32, float64, ...) or a DataClass.

!images/040-ProtocolClassTextualNotation.png!

h2. Ports

h3. Description

Ports are the only interfaces of actors. A port has always a protocol assigned. 
Service Access Points (SAP) and Service Provision Points (SPP) are specialized ports that are used to define layering.

h3. Motivation

* Ports decouple interface definition (Protocols) from interface usage
* Ports decouple the logical interface from the transport 

h3. Notation

h4. Class Ports

These symbols can only appear on the border of an actor class symbol. 

Ports that define an external interface of the ActorClass, are defined in the _Interface_. Ports that define an internal interface are defined in the _Structure_ (e.g. internal ports).
* *External End Ports* are defined in the Interface and the Structure
* *Internal End Ports* are only defined in the Structure
* *Relay Ports* are only defined in the Interface
* *End Ports* are always connected to the internal behavior of the ActorClass
* *Replicated Ports* can be defined with a fixed replication factor ( e.g. _Port port18 [ 5 ]: ProtocolClass1_ ) or a variable replication factor (e.g. _Port port18[ * ]: ProtocolClass1_ )

<table title="Class Port Notation" frame="box" border="2" cellpadding="3" cellspacing="0">
	<tr>
		<td align="center">*Element*</td>
		<td align="center" width="15%">*Graphical Notation*</td>
		<td align="center">*Textual Notation*</td>
	</tr>
	<tr>
		<td>Class End Port</td>
		<td align="center">!images/040-ClassEndPort.png!</td>
		<td>
			*External Class End Port:*
			!images/040-ClassEndPortTextual.png!
			*Internal Class End Port:*
			!images/040-ClassEndPortInternalTextual.png!
		</td>
	</tr>
	<tr>
		<td>Conjugated Class End Port</td>
		<td align="center">!images/040-ConjugatedClassEndPort.png!</td>
		<td>
			*External Conjugated Class End Port:*
			!images/040-ConjugatedClassEndPortTextual.png!
			*Internal Conjugated Class End Port:*
			!images/040-ConjugatedClassEndPortInternalTextual.png!
		</td>
	</tr>
	<tr>
		<td>Class Relay Port</td>
		<td align="center">!images/040-ClassRelayPort.png!</td>
		<td>
			!images/040-ClassRelayPortTextual.png!
		</td>
	</tr>
	<tr>
		<td>Conjugated Class Relay Port</td>
		<td align="center">!images/040-ConjugatedClassRelayPort.png!</td>
		<td>
			!images/040-ConjugatedClassRelayPortTextual.png!
		</td>
	</tr>
	<tr>
		<td>Replicated Class End Port</td>
		<td align="center">!images/040-ReplicatedClassEndPort.png!</td>
		<td>
			*External Replicated Class End Port:*
			!images/040-ReplicatedClassEndPortTextual.png!
			*Internal Replicated Class End Port:*
			!images/040-ReplicatedClassEndPortInternalTextual.png!
		</td>
	</tr>
	<tr>
		<td>Conjugated Replicated Class End Port</td>
		<td align="center">!images/040-ConjugatedReplicatedClassEndPort.png!</td>
		<td>
			*External Conjugated Replicated Class End Port:*
			!images/040-ConjugatedReplicatedClassEndPortTextual.png!
			*Internal Conjugated Replicated Class End Port:*
			!images/040-ConjugatedReplicatedClassEndPortInternalTextual.png!
		</td>
	</tr>
	<tr>
		<td>Replicated Class Relay Port</td>
		<td align="center">!images/040-ReplicatedClassRelayPort.png!</td>
		<td>
			!images/040-ReplicatedClassRelayPortTextual.png!
		</td>
	</tr>
	<tr>
		<td>Conjugated Replicated Class Relay Port</td>
		<td align="center">!images/040-ConjugatedReplicatedClassRelayPort.png!</td>
		<td>
			!images/040-ConjugatedReplicatedClassRelayPortTextual.png!
		</td>
	</tr>
</table>

h4. Reference Ports

These symbols can only appear on the border of an ActorReference symbol. Since the type of port is defined in the ActorClass, no textual notation for the Reference Ports exists.

<table title="Title" frame="box" border="2" cellpadding="3" cellspacing="0">
	<tr>
		<td align="center">*Element*</td>
		<td align="center">*Graphical Notation*</td>
		<td align="center">*Textual Notation*</td>
	</tr>
	<tr>
		<td>Reference Port</td>
		<td align="center">!images/040-ReferencePort.png!</td>
		<td align="center">_implicit_</td>
	</tr>
	<tr>
		<td>Conjugated Reference Port</td>
		<td align="center">!images/040-ConjugatedReferencePort.png!</td>
		<td align="center">_implicit_</td>
	</tr>
	<tr>
		<td>Replicated Reference Port</td>
		<td align="center">!images/040-ReplicatedReferencePort.png!</td>
		<td align="center">_implicit_</td>
	</tr>
	<tr>
		<td>Conjugated Replicated Reference Port</td>
		<td align="center">!images/040-ConjugatedReplicatedReferencePort.png!</td>
		<td align="center">_implicit_</td>
	</tr>
</table>

h2. DataClass

h3. Description

The DataClass enables the modeling of hierarchical complex datatypes and operations on them. The DataClass is the equivalent to a Class in languages like Java or C++, but has less features. The content of a DataClass can always be sent via message between actors (defined as message data in ProtocolClass).

h3. Notation
  
Example: DataClass using PrimitiveTypes

!images/040-DataClass1.png!

Example: DataClass using other DataClasses:

!images/040-DataClass2.png!

h2. Layering

h3. Description

In addition to the Actor containment hierarchies, Layering provides another method to hierarchically structure a software system. Layering and actor hierarchies with port to port connections can be mixed on every level of granularity.
# an ActorClass can define a Service Provision Point (SPP) to publish a specific service, defined by a ProtocolClass
# an ActorClass can define a Service Access Point (SAP) if it needs a service, defined by a ProtocolClass
# for a given Actor hierarchy, a LayerConnection defines which SAP will be satisfied by (connected to) which SPP

h3. Notation

<table title="Title" frame="box" border="2" cellpadding="3" cellspacing="0">
	<tr>
		<td align="center">*Description*</td>
		<td align="center">*Graphical Notation*</td>
		<td align="center">*Textual Notation*</td>
	</tr>
	<tr>
		<td>The Layer Connections in this model define which services are provided by the _ServiceLayer_  (_digitalIO_ and _timer_)</td>
		<td>!images/040-LayeringModel.png!</td>
		<td>!images/040-LayeringModelTextual.png!</td>
	</tr>
	<tr>
		<td>The implementation of the services (SPPs) can be delegated to sub actors. In this case the actor _ServiceLayer_ relays (delegates) the implementation services _digitalIO_ and _timer_ to sub actors</td>
		<td>!images/040-LayeringServiceLayer.png!</td>
		<td>!images/040-LayeringServiceLayerTextual.png!</td>
	</tr>
	<tr>
		<td>Every Actor inside the _ApplicationLayer_ that contains an SAP with the same Protocol as _timer_ or _digitalIO_ will be connected to the specified SPP</td>
		<td>!images/040-LayeringApplicationLayer.png!</td>
		<td>!images/040-LayeringApplicationLayerTextual.png!</td>
	</tr>
</table>

h2. Finite State Machines

h3. Description

Definition from "Wikipedia":http://en.wikipedia.org/wiki/Finite-state_machine:

bq. 
A finite-state machine (FSM) or finite-state automaton (plural: automata), or simply a state machine, is a mathematical model used to design computer programs and digital logic circuits. It is conceived as an abstract machine that can be in one of a finite number of states. The machine is in only one state at a time; the state it is in at any given time is called the current state. It can change from one state to another when initiated by a triggering event or condition, this is called a transition. A particular FSM is defined by a list of the possible states it can transition to from each state, and the triggering condition for each transition.

In ROOM each actor class can implement its behavior using a state machine. Events occurring at the end ports of an actor will be forwarded to and processed by the state machine. Events possibly trigger state transitions.

h3. Motivation

For event driven systems a finite state machine is ideal for processing the stream of events. Typically during processing new events are produced which are sent to peer actors.

We distinguish flat and hierarchical state machines.

h3. Notation

h4. Flat Finite State Machine

The simpler flat finite state machines are composed of the following elements:

<table title="Title" frame="box" border="2" cellpadding="3" cellspacing="0">
	<tr>
		<td align="center">*Description*</td>
		<td align="center">*Graphical Notation*</td>
		<td align="center">*Textual Notation*</td>
	</tr>
	<tr>
		<td>State</td>
		<td>!images/040-State.jpg!</td>
		<td>!images/040-StateTextual.jpg!</td>
	</tr>
	<tr>
		<td>InitialPoint</td>
		<td>!images/040-InitialPoint.jpg!</td>
		<td>_implicit_</td>
	</tr>
	<tr>
		<td>TransitionPoint</td>
		<td>!images/040-TransitionPoint.jpg!</td>
		<td>!images/040-TransitionPointTextual.jpg!</td>
	</tr>
	<tr>
		<td>ChoicePoint</td>
		<td>!images/040-ChoicePoint.jpg!</td>
		<td>!images/040-ChoicePointTextual.jpg!</td>
	</tr>
	<tr>
		<td>Initial Transition</td>
		<td>!images/040-InitialTransition.jpg!</td>
		<td>!images/040-InitialTransitionTextual.jpg!</td>
	</tr>
	<tr>
		<td>Triggered Transition</td>
		<td>!images/040-TriggeredTransition.jpg!</td>
		<td>!images/040-TriggeredTransitionTextual.jpg!</td>
	</tr>
</table>

h4. Hierarchical Finite State Machine

The hierarchical finite state machine adds the notion of a sub state machine nested in a state.
A few modeling elements are added to the set listed above:

<table title="Title" frame="box" border="2" cellpadding="3" cellspacing="0">
	<tr>
		<td align="center">*Description*</td>
		<td align="center">*Graphical Notation*</td>
		<td align="center">*Textual Notation*</td>
	</tr>
	<tr>
		<td>State with sub state machine</td>
		<td>Parent State
		!images/040-StateWithSubFSM.jpg!
		Sub state machine
		!images/040-SubFSM.jpg!</td>
		<td>!images/040-StateWithSubFSMTextual.jpg!</td>
	</tr>
	<tr>
		<td>Entry Point</td>
		<td>In sub state machine
		!images/040-EntryPoint.jpg!
		On parent state
		!images/040-EntryPointRef.jpg!</td>
		<td>!images/040-EntryPointTextual.jpg!</td>
	</tr>
	<tr>
		<td>Exit Point</td>
		<td>In sub state machine
		!images/040-ExitPoint.jpg!
		On parent state
		!images/040-ExitPointRef.jpg!</td>
		<td>!images/040-ExitPointTextual.jpg!</td>
	</tr>
</table>

h3. Examples

h4. Example of a flat finite state machine:

!images/040-FlatFSM.jpg!

h4. Example of a hierarchical finite state machine:

Top level
!images/040-HierarchicalFSMTop.jpg!

Sub state machine of Initializing
!images/040-HierarchicalFSMInitializing.jpg!

Sub state machine of Running
!images/040-HierarchicalFSMRunning.jpg!


Back to the top