reference.textile 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. <link href="../../css/bootstrap.css" rel="stylesheet" />
  2. h1. SCT Reference
  3. h2. Statechart elements
  4. In the following the state chart elements of the YAKINDU SCT 2 editor are described. The meta model of the YAKINDU SCT 2 is the model of finite state machines. It is based on the view of a system that is defined by a finite number of states. The behavior of that system is based on the active states. These states are determined by the history of the state machine. Very important are the theoretical models for state machines by Mealy and Moore. Mealy state machines associate actions with transitions. Moore machines associate actions with states (entry, exit). In the YAKINDU SCT 2 both is possible.
  5. The YAKINDU SCT 2 meta model is designed similar to the UML state chart meta model with the following differences
  6. * they are self contained with interfaces defined by events and variables
  7. * core execution semantics are cycle driven, not event driven
  8. ** this allows to process concurrent events
  9. ** event driven behavior can be defined on top
  10. * time is an abstract concept for state charts
  11. * time control is delegated to the environment
  12. The model interpreter and different flavors of generated code follow these same core semantics.
  13. Please refer to the description of the "UML Statecharts":http://en.wikipedia.org/wiki/UML_state_machine for more details.
  14. h3. Regions
  15. As already mentioned the YAKINDU state charts are self contained. They are organized in regions. Due to this it is possible to organize multiple state machines in different regions and to run them concurrently.
  16. !images/parallelRegions.jpg!
  17. h3. States
  18. States are the central elements of a state machine. A state has to be placed inside a region and needs a unique name inside this region. During simulation each state can be active or passive. An active state has actions that are accomplished. Either an action is carried out on entering a state, during active state or on exit.
  19. h3. Transitions
  20. A transition is the transfer of one state to another. Transitions are diagrammed as arrows and can carry events and actions but must not.
  21. The syntax of events and actions is defined by a textual description language (#Statechartdescriptionlanguage). Please refer to the documentation section "Events":#Events for more details. For more details on Actions refer to the chapter "Actions":#ReactionTriggers.
  22. If a state has more than one outgoing transition without event that transition is carried out first that was modeled first.
  23. h3. Initial state and final state
  24. Initial and final states are pseudo states, because the state chart does not rest on them. Pseudo states express characteristics that are impossible to express by simple states.
  25. The initial state is always the first state that is active during interpretation or simulation of the state machine. An initial state can only have one outgoing transition and no incoming. This transition has no events or actions.
  26. Inside a region only one initial state is allowed, but every region can have an initial state.
  27. h3. Choice
  28. Choice is also a pseudo state. It can be used to model a conditional path. Choice nodes divide a transition into multiple parts.
  29. Usually the first transition points towards the choice node. One of the choice outgoing transitions can carry a condition.
  30. h3. Junction
  31. A junction is a pseudo state do combine transitions. This is very comfortable if a state machine has many similar transitions. Junctions add clear arrangement to the state machine.
  32. h3. Composite State
  33. A composite state is a state that is composed of other state machines. These are also organized in regions. Besides the simple composite state YAKINDU knows two kinds of composite states: orthogonal state and submachine states.
  34. Composite states contain other state machine branches.
  35. h4. Orthogonal states
  36. In the context of state machines orthogonal states are states that are independent from each other. The most famous example is the keyboard example:
  37. !images/orthogonalState_example.jpg!
  38. h4. Submachine states
  39. Submachine states may contain complete state machines. Here the user can chose another state machine to be included or create a new sub statemachine. During simulation only the top level statemachine is interpreted. It is not possible to jump to the sub level state machines and back.
  40. !images/substatemachine_example.jpg!
  41. h3. Shallow History
  42. The shallow history state is a pseudo state that is placed inside regions of composite states. It is used to 'remember' the last active state inside a composite state. So it is possible to jump to this state instead of starting at the inner entry state again. The following example of a questionaire answering will explain this:
  43. !images/shallowHistory01.jpg!
  44. The interesting parts in this state chart are the events _checkProgress_ and _goon_. CheckProgress jumps back to the init state while assigning the current progress count to the variable _temp_. _goon_ jumps to the shallow history state that was placed inside the composite state.
  45. !images/shallowHistory02.jpg!
  46. !images/shallowHistory03.jpg!
  47. On triggering the _goon_ event the last active state is activated again.
  48. h3. Deep History
  49. Deep history is similar to shallow history but more complex. With a deep history the latest state of multiple nested states is remembered.
  50. h2. Statechart description language
  51. The textual description language is used to declare and describe behaviors in the state machine. It is case sensitive.
  52. h3. Typesystem
  53. The language has an integrated small typesystem with the following simple types:
  54. * integer
  55. * real
  56. * boolean
  57. * string
  58. * void
  59. So events and variables can be declared with types:
  60. bc..
  61. var intVar : integer
  62. var realVar : real
  63. var boolVar : boolean
  64. var stringVar : string
  65. var voidVar : void
  66. event addInt : integer
  67. event checkValidity : boolean
  68. h3. Expressions
  69. Expressions can be defined similar to other programming languages. The language offers operators to define logical expressions, bitwise arithmetic, and arithmetic expressions and bit shifting.
  70. Logical expressions are similar to other programming languages. The return type is *boolean*. In the following there are some examples of these:
  71. h4. Logical AND
  72. bc..
  73. var1 && var2
  74. h4. Logical OR
  75. bc..
  76. var1 || var2
  77. h4. Logical NOT
  78. bc..
  79. !var1
  80. h4. Conditional expression
  81. bc..
  82. var1 ? var2 : 23
  83. h4. Bitwise XOR
  84. bc..
  85. var1 ^ var2
  86. h4. Bitwise OR
  87. bc..
  88. var1 | var2
  89. h4. Bitwise AND
  90. bc..
  91. var1 & var2
  92. h4. Logical Relations and Shift Operators
  93. |less than | < |
  94. |equal or less than | <= |
  95. |greater than | > |
  96. |equal or greater than | >= |
  97. |equal | == |
  98. |not equal | != |
  99. |shift left | << |
  100. |shift right | >> |
  101. h4. Binary arithmetic operators
  102. |plus | + |
  103. |minus | - |
  104. |multiply | * |
  105. |divide | / |
  106. |modulo | % |
  107. h4. Unary arithmetic operators
  108. |positive | + |
  109. |negative | - |
  110. |complement | ~ |
  111. h3. Statements
  112. A statements can be either an assignment, raising an event or call an operation. The language has the following assignment operators:
  113. * simple assignment: =
  114. * multiply and assign: *=
  115. * divide and assign: /=
  116. * calculate modulo and assign: %=
  117. * add and assign: +=
  118. * subtract and assign: -=
  119. * bitshift left and assign: <<=
  120. * bitshift right and assign: >>=
  121. * bitwise AND and assign: &=
  122. * bitwise XOR and assign: ^=
  123. * bitwise OR and assign: @|=@
  124. An event is raised by the keyword _raise_ followed by the event name and if it is an interface event the name of the interface.
  125. An operation is called similar to other programming languages with the operation name and passing concrete parameters. The parameters can be expressions.
  126. h3. Scopes
  127. ==<!-- Start stext_keyword_namespace -->==
  128. h4. Namespace
  129. The language allows to define unique namespaces, which can be used to qualify references to the statechart.
  130. bc..
  131. namespace trafficlights
  132. p. ==<!-- End stext_keyword_namespace -->==
  133. ==<!-- Start stext_keyword_interface -->==
  134. h4. interface scope
  135. Declarations in the interface scope are externally visible. They can be shared within the environment.
  136. bc..
  137. interface NamedInterface:
  138. in event event1
  139. out event event3
  140. var variable1 : real
  141. entrypoint entry1
  142. exitpoint exit1
  143. p. ==<!-- End stext_keyword_interface -->==
  144. ==<!-- Start stext_keyword_internal -->==
  145. h4. internal scope
  146. Declarations made in an internal scope are only visible for contained states.
  147. bc..
  148. internal:
  149. var localVariable1: integer
  150. event localEvent: integer
  151. local event localEvent2: NamedInterface.event1 || localEvent
  152. local event localEvent3: localEvent || localEvent2 : 25
  153. operation localOperation (integer, integer): integer
  154. localEvent3 / raise NamedInterface.event3 :
  155. localOperation(valueOf(localEvent),NamedInterface.variable1);
  156. p. ==<!-- End stext_keyword_internal -->==
  157. h3. Declarations
  158. Within scopes there can be declarations of Events, Variables, Operations, LocalReactions, EntryPoints and ExitPoints.
  159. ==<!-- Start stext_keyword_event -->==
  160. h3. Events
  161. Within interface scope events have an direction. They can either be ingoing or outgoing:
  162. bc..
  163. interface NamedInterface:
  164. in event event1
  165. out event event2
  166. p. Within local scope events can carry variables:
  167. bc..
  168. internal:
  169. event localEvent1 : integer
  170. p. Local events can be derived from interface events or other local events and can have a value assignment:
  171. bc..
  172. internal:
  173. event localEvent1: integer
  174. local event localEvent2 = NamedInterface.event1 || localEvent1
  175. local event localEvent3 = localEvent2 || 25
  176. p. ==<!-- End stext_keyword_event -->==
  177. ==<!-- Start stext_keyword_var -->==
  178. h3. Variables
  179. Variables can have different visibilities. They can be visible for the environment:
  180. bc..
  181. var variable1: real
  182. p. Variables can be *readonly* (constants):
  183. bc..
  184. var readonly pi: real = 3.1415
  185. p. Variables can be referenced by the environment.
  186. bc..
  187. var external variable3: integer = 34
  188. p. ==<!-- End stext_keyword_var -->==
  189. h3. Reaction Triggers
  190. Actions are key constructs in state machines to model behavior. The YAKINDU SCT 2 knows the following kinds of actions.
  191. ==<!-- Start stext_keyword_after -->==
  192. h4. after
  193. The _after_ trigger specifies one-shot time events.
  194. After the specified time the reaction is triggered. An _after_ trigger can be used in transitions of states as well in local reactions of states and statecharts. The specified time starts when the state or statechart is entered.
  195. bc. after 20 s
  196. Structure:
  197. @after@ _@time@_ (_@unit@_)?
  198. The time unit can be:
  199. * ==<!-- Start stext_keyword_s -->== s - seconds ==<!-- End stext_keyword_s -->==
  200. * ==<!-- Start stext_keyword_ms -->== ms - milliseconds ==<!-- End stext_keyword_ms -->==
  201. * ==<!-- Start stext_keyword_us -->== us - microseconds ==<!-- End stext_keyword_us -->==
  202. * ==<!-- Start stext_keyword_ns -->== ns - nanoseconds ==<!-- End stext_keyword_ns -->==
  203. * empty - implies seconds
  204. p. ==<!-- End stext_keyword_after -->==
  205. ==<!-- Start stext_keyword_every -->==
  206. h4. every
  207. The _every_ trigger specifies periodic time events.
  208. The reaction is triggered periodically after the specified time. An _every_ trigger can be used in transitions of states as well in local reactions of states and statecharts. The specified time starts when the state or statechart is entered and repeats periodically.
  209. bc. every 200 ms
  210. Structure:
  211. @every@ _@time@_ (_@unit@_)?
  212. The time unit can be:
  213. * s - seconds
  214. * ms - milliseconds
  215. * us - microseconds
  216. * ns - nanoseconds
  217. * empty - implies seconds
  218. ==<!-- End stext_keyword_every -->==
  219. ==<!-- Start stext_keyword_always -->==
  220. h4. always
  221. This trigger is always true and enables a reaction to be executed in every run to completion step (RTS). It is equivalent to _oncycle_.
  222. ==<!-- End stext_keyword_always -->==
  223. ==<!-- Start stext_keyword_default -->==
  224. ==<!-- Start stext_keyword_else -->==
  225. h4. default, else
  226. The _default_ trigger is equivalent to the _else_ trigger. It is intended for use for the outgoing transitions of _choice_ pseudo states, to make sure that always an outgoing transition can be taken. It can only be be used in transitions and implies the lowest evaluation priority for that transition.
  227. ==<!-- End stext_keyword_else -->==
  228. ==<!-- End stext_keyword_default -->==
  229. ==<!-- Start stext_keyword_entry -->==
  230. h4. entry
  231. An _entry_ trigger marks actions that are carried out on entering a state or state machine.
  232. ==<!-- End stext_keyword_entry -->==
  233. ==<!-- Start stext_keyword_exit -->==
  234. h4. exit
  235. An _exit_ trigger marks actions that are carried out on exiting a state or state machine.
  236. ==<!-- End stext_keyword_exit -->==
  237. ==<!-- Start stext_keyword_oncycle -->==
  238. h4. oncycle
  239. The _oncycle_ trigger is always true and enables a reaction to be executed in every run to completion step (RTS). It is equivalent to _always_.
  240. ==<!-- End stext_keyword_oncycle -->==
  241. ==<!-- Start stext_keyword_operation -->==
  242. h3. Operations
  243. Operations can have none, one or multiple parameters. The parameters are only declarated by their type. An operation can have one return type similar to Java.
  244. bc..
  245. operation localOperation (integer, integer):integer
  246. localEvent3/ raise NamedInterface3.event1
  247. p.
  248. ==<!-- End stext_keyword_operation -->==
  249. h3. Build-In Functions
  250. ==<!-- Start stext_keyword_valueof -->==
  251. h4. valueof(event)
  252. Returns the value of an valued event that it passed to the function as parameter.
  253. bc..
  254. myVar = valueof(myEvent)
  255. p.
  256. ==<!-- End stext_keyword_valueof -->==
  257. ==<!-- Start stext_keyword_active -->==
  258. h4. active(state)
  259. Returns "true" if a state is active or "false" otherwise.
  260. bc..
  261. myBool = active(StateA)
  262. p.
  263. ==<!-- End stext_keyword_active -->==
  264. h3. LocalReactions
  265. Local reactions describe the internal behavior of a state. So they have internal scope. A local reaction is declared as follows:
  266. bc..
  267. LocalReaction: ReactionTrigger '/' ReactionEffect ('#' ReactionProperties)?
  268. ReactionTrigger: (Event ("," Event )* (=> '[' Expression ']')?) | '[' Expression ']'
  269. ReactionEffect: Statement (';' Statement )* (';')?
  270. Statement: Assignment | EventRaising | OperationCall
  271. ReactionProperties: (EntryPoint | ExitPoint)*
  272. p. Within a local reaction an interface event can be raised:
  273. bc..
  274. internal:
  275. localEvent1 / raise NamedInterface.event3 : localOperation (valueOf(localEvent), NamedInterface.variable1);
  276. p. Local reactions can have priority values. These are defined by a following # and the integer number of priority:
  277. bc..
  278. localEvent2 / NamedInterface.variable2 += 3; #1
  279. localEvent3 / NamedInterface.variable4 += 2.0; #2
  280. p. ==<!-- Start stext_keyword_entrypoint -->==
  281. h3. EntryPoints
  282. Every state chart has an entry point. An entry point can be declared like the following:
  283. bc..
  284. entrypoint entry1
  285. p. ==<!-- End stext_keyword_entrypoint -->==
  286. ==<!-- Start stext_keyword_exitpoint -->==
  287. h3. ExitPoints
  288. Every state chart has an exit point. This exit point can be declared like the following.
  289. bc..
  290. exitpoint exit1
  291. p. ==<!-- End stext_keyword_exitpoint -->==
  292. h2. SGen Generator Features
  293. All generators can be customized with a generator model. This is a textual model file where generator features, like i.e. the outlet path, can be specified. The following screenshot shows an example configuration for the java code generator.
  294. To get started with the generator model, we included a new Eclipse wizard that creates a basic configuration file with default values.
  295. !images/sGenEditor.png!
  296. The generator model is associated with the builder. If *Project* > *Build Automatically* is checked the files are generated. In the following the specific customizing features of the generator models are explained.
  297. The following section describes the *Core Features* which are available for all code generators:
  298. ==<!-- Start sgen_feature_outlet -->==
  299. h4. Outlet
  300. The *Outlet* feature specifies the target project and folder for the generated artifacts. It is a *required* feature and consists of the following parameters:
  301. # __targetProject__ (String, required): The project to store the generated artifacts
  302. # __targetFolder__ (String, required): The folder to store the generated artifacts
  303. Example configuration:
  304. bc..
  305. feature Outlet {
  306. targetProject = "ExampleProject"
  307. targetFolder = "src-gen"
  308. }
  309. p. ==<!-- End sgen_feature_outlet -->==
  310. ==<!-- Start sgen_feature_licenseheader -->==
  311. h4. LicenseHeader
  312. The *LicenseHeader* feature specifies the license text that should be added as a header to the generated artifacts. It is an *optional* feature and consists of the following parameters:
  313. # __licenseText__ (String, required): The license text to add as a header
  314. Example configuration:
  315. bc..
  316. feature LicenseHeader {
  317. licenseText = "Copyright (c) 2012 committers of YAKINDU and others."
  318. }
  319. p. ==<!-- End sgen_feature_licenseheader -->==
  320. ==<!-- Start sgen_feature_functioninlining -->==
  321. h4. FunctionInlining
  322. The *FunctionInlining* feature allows the inlining of expressions instead of generating separate functions or methods. This might reduce the readability of the generated code, but increases performance because less operation calls are necessary.
  323. It is an *optinal* feature and consists of the following parameters:
  324. # __inlineReactions__ (Boolean, optional): Inlines the expression for reactions
  325. # __inlineEntryActions__ (Boolean, optional): Inlines the expression for entry actions
  326. # __inlineExitActions__ (Boolean, optional): Inlines the expression for exit actions
  327. # __inlineEnterSequences__ (Boolean, optional): Inlines the expression for enter sequences
  328. # __inlineExitSequences__ (Boolean, optional): Inlines the expression for exit sequences
  329. # __inlineChoices__ (Boolean, optional): Inlines the expression for choices
  330. # __inlineEnterRegion__ (Boolean, optional): Inlines the expression for enter regions
  331. # __inlineExitRegion__ (Boolean, optional): Inlines the expression for exit regions
  332. # __inlineEntries__ (Boolean, optional): Inlines the expression for entries
  333. Example configuration:
  334. bc..
  335. feature FunctionInlining {
  336. inlineChoices = false
  337. inlineEnterRegion = true
  338. inlineEntries = true
  339. }
  340. p. ==<!-- End sgen_feature_functioninlining -->==
  341. ==<!-- Start sgen_feature_debug -->==
  342. h4. Debug
  343. The *Debug* feature dumps the Execution Model to the target folder as xmi model. It is an *optional* feature and consists of the following parameters:
  344. # __dumpSexec__ (Boolean, required): The license text to add as a header
  345. Example configuration:
  346. bc..
  347. feature Debug {
  348. dumpSexec = true
  349. }
  350. p. ==<!-- End sgen_feature_debug -->==
  351. h2. Java Generator Features
  352. ==<!-- Start sgen_feature_naming -->==
  353. h4. Naming
  354. The *Naming* feature allows the configuration of package names as well as class name prefix / suffix.
  355. It is an *optional* feature and consists of the following parameters:
  356. # __basePackage__ (Boolean, required): The package to create for the generated java classes
  357. # __implementationSuffix__ (Boolean, optional): The suffix for the implementing classes
  358. Example configuration:
  359. bc..
  360. feature Naming {
  361. basePackage = "org.yakindu.sct"
  362. implementationSuffix = "Impl"
  363. }
  364. p. ==<!-- End sgen_feature_naming -->==
  365. ==<!-- Start sgen_feature_generalfeatures -->==
  366. h4. GeneralFeatures
  367. The *GeneralFeatures* feature allows to configure additional services to generate with the statemachine. Per default, all parameters are configured to __false__ It is an *optional* feature and consists of the following parameters:
  368. ==<!-- # __EventBasedStatemachine__ (Boolean, optional): Enables/disables the generation of a cycle based statemachine implementation -->==
  369. # __InterfaceObserverSupport__ (Boolean, optional): Enables/disables the generation of listener interfaces for the statemachine
  370. # __RuntimeService__ (Boolean, optional): Enables/disables the generation of a runtime service that triggers the runcycle of a cycle based statemachine
  371. # __TimerService__ (Boolean, optional): Enables/disables the generation of a timer service implementation using __java.util.Timer__
  372. ==<!-- # __GenericInterfaceSupport__ (Boolean, optional): Enables/disables the generation of generic interfaces -->==
  373. ==<!-- # __StatemachineFactorySupport__ (Boolean, optional): Enables/disables the generation of a factory class -->==
  374. Example configuration:
  375. bc..
  376. feature GeneralFeatures {
  377. InterfaceObserverSupport = true
  378. RuntimeService = true
  379. TimerService = true
  380. }
  381. p. ==<!-- End sgen_feature_generalfeatures -->==
  382. h2. Create Custom Code Generators
  383. YAKINDU Statechart Tools provides a rich feature set to supports custom code generators out of the box. These code generators can be either written in Java, "Xtend":http://www.eclipse.org/xtend/ or in "Xpand":http://www.eclipse.org/modeling/m2t/?project=xpand
  384. h3. Writing a custom code generator with Xtend2/Java
  385. First, you have to create a new Xtend2 generator project. Click *File* > *New* > *Other...* > *YAKINDU* > *YAKINDU Xtend2/Java Generator Project* to create a new Xtend2 Generator Project.
  386. !images/xtendGenerator.png!
  387. The wizards asks for a *Project name* and the name of the *Generator class*, where you have to specify a full qualified class name. If you check the *Use Xtend* checkbox, the Generator class will be initially created as an "Xtend":http://www.eclipse.org/xtend/ class. Otherwise, Java will be used for the generator.
  388. The check box *Configure for Plugin Export* adds all required extension point registrations to the new project for exporting as a plugin The Generator Model can refer to the new Generator Plugin via its unique *Generator ID*. If you want to contribute custom generator features for your code generator, check the *Create Feature Library* check box.
  389. After click on *Finish* a new project is created in your workspace. All required plugin dependencies and extension points are registered and you can start to write your code generator based on the ExecutionFlow meta model [Link].
  390. h3. Executing a custom Xtend2/Java code generator
  391. YAKINDU Statechart Tools provide a convenient way to execute your generator while you are developing it.
  392. Therefore, you have to create a new *Generator Model* with the generator id *yakindu::generic*, either by using the *New Statechart Generator Model* wizard or by simple creating a new text file with the file extension *.sgen*. the following feature allows to configure your code generator.
  393. ==<!-- Start sgen_feature_generator -->==
  394. h4. Generator
  395. The *Generator* feature allows the configuration of a custom code generator located in the workspace and written in Java or another JVM language. It is a *required* feature and consists of the following parameters:
  396. # __generatorProject__ (String, required): The name of the generator project
  397. # __generatorClass__ (String, required): The full qualified class name of the code generator class.
  398. # __configurationModule__ (String, optional): The full qualified class name for a guice module to configure the code generator
  399. Example configuration:
  400. bc..
  401. feature Generator {
  402. generatorProject = "org.yakindu.sct.mygenerator"
  403. generatorClass = "org.yakindu.sct.MyGenerator"
  404. }
  405. p. ==<!-- End sgen_feature_generator -->==
  406. h3. Executing a custom Xpand code generator
  407. to execute an xpand based custom code generator, you have to create a new *Generator Model* with the generator id *yakindu::xpand*, either by using the *New Statechart Generator Model* wizard or by simple creating a new text file with the file extension *.sgen*. the following feature allows to configure your code generator.
  408. ==<!-- Start sgen_feature_template -->==
  409. h4. Template
  410. The *Generator* feature allows the configuration of a custom code generator located in the workspace and written in Java or another JVM language. It is a *required* feature and consists of the following parameters:
  411. # __templateProject__ (String, required): The name of the generator project
  412. # __templatePath__ (String, required): The full qualified template path to the main template.
  413. Example configuration:
  414. bc..
  415. feature Template {
  416. templateProject = "ExampleProject"
  417. templatePath = "org::yakindu::sct::generator::xpand::Main::main"
  418. }
  419. p. ==<!-- End sgen_feature_template -->==
  420. h2. API specifications of the generated code
  421. In the following comments the TrafficLight example statemachine is used to describe the API specifications of the code generated by the Yakindu C and Java code generators. The following image shows the statechart. It is a model of a simple pedestrian crossing with a traffic light for pedestrians and a traffic light for the cars.
  422. !images/TrafficLight.png!
  423. h3. Specifications of Java code
  424. For Java you can checkout the project 'org.yakindusct.examples.trafficlight' from the Yakindu google code repository ( "Google code link":http://svn.codespot.com/a/eclipselabs.org/yakindu/SCT2/trunk/examples ). The Java example contains the statechart, sgen model, graphical widgets and some glue code to connect the generated code with the widgets. The graphical widgets are based on SWT. To execute the Java example you can run the file 'CrossingDemoCycleBased.java' as 'Java Application' from the eclipse 'Run As' context menu.
  425. You find the generated code in the 'src-gen' folder of the traffic light example.
  426. In the package 'org.yakindu.sct.examples.trafficlight.cyclebased' are the most basic statemachine interfaces and classes located. These are needed by each statemachine and are independend from the concrete statemachine design.
  427. h4. Interface IStatemachine
  428. The interface @IStatemachine@ is implemented by each generated statemachine:
  429. bc..
  430. package org.yakindu.sct.examples.trafficlight.cyclebased;
  431. /**
  432. * Basic interface for statemachines.
  433. *
  434. *
  435. */
  436. public interface IStatemachine {
  437. /**
  438. * Initializes the statemachine. Use to init internal variables etc.
  439. */
  440. public void init();
  441. /**
  442. * Enters the statemachine. Sets the statemachine in a defined state.
  443. */
  444. public void enter();
  445. /**
  446. * Exits the statemachine. Leaves the statemachine with a defined state.
  447. */
  448. public void exit();
  449. /**
  450. * Start a run-to-completion cycle.
  451. */
  452. public void runCycle();
  453. }
  454. p. It contains the four methods @init()@, @enter()@, @exit()@ and @runCycle()@. The @init()@ method is used to initialize the internal objects of the statemachine after instantiation. Variables are initialized to a default value. If you have initialized variables in the statechart definition these initializations are done in the init method too. The @enter()@ method should be called if the statemachine is entered. It sets the statemachine into a defined state. The @exit()@ method is used to leave a statemachine statefully. If for example a history state is used in one of the top regions the last active state is stored and the statemachine is leaved via @exit()@ and reentered via @enter()@ it continues working with this state. The @runCycle()@ method is used to trigger a run to completion step in which the statemachine evaluates arising events and computes possible state changes. A run to completion step consists in a simplified view of the following steps:
  455. * Clear list of outgoing events.
  456. * Check whether events have occurred which lead to a state change
  457. * If a state change has to be done:
  458. ** Execute exit actions of leaving state.
  459. ** Save history state if necessary.
  460. ** Set the new State active.
  461. ** Execute entry action of the new state.
  462. * Clear list of incoming events.
  463. h4. Timed statemachines
  464. In the traffic light example timing is used (after clauses). To support this the interfaces 'ITimedStatemachine', 'ITimerService' and the class 'TimeEvent' are generated.
  465. bc..
  466. package org.yakindu.sct.examples.trafficlight.cyclebased;
  467. /**
  468. * Interface for state machines which use timed event triggers.
  469. */
  470. public interface ITimedStatemachine {
  471. /**
  472. * Set the {@link ITimerService} for the state machine. It must be set
  473. * externally on a timed state machine before a run cycle can be correct
  474. * executed.
  475. *
  476. * @param timerService
  477. */
  478. public void setTimerService(ITimerService timerService);
  479. /**
  480. * Returns the currently used timer service.
  481. *
  482. * @return {@link ITimerService}
  483. */
  484. public ITimerService getTimerService();
  485. /**
  486. * Callback method if a {@link TimeEvent} occurred.
  487. *
  488. * @param timeEvent
  489. */
  490. public void onTimeEventRaised(TimeEvent timeEvent);
  491. }
  492. p. @ITimedStatemachine@ extends the generated statemachine to set an @ITimerService@ and provides a callback method @onTimeEventRaised(TimeEvent timeEvent)@ to let the timer service raise @TimeEvents@.
  493. Basically the correct handling of time has to be implemented by the developer because timer functions generally depend on the hardware target used. So for every hardware target a timer service class which implements the @ITimerService@ interface has to be developed. Let's have a look at the @ITimerService@ interface:
  494. bc..
  495. package org.yakindu.sct.examples.trafficlight.cyclebased;
  496. /**
  497. * Interface a timer service has to implement. Use to implement your own timer
  498. * service. A timer service has to be added to a timed state machine.
  499. *
  500. */
  501. public interface ITimerService {
  502. /**
  503. * Starts the timing for a given {@link TimeEvent}.
  504. *
  505. * @param event
  506. * : The TimeEvent the timer service should throw if timed out.
  507. * @param time
  508. * : Time in milliseconds after the given time event should be
  509. * triggered
  510. * @param cycleStartTime
  511. * : The absolute start time in milliseconds at which the last
  512. * run cycle was called. Can be used to produce a more accurate
  513. * timing behavior.
  514. */
  515. public void setTimer(TimeEvent event, long time, long cycleStartTime);
  516. /**
  517. * Unset the given {@link TimeEvent}. Use to unset cyclic repeated time
  518. * events.
  519. *
  520. * @param event
  521. */
  522. public void resetTimer(TimeEvent event);
  523. /**
  524. * Cancel timer service. Use this to end possible timing threads and free
  525. * memory resources.
  526. */
  527. public void cancel();
  528. /**
  529. * Returns the system time in milliseconds.
  530. *
  531. * @return the difference, measured in milliseconds, between the current
  532. * time and a defined point of time in the past.
  533. */
  534. public long getSystemTimeMillis();
  535. }
  536. p. The @ITimerService@ interface defines four methods. The @public void setTimer(TimeEvent event, long time, long cycleStartTime)@ method is called by a statemachine to tell the timer service that it has to start a timer for the given time event and raise it after the time given by the same named parameter is expired. It is important that within the 'setTimer' method only a timer thread or a hardware timer interrupt is started and no long time taking operations like Thread.sleep(...) or waiting are done. Otherwise the statemachine execution may hang within the timer service or it shows a not expected runtime behavior.
  537. To raise a @TimeEvent@ after the time is expired the method @onTimeEventRaised(TimeEvent timeEvent)@ has to be called on the statemachine (should be a @ITimedStatemachine@). So the time event is recognized by the statemachine and will be processed by the next run cycle. You can conclude that the runtime environment has to call the statemachines 'runCycle' method as often as needed to process time events raised by the timing service as fast as possible. If you have in example a time event which should be raised by the timer service after 500 ms and the runtime environment only calls the statemachines @runCycle@ method with a time period of 1000 ms the event could not be processed in the correct time.
  538. The parameter 'cycleStartTime' holds the absolute start time of the last run cycle. It can be used to reduce or remove the time offset used by the statemachines runtime operations to get a more precise timing behavior.
  539. The method @resetTimer(TimeEvent event)@ is called by the statemachine to unset the timer.
  540. The last class used by timed statemachine is @TimeEvent@:
  541. bc..
  542. package org.yakindu.sct.examples.trafficlight.cyclebased;
  543. /**
  544. * Event that reflects a time event. It's internally used by
  545. * {@link ITimedStatemachine}.
  546. *
  547. * @author muehlbrandt
  548. *
  549. * @param <T>
  550. */
  551. public class TimeEvent {
  552. private boolean periodic;
  553. private ITimedStatemachine statemachine;
  554. int index;
  555. /**
  556. * Constructor for a time event.
  557. *
  558. * @param periodic
  559. * : Set to {@code true} if event should be repeated
  560. * periodically.
  561. *
  562. * @param index
  563. * : Index position within the state machine's timeEvent array.
  564. */
  565. public TimeEvent(boolean periodic, int index) {
  566. this.periodic = periodic;
  567. this.index = index;
  568. }
  569. /**
  570. * Returns the state machine reference of the event.
  571. *
  572. */
  573. public ITimedStatemachine getStatemachine() {
  574. return statemachine;
  575. }
  576. /**
  577. * Sets the state machine reference of the event.
  578. *
  579. * @param statemachine
  580. */
  581. public void setStatemachine(ITimedStatemachine statemachine) {
  582. this.statemachine = statemachine;
  583. }
  584. public boolean isPeriodic() {
  585. return periodic;
  586. }
  587. public int getIndex() {
  588. return index;
  589. }
  590. }
  591. p. A @TimeEvent@ holds a reference to the statemachine it belongs to and a flag if it should be raised periodically. These informations are needed by the timer service implementation to raise the time event on the corresponding statemachine. The index field is used by the timed statemachine internally.
  592. h4. Default implementation of ITimerService
  593. The java code generator generates a default implementation of @ITimerService@ interface if the TimerService feature is set to 'true' in the sgen model. This implementation is based on @java.util.Timer@ and @java.util.TimerTask@ and should be compatible with the normal Oracle VM or Open JDK VM:
  594. bc..
  595. package org.yakindu.sct.examples.trafficlight.cyclebased;
  596. import java.util.HashMap;
  597. import java.util.Map;
  598. import java.util.Timer;
  599. import java.util.TimerTask;
  600. /**
  601. * Default timer service implementation.
  602. *
  603. */
  604. public class TimerService implements ITimerService {
  605. private final Timer timer = new Timer();
  606. private final Map<TimeEvent, TimerTask> timerTaskMap = new HashMap<TimeEvent, TimerTask>();
  607. public void setTimer(final TimeEvent event, long time,
  608. long cycleStartTime) {
  609. // Reset existing TimerTask for event. This step isn't necessary if
  610. // timer tasks are properly reset by sexec model.
  611. if (timerTaskMap.containsKey(event)) {
  612. resetTimer(event);
  613. }
  614. // Create a new TimerTask for given event.
  615. timerTaskMap.put(event, new TimerTask() {
  616. @Override
  617. public void run() {
  618. event.getStatemachine().onTimeEventRaised(event);
  619. }
  620. });
  621. // start scheduling the timer
  622. if (event.isPeriodic()) {
  623. timer.scheduleAtFixedRate(timerTaskMap.get(event),
  624. time - (System.currentTimeMillis() - cycleStartTime), time);
  625. } else {
  626. timer.schedule(timerTaskMap.get(event),
  627. time - (System.currentTimeMillis() - cycleStartTime));
  628. }
  629. }
  630. public void resetTimer(TimeEvent event) {
  631. if (timerTaskMap.containsKey(event) && timerTaskMap.get(event) != null) {
  632. timerTaskMap.get(event).cancel();
  633. timer.purge();
  634. }
  635. timerTaskMap.remove(event);
  636. }
  637. public void cancel() {
  638. timer.cancel();
  639. timer.purge();
  640. }
  641. public long getSystemTimeMillis() {
  642. return System.currentTimeMillis();
  643. }
  644. }
  645. h4. Runtime service
  646. The runtime service class can be used by client implementations to execute a run to completion step of a statemachine periodically.
  647. h4. Interfaces, Variable and Event access
  648. In a yakindu statechart variables and events are contained in interfaces. There could be one default interface defined (without a name) and several named interfaces. In the generated code these interfaces are defined as internal java interfaces of an interface that has the same name as the statemachine. Let's have a look at following example statechart interface declaration:
  649. bc..
  650. interface:
  651. var a:boolean
  652. in event evA:boolean
  653. out event evB:integer
  654. p. The generated interface code looks like following:
  655. bc..
  656. public interface IDefaultSMStatemachine extends IStatemachine {
  657. public interface SCInterface {
  658. public void raiseEvA(boolean value);
  659. public boolean isRaisedEvB();
  660. public int getEvBValue();
  661. public boolean getA();
  662. public void setA(boolean value);
  663. }
  664. public SCInterface getSCInterface();
  665. }
  666. p. For the unnamed statechart interface a java interface @SCInterface@ is generated. For the incoming event 'evA' a raise method with a boolean parameter is created because the event has a boolean type set. For the outgoing event 'evB' the methods @isRaisedEvB()@ and @getEvBValue()@ are generated. The first one can be used to determine if the event is raised by the statemachine and the second method serves to query the boolean value of the event. For variables getters and setters are generated too. Additionally the parent interface decribes getter methods to acquire each nested interface.
  667. The statemachine implements the parent interface by iteself and each nested interface is implemented as internal class. It holds an instance of each nested interface implementation which is accessible through a getter method. Have a look at the code snipped of the 'unnamed' default interface implementation:
  668. bc..
  669. public class DefaultSMStatemachine implements IDefaultSMStatemachine {
  670. private final class SCInterfaceImpl implements SCInterface {
  671. private boolean evA;
  672. private boolean evAValue;
  673. public void raiseEvA(boolean value) {
  674. evA = true;
  675. evAValue = value;
  676. }
  677. private boolean getEvAValue() {
  678. if (!evA)
  679. throw new IllegalStateException(
  680. "Illegal event value acces. Event EvA is not raised!");
  681. return evAValue;
  682. }
  683. private boolean evB;
  684. private int evBValue;
  685. public boolean isRaisedEvB() {
  686. return evB;
  687. }
  688. private void raiseEvB(int value) {
  689. evB = true;
  690. evBValue = value;
  691. }
  692. public int getEvBValue() {
  693. if (!evB)
  694. throw new IllegalStateException(
  695. "Illegal event value acces. Event EvB is not raised!");
  696. return evBValue;
  697. }
  698. private boolean a;
  699. public boolean getA() {
  700. return a;
  701. }
  702. public void setA(boolean value) {
  703. this.a = value;
  704. }
  705. public void clearEvents() {
  706. evA = false;
  707. }
  708. public void clearOutEvents() {
  709. evB = false;
  710. }
  711. }
  712. private SCInterfaceImpl sCInterface;
  713. public DefaultSMStatemachine() {
  714. sCInterface = new SCInterfaceImpl();
  715. }
  716. public SCInterface getSCInterface() {
  717. return sCInterface;
  718. }
  719. }
  720. p. Now even a few notes on the naming of the generated interfaces and the value access of events. The default (unnamed) interface is named 'SCInterface'. If an interface has a dedicated name then this name is used with the prefix 'SCI' (e.g. 'SCIInterfacename'). Additionally a value of an event can only be accessed if the event is occured during the run to completion step. Otherwise an @IllegalStateException@ is thrown by the interface.
  721. h4. Interface observers
  722. If the general feature 'InterfaceObserverSupport' is enabled in the sgen model the generated interfaces get support to register observers:
  723. bc..
  724. public interface IDefaultSMStatemachine extends IStatemachine {
  725. public interface SCInterface {
  726. public void raiseEvA(boolean value);
  727. public boolean isRaisedEvB();
  728. public int getEvBValue();
  729. public boolean getA();
  730. public void setA(boolean value);
  731. public List<SCInterfaceListener> getListeners();
  732. }
  733. public interface SCInterfaceListener {
  734. public void onEvBRaised(int value);
  735. }
  736. public SCInterface getSCInterface();
  737. }
  738. p. An additional interface @SCInterfaceListener@ is generated. This interface has to be implemented by the user and contains callback methods for each outgoing event. So the listener get notified if a outgoing event is raised by the statemachine internally. To add or remove a listener from an interface use the @getListeners()@ method of the associated interface. This method returns a @java.util.list@ which is parameterized with the appropriate listener type. The operations within the callback should not take a long process time because the statemachine execution may hang too long which leads to a not expected runtime behavior.
  739. h4. Operation callbacks
  740. The yakindu statecharts support the declaration of operations which can be used within a statechart as actions. These operations have to be implemented by the user before a statechart is executable. Here is an example statechart using an operation:
  741. !images/OperationExample.png!
  742. Now have a look at the generated code:
  743. bc..
  744. public interface IDefaultSMStatemachine extends IStatemachine {
  745. public interface SCInterface {
  746. public void raiseEvA(boolean value);
  747. public boolean isRaisedEvB();
  748. public int getEvBValue();
  749. public boolean getA();
  750. public void setA(boolean value);
  751. public void setSCInterfaceOperationCallback(
  752. SCInterfaceOperationCallback operationCallback);
  753. }
  754. public interface SCInterfaceOperationCallback {
  755. public int myOperation(int param1, boolean param2);
  756. }
  757. public SCInterface getSCInterface();
  758. }
  759. p. An additional interface @SCInterfaceOperationCallback@ with the method @myOperation(int param1, boolean param2)@ is generated. This interface has to be implemented by the user and set with the @setSCInterfaceOperationCallback(SCInterfaceOperationCallback operationCallback)@ method so that the statechart can use it:
  760. bc..
  761. public static void main(String[] args) {
  762. DefaultSMStatemachine statemachine = new DefaultSMStatemachine();
  763. SCInterfaceOperationCallback callback = new SCInterfaceOperationCallback() {
  764. @Override
  765. public int myOperation(int param1, boolean param2) {
  766. // Your operation code should be placed here;
  767. return 0;
  768. }
  769. };
  770. statemachine.getSCInterface().setSCInterfaceOperationCallback(callback);
  771. statemachine.init();
  772. statemachine.enter();
  773. statemachine.runCycle();
  774. }
  775. h4. Integration of generated code
  776. To get a clue how to integrate the generated java statemachines into your existing projects have a look at the
  777. @CrossingDemoCycleBased@ class and it's abstract super class @CrossingDemoBase@. The code starts with the main method in @CrossingDemoCycleBased@ class:
  778. bc..
  779. public static void main(String[] args) {
  780. new CrossingDemoCycleBased().runTrafficLight();
  781. }
  782. p. A new instance of the class is created and the method @runTrafficLight()@ is directly called. This method consist in the super class:
  783. bc..
  784. public void runTrafficLight() {
  785. setUpAndRunStatemachine();
  786. createUIContent();
  787. shell.open();
  788. while (!shell.isDisposed()) {
  789. // update traffic lights
  790. readStatemachineOutput();
  791. crossing.repaint();
  792. if (!display.readAndDispatch()) {
  793. display.sleep();
  794. }
  795. }
  796. tearDownStatemachine();
  797. }
  798. p. This method setups the statemachine and creates the UI content. In a while loop the content of the statemachine is read and the ui is repainted. If the ui shell is closed the loop is left and the statemachine is teared down. The really interresting methods are @setUpAndRunStatemachine()@, @readStatemachinOutput@ and @tearDownStatemachine()@:
  799. bc..
  800. protected void setUpAndRunStatemachine() {
  801. statemachine = new TrafficLightWaitingStatemachine();
  802. statemachine.setTimerService(new TimerService());
  803. statemachine.init();
  804. statemachine.enter();
  805. RuntimeService.getInstance().registerStatemachine(statemachine, 100);
  806. }
  807. p. First a new instance of the generated statemachine is created. Because the traffic light statechart uses timing clauses the default implementation of the @TimerService@ is set. In the next steps the statemachine is initialized and entered. After the enter method ist executed the machine stays in a defined state. Finally the statemachine is passed to the runtime service. This service executes the @runCycle()@ method of the statemachine every 100 ms. So the statemachine executes a run to completion step every 100 ms.
  808. bc..
  809. protected void readStatemachineOutput() {
  810. trafficLightFigure.setRed(statemachine.getSCITrafficLight()
  811. .getRed());
  812. trafficLightFigure.setYellow(statemachine.getSCITrafficLight()
  813. .getYellow());
  814. trafficLightFigure.setGreen(statemachine.getSCITrafficLight()
  815. .getGreen());
  816. pedestrianLightFigure.setWhite(statemachine.getSCIPedestrian()
  817. .getRequest());
  818. pedestrianLightFigure.setRed(statemachine.getSCIPedestrian()
  819. .getRed());
  820. pedestrianLightFigure.setGreen(statemachine.getSCIPedestrian()
  821. .getGreen());
  822. }
  823. p. The generated code contains getters and setters for each variable and event. So it's easy to read values from and write values to a statemachine or raise events and ask the statemachine if outgoing events were raised during the last run to completion step. Within @readStatemachineOutput()@ method these methods are used to read the light values from the statemachine and set them to the ui elements. Within the methods @pedestrianRequestButtonClicked()@ and @onOffButtonClicked()@ some events are raised.
  824. Hint:
  825. If outgoing events are raised within the statemachine they remain active until the next run to completion step is started.
  826. bc..
  827. @Override
  828. protected void tearDownStatemachine() {
  829. // End TimerHandler and RuntimeService.
  830. statemachine.getTimerService().cancel();
  831. RuntimeService.getInstance().cancelTimer();
  832. }
  833. p. If the UI thread has been terminated by the user, the state machine will be shut down. It is necessary to end the timer service. Finally the runtime service is cancelled.
  834. h3. Specifications of C code
  835. For C you can checkout the project 'org.yakindu.examples.c.trafficlight' from the Yakindu google code repository ( "Google code link":http://svn.codespot.com/a/eclipselabs.org/yakindu/SCT2/trunk/examples ). The C example contains the statechart, sgen model, graphical widgets and some glue code to connect the generated code with the widgets. The graphical widgets are based on Qt. To execute the c example you can run the file org_yakindu_sct_examples_c_trafficlight as 'Local C/C++ application' from the eclipse 'Run As' context menu.
  836. h4. Generated header files
  837. The C code generator generates three header files. The first one is 'sc_types.h':
  838. bc..
  839. #ifndef SC_TYPES_H_
  840. #define SC_TYPES_H_
  841. #ifdef __cplusplus
  842. extern "C" {
  843. #endif
  844. #include <stdint.h>
  845. #include <stdbool.h>
  846. typedef int_fast16_t sc_short;
  847. typedef uint_fast16_t sc_ushort;
  848. typedef int32_t sc_integer;
  849. typedef uint32_t sc_uinteger;
  850. typedef double sc_real;
  851. typedef char* sc_string;
  852. typedef void* sc_eventid;
  853. #ifdef __cplusplus
  854. }
  855. #endif
  856. #define sc_boolean bool
  857. #define bool_true true
  858. #define bool_false false
  859. #endif /* SC_TYPES_H_ */
  860. p. It contains some basic definitions for C++ compiler compatibility and typedefs to map the Yakindu statechart types to C types. The next header file is named like the statechart. For the traffic light example it is called 'TrafficLightWaiting.h':
  861. bc..
  862. #ifndef TRAFFICLIGHTWAITING_H_
  863. #define TRAFFICLIGHTWAITING_H_
  864. #include "sc_types.h"
  865. #ifdef __cplusplus
  866. extern "C" {
  867. #endif
  868. /*! \file Header of the state machine 'TrafficLightWaiting'.
  869. */
  870. //! enumeration of all states
  871. typedef enum {
  872. TrafficLightWaiting_main_region_on ,
  873. TrafficLightWaiting_main_region_on_r1_StreetGreen ,
  874. TrafficLightWaiting_main_region_on_r1_PedWaiting ,
  875. TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOn ,
  876. TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOff ,
  877. TrafficLightWaiting_main_region_on_r1_StreetAttention ,
  878. TrafficLightWaiting_main_region_on_r1_StreetRed ,
  879. TrafficLightWaiting_main_region_on_r1_PedestrianGreen ,
  880. TrafficLightWaiting_main_region_on_r1_PedestrianRed ,
  881. TrafficLightWaiting_main_region_on_r1_StreetPrepared ,
  882. TrafficLightWaiting_main_region_off ,
  883. TrafficLightWaiting_main_region_off_r1_YellowOn ,
  884. TrafficLightWaiting_main_region_off_r1_YellowOff ,
  885. TrafficLightWaiting_last_state
  886. } TrafficLightWaitingStates;
  887. //! Type definition of the data structure for the TrafficLightWaitingIfaceTrafficLight interface scope.
  888. typedef struct {
  889. sc_boolean red;
  890. sc_boolean yellow;
  891. sc_boolean green;
  892. } TrafficLightWaitingIfaceTrafficLight;
  893. //! Type definition of the data structure for the TrafficLightWaitingIfacePedestrian interface scope.
  894. typedef struct {
  895. sc_boolean request;
  896. sc_boolean red;
  897. sc_boolean green;
  898. } TrafficLightWaitingIfacePedestrian;
  899. //! Type definition of the data structure for the TrafficLightWaitingIface interface scope.
  900. typedef struct {
  901. sc_boolean pedestrianRequest_raised;
  902. sc_boolean onOff_raised;
  903. } TrafficLightWaitingIface;
  904. //! Type definition of the data structure for the TrafficLightWaitingTimeEvents interface scope.
  905. typedef struct {
  906. sc_boolean TrafficLightWaiting_main_region_on_r1_PedWaiting_time_event_0_raised;
  907. sc_boolean TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOn_time_event_0_raised;
  908. sc_boolean TrafficLightWaiting_main_region_on_r1_PedWaiting_r1_waitOff_time_event_0_raised;
  909. sc_boolean TrafficLightWaiting_main_region_on_r1_StreetAttention_time_event_0_raised;
  910. sc_boolean TrafficLightWaiting_main_region_on_r1_StreetRed_time_event_0_raised;
  911. sc_boolean TrafficLightWaiting_main_region_on_r1_PedestrianGreen_time_event_0_raised;
  912. sc_boolean TrafficLightWaiting_main_region_on_r1_PedestrianRed_time_event_0_raised;
  913. sc_boolean TrafficLightWaiting_main_region_on_r1_StreetPrepared_time_event_0_raised;
  914. sc_boolean TrafficLightWaiting_main_region_off_r1_YellowOn_time_event_0_raised;
  915. sc_boolean TrafficLightWaiting_main_region_off_r1_YellowOff_time_event_0_raised;
  916. } TrafficLightWaitingTimeEvents;
  917. //! the maximum number of orthogonal states defines the dimension of the state configuration vector.
  918. #define TRAFFICLIGHTWAITING_MAX_ORTHOGONAL_STATES 1
  919. /*! Type definition of the data structure for the TrafficLightWaiting state machine.
  920. This data structure has to be allocated by the client code. */
  921. typedef struct {
  922. TrafficLightWaitingStates stateConfVector[TRAFFICLIGHTWAITING_MAX_ORTHOGONAL_STATES];
  923. sc_ushort stateConfVectorPosition;
  924. TrafficLightWaitingIfaceTrafficLight ifaceTrafficLight;
  925. TrafficLightWaitingIfacePedestrian ifacePedestrian;
  926. TrafficLightWaitingIface iface;
  927. TrafficLightWaitingTimeEvents timeEvents;
  928. } TrafficLightWaiting;
  929. /*! Initializes the TrafficLightWaiting state machine data structures. Must be called before first usage.*/
  930. extern void trafficLightWaiting_init(TrafficLightWaiting* handle);
  931. /*! Activates the state machine */
  932. extern void trafficLightWaiting_enter(TrafficLightWaiting* handle);
  933. /*! Deactivates the state machine */
  934. extern void trafficLightWaiting_exit(TrafficLightWaiting* handle);
  935. /*! Performs a 'run to completion' step. */
  936. extern void trafficLightWaiting_runCycle(TrafficLightWaiting* handle);
  937. /*! Raises a time event. */
  938. extern void trafficLightWaiting_raiseTimeEvent(TrafficLightWaiting* handle, sc_eventid evid);
  939. /*! Gets the value of the variable 'red' that is defined in the interface scope 'TrafficLight'. */
  940. extern sc_boolean trafficLightWaitingIfaceTrafficLight_get_red(TrafficLightWaiting* handle);
  941. /*! Sets the value of the variable 'red' that is defined in the interface scope 'TrafficLight'. */
  942. extern void trafficLightWaitingIfaceTrafficLight_set_red(TrafficLightWaiting* handle, sc_boolean value);
  943. /*! Gets the value of the variable 'yellow' that is defined in the interface scope 'TrafficLight'. */
  944. extern sc_boolean trafficLightWaitingIfaceTrafficLight_get_yellow(TrafficLightWaiting* handle);
  945. /*! Sets the value of the variable 'yellow' that is defined in the interface scope 'TrafficLight'. */
  946. extern void trafficLightWaitingIfaceTrafficLight_set_yellow(TrafficLightWaiting* handle, sc_boolean value);
  947. /*! Gets the value of the variable 'green' that is defined in the interface scope 'TrafficLight'. */
  948. extern sc_boolean trafficLightWaitingIfaceTrafficLight_get_green(TrafficLightWaiting* handle);
  949. /*! Sets the value of the variable 'green' that is defined in the interface scope 'TrafficLight'. */
  950. extern void trafficLightWaitingIfaceTrafficLight_set_green(TrafficLightWaiting* handle, sc_boolean value);
  951. /*! Gets the value of the variable 'request' that is defined in the interface scope 'Pedestrian'. */
  952. extern sc_boolean trafficLightWaitingIfacePedestrian_get_request(TrafficLightWaiting* handle);
  953. /*! Sets the value of the variable 'request' that is defined in the interface scope 'Pedestrian'. */
  954. extern void trafficLightWaitingIfacePedestrian_set_request(TrafficLightWaiting* handle, sc_boolean value);
  955. /*! Gets the value of the variable 'red' that is defined in the interface scope 'Pedestrian'. */
  956. extern sc_boolean trafficLightWaitingIfacePedestrian_get_red(TrafficLightWaiting* handle);
  957. /*! Sets the value of the variable 'red' that is defined in the interface scope 'Pedestrian'. */
  958. extern void trafficLightWaitingIfacePedestrian_set_red(TrafficLightWaiting* handle, sc_boolean value);
  959. /*! Gets the value of the variable 'green' that is defined in the interface scope 'Pedestrian'. */
  960. extern sc_boolean trafficLightWaitingIfacePedestrian_get_green(TrafficLightWaiting* handle);
  961. /*! Sets the value of the variable 'green' that is defined in the interface scope 'Pedestrian'. */
  962. extern void trafficLightWaitingIfacePedestrian_set_green(TrafficLightWaiting* handle, sc_boolean value);
  963. /*! Raises the in event 'pedestrianRequest' that is defined in the default interface scope. */
  964. extern void trafficLightWaitingIface_raise_pedestrianRequest(TrafficLightWaiting* handle);
  965. /*! Raises the in event 'onOff' that is defined in the default interface scope. */
  966. extern void trafficLightWaitingIface_raise_onOff(TrafficLightWaiting* handle);
  967. /*! Checks if the specified state is active. */
  968. extern sc_boolean trafficLightWaiting_isActive(TrafficLightWaiting* handle, TrafficLightWaitingStates state);
  969. #ifdef __cplusplus
  970. }
  971. #endif
  972. #endif /* TRAFFICLIGHTWAITING_H_ */
  973. p. Within this header file an enum that contains the state names is defined as well as the data structures for each interface a statechart has. Aditionally a structure for the time events the statechart uses is defined. The interface and time events data structures are nested in the parent structure @TrafficLightWaiting@. The client has to allocate this structure. In general it is a parameter of the most methods the statechart defines. In the following it is called statechart data structure.
  974. h5. Base statechart methods
  975. The most basic methods the statechart defines are methods to init, enter, exit and to start a run to completion step. In the header file they got the statechart name as prefix and expect the parent data structure as parameter. For example the init method of the traffic light example is called @extern void trafficLightWaiting_init(TrafficLightWaiting* handle)@.
  976. The init method is used to initialize the statechart data structure. Variables are initialized to a default value. If you have initialized variables in the statechart definition these initializations are done in the init method too. The enter method should be called if the statemachine is entered. It sets the statemachine into a defined state. The exit method is used to leave a statemachine statefully. If for example a history state is used in one of the top regions the last active state is stored and the statemachine is leaved via exit and reentered via enter it continues working with this state. The run cycle method is used to trigger a run to completion step in which the statemachine evaluates arising events and computes possible state changes. A run to completion step consists in a simplified view of the following steps:
  977. * Clear list of outgoing events.
  978. * Check whether events have occurred which lead to a state change
  979. * If a state change has to be done:
  980. ** Execute exit actions of leaving state.
  981. ** Save history state if necessary.
  982. ** Set the new State active.
  983. ** Execute entry action of the new state.
  984. * Clear list of incoming events.
  985. h5. Variable and event access
  986. The getters and setters for each variable and event are contained in the header file too. The method names uses the pattern <statechart name>Iface<Interface name>_<set, get or raise>_<variable / event name>. For example the getter for the variable 'red' of the 'pedestrian' interface is named @trafficLightWaitingIfacePedestrian_get_red(TrafficLightWaiting* handle)@.
  987. h4. Optional header file
  988. If the statechart uses timing or external operations an additional header file with the name pattern <statechart name>Required.h is generated. This header file defines method hooks the client code has to implement externally.
  989. h5. Timing service support
  990. p. Because the traffic light example uses timing it contains such a header file:
  991. bc..
  992. extern "C" {
  993. #endif
  994. /*! \file This header defines prototypes for all functions that are required by the state machine implementation.
  995. This is a state machine uses time events which require access to a timing service. Thus the function prototypes:
  996. - trafficLightWaiting_setTimer and
  997. - trafficLightWaiting_unsetTimer
  998. are defined.
  999. These functions will be called during a 'run to completion step' (runCycle) of the statechart.
  1000. There are some constraints that have to be considered for the implementation of these functions:
  1001. - never call the statechart API functions from within these functions.
  1002. - make sure that the execution time is as short as possible.
  1003. */
  1004. //
  1005. // This is a timed state machine that requires timer services
  1006. //
  1007. //! This function has to set up timers for the time events that are required by the state machine.
  1008. /*!
  1009. This function will be called for each time event that is relevant for a state when a state will be entered.
  1010. \param evid An unique identifier of the event.
  1011. \time_ms The time in milli seconds
  1012. \periodic Indicates the the time event must be raised periodically until the timer is unset
  1013. */
  1014. extern void trafficLightWaiting_setTimer(const sc_eventid evid, const sc_integer time_ms, const sc_boolean periodic);
  1015. //! This function has to unset timers for the time events that are required by the state machine.
  1016. /*!
  1017. This function will be called for each time event taht is relevant for a state when a state will be left.
  1018. \param evid An unique identifier of the event.
  1019. */
  1020. extern void trafficLightWaiting_unsetTimer(const sc_eventid evid);
  1021. #ifdef __cplusplus
  1022. }
  1023. #endif
  1024. #endif /* TRAFFICLIGHTWAITINGREQUIRED_H_ */
  1025. p. Basically the correct handling of time has to be implemented by the developer because timer functions generally depend on the hardware target used. So for every hardware target a method to set a timer and a method to reset it has to be implemented externally and linked to the generated code. In case of our trafficlight example the method @trafficLightWaiting_setTimer(const sc_eventid evid, const sc_integer time_ms, const sc_boolean periodic)@ is called by the statemachine to notify the timer service that it has to start a timer for the given time event identifier and raise it after the time given by the same named parameter is expired. It is important that within the 'setTimer' method only a timer thread or a hardware timer interrupt is started and no long time taking operations like sleeping threads or waiting are done. Never call the statechart API functions from within these functions. Otherwise the statemachine execution may hang within the timer service or it shows a not expected runtime behavior. The parameter 'periodic' is set to true if the time event should be raised periodically by the timer service.
  1026. The method @trafficLightWaiting_unsetTimer(const sc_eventid evid)@ is called by the statemachine to notify the timer service to reset the timer for the given event identifier.
  1027. To notify the statemachine of the occurence of a time event the header of the statemachine defines a 'raiseTimeEvent' method. In case of the traffic light example it's named @trafficLightWaiting_raiseTimeEvent(TrafficLightWaiting* handle, sc_eventid evid)@ (in TrafficLightWaiting.h).
  1028. h5. Operation callbacks
  1029. The yakindu statecharts support the declaration of operations which can be used within a statechart as actions. These operations have to be implemented by the user before a statechart is executable. Here is an example statechart using an operation:
  1030. !images/OperationExample.png!
  1031. Now have a look at the generated code:
  1032. bc..
  1033. #ifndef DEFAULTREQUIRED_H_
  1034. #define DEFAULTREQUIRED_H_
  1035. #include "sc_types.h"
  1036. #ifdef __cplusplus
  1037. extern "C" {
  1038. #endif
  1039. /*! \file This header defines prototypes for all functions that are required by the state machine implementation.
  1040. This state machine makes use of operations declared in the state machines interface or internal scopes. Thus the function prototypes:
  1041. - defaultIface_myOperation
  1042. are defined.
  1043. These functions will be called during a 'run to completion step' (runCycle) of the statechart.
  1044. There are some constraints that have to be considered for the implementation of these functions:
  1045. - never call the statechart API functions from within these functions.
  1046. - make sure that the execution time is as short as possible.
  1047. */
  1048. extern sc_integer defaultIface_myOperation(const sc_integer param1, const sc_boolean param2);
  1049. #ifdef __cplusplus
  1050. }
  1051. #endif
  1052. #endif /* DEFAULTREQUIRED_H_ */
  1053. p. An additional method @sc_integer defaultIface_myOperation(const sc_integer param1, const sc_boolean param2)@ is generated. This method has to be implemented by the user and linked with the generated code so that the statechart can use it.
  1054. h4. Integration of generated code
  1055. To get a clue how to integrate the generated c statemachines into your existing projects have a look at the
  1056. @main.cpp@ file. The code starts with the main method:
  1057. bc..
  1058. #include "org_yakindu_sct_examples_c_trafficlight.h"
  1059. #include <QtGui>
  1060. #include <QApplication>
  1061. #include "src-gen/sc_types.h"
  1062. #include "src-gen/TrafficLightWaiting.h"
  1063. #include "statemachine/TrafficLightTimer.h"
  1064. #include "statemachine/TrafficLightRunner.h"
  1065. TrafficLightTimer *timer;
  1066. int main(int argc, char *argv[]) {
  1067. TrafficLightWaiting handle;
  1068. trafficLightWaiting_init(&handle);
  1069. timer = new TrafficLightTimer(&handle);
  1070. trafficLightWaiting_enter(&handle);
  1071. QApplication a(argc, argv);
  1072. TrafficLightRunner *runner = new TrafficLightRunner(&handle, 100);
  1073. org_yakindu_sct_examples_c_trafficlight w(0, runner);
  1074. w.show();
  1075. int ret = a.exec();
  1076. return ret;
  1077. }
  1078. void trafficLightWaiting_setTimer(const sc_eventid evid,
  1079. const sc_integer time_ms, const sc_boolean periodic) {
  1080. timer->setTimer(evid, time_ms, periodic);
  1081. }
  1082. void trafficLightWaiting_unsetTimer(const sc_eventid evid) {
  1083. timer->unsetTimer(evid);
  1084. }
  1085. p. First an instance of the main statemchine data structure is created and intialized with the @trafficLightWaiting_init(&handle)@ method. In the next step the Timer is instantiated. The class @TrafficLightTimer@ represents an implementation of a timer service and uses the timer fuctionality of the Qt framework. The @TrafficLightRunner@ solves as a run time service which executes every 100 ms a run to completion step of the statemachine. Within the class @org_yakindu_sct_examples_c_trafficlight@ the runner class and the gui are wired:
  1086. bc..
  1087. #include "org_yakindu_sct_examples_c_trafficlight.h"
  1088. org_yakindu_sct_examples_c_trafficlight::org_yakindu_sct_examples_c_trafficlight(
  1089. QWidget *parent, TrafficLightRunner *runner) :
  1090. QMainWindow(parent) {
  1091. ui.setupUi(this);
  1092. crossing = new CrossingWidget(this);
  1093. trafficLight = new TrafficLightWidget(crossing);
  1094. trafficLight->setGeometry(275, 75, 30, 90);
  1095. pedestrianLight = new PedestrianLightWidget(crossing);
  1096. pedestrianLight->setGeometry(50, 10, 70, 20);
  1097. connect(runner, SIGNAL(cycleDone(TrafficLightWaiting*)), this, SLOT(update(TrafficLightWaiting*)));
  1098. pedestrianReq = new QPushButton("pedestrian request", this);
  1099. pedestrianReq->setGeometry(1, 365, 150, 30);
  1100. connect(pedestrianReq, SIGNAL(released()), runner, SLOT(raisePedestrianRequest()));
  1101. off = new QPushButton("off / on", this);
  1102. off->setGeometry(249, 365, 150, 30);
  1103. connect(off, SIGNAL(released()), runner, SLOT(raiseOnOff()));
  1104. }
  1105. void org_yakindu_sct_examples_c_trafficlight::update(
  1106. TrafficLightWaiting *handle) {
  1107. trafficLight->setSignals(handle->ifaceTrafficLight.red,
  1108. handle->ifaceTrafficLight.yellow, handle->ifaceTrafficLight.green);
  1109. pedestrianLight->setSignals(handle->ifacePedestrian.request,
  1110. handle->ifacePedestrian.red, handle->ifacePedestrian.green);
  1111. QMainWindow::update();
  1112. }
  1113. org_yakindu_sct_examples_c_trafficlight::~org_yakindu_sct_examples_c_trafficlight() {
  1114. }