aboutsummaryrefslogtreecommitdiffstats
blob: 190133bf559d9d3fd899724920c7a9fdef268001 (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
/*******************************************************************************
 * Copyright (c) 2011 protos software gmbh (http://www.protos.de).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * CONTRIBUTORS:
 * 		Henrik Rentz-Reichert (initial contribution)
 * 		Thomas Schuetz (changed for C code generator)
 * 
 *******************************************************************************/

package org.eclipse.etrice.generator.c.gen

import java.util.HashMap
import java.util.ArrayList
import com.google.inject.Inject
import com.google.inject.Singleton
import org.eclipse.etrice.core.room.SubSystemClass
import org.eclipse.etrice.core.room.CommunicationType
import static extension org.eclipse.etrice.core.room.util.RoomHelpers.*

import org.eclipse.etrice.generator.base.ILogger
import org.eclipse.etrice.generator.etricegen.Root
import org.eclipse.etrice.generator.etricegen.ActorInstance
import org.eclipse.etrice.generator.etricegen.PortInstance
import org.eclipse.etrice.generator.etricegen.InterfaceItemInstance
import org.eclipse.etrice.generator.etricegen.SubSystemInstance
import org.eclipse.xtext.generator.JavaIoFileSystemAccess
import org.eclipse.etrice.generator.generic.RoomExtensions
import org.eclipse.etrice.generator.generic.ProcedureHelpers
import org.eclipse.etrice.core.room.ActorCommunicationType

import static extension org.eclipse.etrice.generator.base.Indexed.*


@Singleton
class SubSystemClassGen {
	
	@Inject extension JavaIoFileSystemAccess fileAccess
	@Inject extension CExtensions stdExt
	@Inject extension RoomExtensions roomExt
	@Inject extension ProcedureHelpers helpers
	@Inject ILogger logger
	
	def doGenerate(Root root) {
		for (ssi: root.subSystemInstances) {
			var path = ssi.subSystemClass.generationTargetPath+ssi.subSystemClass.getPath
			var file = ssi.subSystemClass.getCHeaderFileName
			logger.logInfo("generating SubSystemClass declaration: '"+file+"' in '"+path+"'")
			fileAccess.setOutputPath(path)
			fileAccess.generateFile(file, root.generateHeaderFile(ssi, ssi.subSystemClass))
			
			file = ssi.subSystemClass.getCSourceFileName
			logger.logInfo("generating SubSystemClass implementation: '"+file+"' in '"+path+"'")
			fileAccess.setOutputPath(path)
			fileAccess.generateFile(file, root.generateSourceFile(ssi, ssi.subSystemClass))
			
			file = ssi.subSystemClass.getInstSourceFileName
			logger.logInfo("generating SubSystemClass instance file: '"+file+"' in '"+path+"'")
			fileAccess.setOutputPath(path)
			fileAccess.generateFile(file, root.generateInstanceFile(ssi, ssi.subSystemClass))

			file = ssi.subSystemClass.getDispSourceFileName
			logger.logInfo("generating SubSystemClass dispatcher file: '"+file+"' in '"+path+"'")
			fileAccess.setOutputPath(path)
			fileAccess.generateFile(file, root.generateDispatcherFile(ssi, ssi.subSystemClass))
		}
	}

	def private generateHeaderFile(Root root, SubSystemInstance ssi, SubSystemClass ssc) {'''
		/**
		 * @author generated by eTrice
		 *
		 * Header File of SubSystemClass «ssc.name»
		 * 
		 */
		
		«generateIncludeGuardBegin(ssc.name)»

		«helpers.userCode(ssc.userCode1)»
		
		
		/* lifecycle functions
		 * init -> start -> run (loop) -> stop -> destroy
		 */
		
		void «ssc.name»_init(void);		/* lifecycle init  	 */
		void «ssc.name»_start(void);	/* lifecycle start 	 */
		
		void «ssc.name»_run(void);		/* lifecycle run 	 */
		
		void «ssc.name»_stop(void); 	/* lifecycle stop	 */
		void «ssc.name»_destroy(void); 	/* lifecycle destroy */
		
		void «ssc.name»_shutdown(void);  /* shutdown the dispatcher loop */
		
		«helpers.userCode(ssc.userCode2)»
		
		«generateIncludeGuardEnd(ssc.name)»
		
		
	'''
	}
	
	def private generateSourceFile(Root root, SubSystemInstance ssi, SubSystemClass ssc) {'''
		/**
		 * @author generated by eTrice
		 *
		 * Source File of SubSystemClass «ssc.name»
		 * 
		 */
		
		#include "«ssc.getCHeaderFileName»"

		/* include instances for all classes */
		#include "«ssc.getInstSourceFileName»"
		#include "«ssc.getDispSourceFileName»"

		#include "debugging/etLogger.h"
		#include "debugging/etMSCLogger.h"
		
		#include "platform/etTimer.h"
		#include "etGlobalFlags.h"

		«helpers.userCode(ssc.userCode3)»
		
		/* data for SubSysten «ssc.name» */
		typedef struct «ssc.name» {
			char *name;
			volatile int shutdownRequest;
		} «ssc.name»;
		
		static «ssc.name» «ssc.name»Inst = {"«ssc.name»",0};
		
		void «ssc.name»_initActorInstances(void);
		void «ssc.name»_constructActorInstances(void);

		void «ssc.name»_init(void){
			ET_MSC_LOGGER_SYNC_ENTRY("SubSys", "init")
			etLogger_logInfoF("%s_init", «ssc.name»Inst.name);
			
			/* construct all actors */
			«ssc.name»_constructActorInstances();
			
			/* initialization of all message services */
			etMessageService_init(&msgService_Thread1, msgBuffer_Thread1, MESSAGE_POOL_MAX, MESSAGE_BLOCK_SIZE, MsgDispatcher_Thread1_receiveMessage);
			
			/* init all actors */
			«ssc.name»_initActorInstances();
			
			ET_MSC_LOGGER_SYNC_EXIT
		}
		
		void «ssc.name»_start(void){
			ET_MSC_LOGGER_SYNC_ENTRY("SubSys", "start")
			etLogger_logInfoF("%s_start", «ssc.name»Inst.name);
			ET_MSC_LOGGER_SYNC_EXIT
		}
		
		void «ssc.name»_run(void){
			ET_MSC_LOGGER_SYNC_ENTRY("SubSys", "run")
			
			#ifdef ET_RUNTIME_ENDLESS
				while(!(«ssc.name»Inst.shutdownRequest)){
					if (etTimer_executeNeeded()){
						etMessageService_execute(&msgService_Thread1);
						«generateDatadrivenExecutes(root, ssi)»
					}
				}
			#else
				uint32 loopCounter = 0;
				while(!(«ssc.name»Inst.shutdownRequest)){
					if (etTimer_executeNeeded()){
						etMessageService_execute(&msgService_Thread1);
						«generateDatadrivenExecutes(root, ssi)»
						etLogger_logInfo("Execute");
						if (loopCounter++ > ET_RUNTIME_MAXLOOP){
							break;
						}
					}
				}
			#endif
			
			ET_MSC_LOGGER_SYNC_EXIT
		}
		
		void «ssc.name»_stop(void){
			ET_MSC_LOGGER_SYNC_ENTRY("SubSys", "stop")
			etLogger_logInfoF("%s_stop", «ssc.name»Inst.name);
			ET_MSC_LOGGER_SYNC_EXIT
		}
		
		void «ssc.name»_destroy(void){
			ET_MSC_LOGGER_SYNC_ENTRY("SubSys", "destroy")
			etLogger_logInfoF("%s_destroy", «ssc.name»Inst.name);
			«FOR ai : ssi.allContainedInstances.reverseView»
				«IF !ai.actorClass.operations.filter(op|op.destructor).empty»
					«ai.actorClass.name»_dtor(&«ai.path.getPathName()»);
				«ENDIF»
			«ENDFOR»
			ET_MSC_LOGGER_SYNC_EXIT
		}

		void «ssc.name»_shutdown(void){
			ET_MSC_LOGGER_SYNC_ENTRY("SubSys", "shutdown")
			etLogger_logInfoF("%s_shutdown", «ssc.name»Inst.name);
			«ssc.name»Inst.shutdownRequest = 1;
			ET_MSC_LOGGER_SYNC_EXIT
		}


		void «ssc.name»_constructActorInstances(void){
			ET_MSC_LOGGER_SYNC_ENTRY("«ssc.name»", "constructActorInstances")
			«FOR ai : ssi.allContainedInstances»
				«IF !ai.actorClass.operations.filter(op|op.constructor).empty»
					«ai.actorClass.name»_ctor(&«ai.path.getPathName()»);
				«ENDIF»
			«ENDFOR»
			ET_MSC_LOGGER_SYNC_EXIT
		}

		void «ssc.name»_initActorInstances(void){
			ET_MSC_LOGGER_SYNC_ENTRY("«ssc.name»", "initActorInstances")
			«FOR ai : ssi.allContainedInstances»
				«ai.actorClass.name»_init(&«ai.path.getPathName()»);
			«ENDFOR»
			ET_MSC_LOGGER_SYNC_EXIT
		}
		
	'''
	}

	def private generateInstanceFile(Root root, SubSystemInstance ssi, SubSystemClass ssc) {'''
		/**
		 * @author generated by eTrice
		 *
		 * Instance File of SubSystemClass «ssc.name»
		 * - instantiation of all actor instances and port instances
		 * - configuration of data and connection of ports
		 */

		#include "messaging/etMessageService.h"
		#include "platform/etMemory.h"
		
		/* instantiation of message services */
		
		/* MessageService for Thread1 */
		static uint8 msgBuffer_Thread1[MESSAGE_POOL_MAX*MESSAGE_BLOCK_SIZE];
		static etMessageService msgService_Thread1;


		/* include all used ActorClasses */
		«FOR actorClass : root.getUsedActorClasses()»
			#include "«actorClass.name».h"
		«ENDFOR»

		/* include all used ProtcolClasses */
		«FOR protocolClass : root.getUsedProtocolClasses()»
			#include "«protocolClass.name».h"
		«ENDFOR»
		
		
		/* declarations of all ActorClass instances (const and variable structs) */

		/* forward declaration of variable actor structs */
		«FOR ai : ssi.allContainedInstances»
			static «ai.actorClass.name» «ai.path.getPathName()»;
		«ENDFOR»
		
		/* forward declaration of variable port structs */		
		«FOR ai: ssi.allContainedInstances»
			«IF ai.orderedIfItemInstances.empty»
/*nothing to do */
			«ELSE»
				«FOR pi:ai.orderedIfItemInstances»
					«IF pi.interfaceItem.protocol.getPortClass(pi.conjugated)!=null»
						«IF !pi.interfaceItem.protocol.getPortClass(pi.conjugated).attributes.empty»
							«IF pi.replicated»
								static «pi.interfaceItem.protocol.getPortClassName(pi.conjugated)»_var «pi.path.pathName»_var[«pi.peers.size»];
							«ELSE»
								static «pi.interfaceItem.protocol.getPortClassName(pi.conjugated)»_var «pi.path.pathName»_var;
							«ENDIF»
						«ENDIF»
					«ENDIF»		
				«ENDFOR»
			«ENDIF» 
		«ENDFOR»
		
		«FOR ai : ssi.allContainedInstances»
			
			/* instance «ai.path.getPathName()» */
			«IF ai.orderedIfItemInstances.empty»
				/* no ports/saps/services - nothing to initialize statically */
			«ELSE»
				«genActorInstanceInitializer(root, ai)»
			«ENDIF»
		«ENDFOR»
		
	'''
	}

	def private genActorInstanceInitializer(Root root, ActorInstance ai) {
		var instName = ai.path.pathName
		
		// list of replicated ports
		var replPorts = new ArrayList<InterfaceItemInstance>()
		replPorts.addAll(ai.orderedIfItemInstances.filter(e|e.replicated))
		var haveReplSubPorts = replPorts.findFirst(e|!e.peers.empty)!=null
		
		var simplePorts = ai.orderedIfItemInstances.filter(e|e.simple)
		
		// list of event ports, simple first, then replicated
		var eventPorts = new ArrayList<InterfaceItemInstance>()
		eventPorts.addAll(simplePorts.filter(p|p.interfaceItem.protocol.commType==CommunicationType::EVENT_DRIVEN).union(replPorts))

		var dataPorts = simplePorts.filter(p|p.interfaceItem.protocol.commType==CommunicationType::DATA_DRIVEN)
		var recvPorts = dataPorts.filter(p|p instanceof PortInstance && !(p as PortInstance).port.conjugated)
		var sendPorts = dataPorts.filter(p|p instanceof PortInstance && (p as PortInstance).port.conjugated)
		
		// compute replicated port offsets		
		var offsets = new HashMap<InterfaceItemInstance, Integer>()
		var offset = 0
		for (p: replPorts) {
			offsets.put(p, offset)
			offset = offset + p.peers.size
		}
		
		var replSubPortsArray = if (haveReplSubPorts) instName+"_repl_sub_ports" else "NULL"
		
	'''
		«IF haveReplSubPorts»
			static const etReplSubPort «replSubPortsArray»[«offset»] = {
				/* Replicated Sub Ports: {varData, msgService, peerAddress, localId, index} */
				«FOR pi : replPorts SEPARATOR ","»
					«genReplSubPortInitializers(root, ai, pi)»
				«ENDFOR»
			};
		«ENDIF»
		«IF !(eventPorts.empty && recvPorts.empty)»
			static const «ai.actorClass.name»_const «instName»_const = {
				/* Ports: {varData, msgService, peerAddress, localId} */
				«FOR pi : eventPorts SEPARATOR ","»
					«IF pi.simple»
						«genPortInitializer(root, ai, pi)»
					«ELSE»
						{«pi.peers.size», «replSubPortsArray»+«offsets.get(pi)»}
					«ENDIF»
				«ENDFOR»
				«IF !eventPorts.empty && !recvPorts.empty»,«ENDIF»
				
				/* data receive ports */
				«FOR pi : recvPorts SEPARATOR ","»
					«genRecvPortInitializer(root, ai, pi)»
				«ENDFOR»
			};
			static «ai.actorClass.name» «instName» = {&«instName»_const};
		«ENDIF»
	'''}
		
	def private String genPortInitializer(Root root, ActorInstance ai, InterfaceItemInstance pi) {
		var recvMsg = if (pi.peers.empty) "NULL" else ai.actorClass.name+"_receiveMessage"
		var objId = if (pi.peers.empty) 0 else pi.peers.get(0).objId
		var idx = if (pi.peers.empty) 0 else pi.peers.get(0).peers.indexOf(pi)
		
		"{"+getInterfaceItemInstanceData(pi)+"," 
		+"&msgService_Thread1, "
		+(objId+idx)+", "
		+(root.getExpandedActorClass(ai).getInterfaceItemLocalId(pi.interfaceItem)+1)
		+"} /* Port "+pi.name+" */"
	}
	
	def private getInterfaceItemInstanceData(InterfaceItemInstance pi){
		if (pi.interfaceItem.protocol.getPortClass(pi.conjugated)== null) return "0"
		if (pi.interfaceItem.protocol.getPortClass(pi.conjugated).attributes.empty){
			return "0"
		}else{
			return "&"+pi.path.pathName+"_var"
		}
	}
	
	
	def private String genRecvPortInitializer(Root root, ActorInstance ai, InterfaceItemInstance pi) {
		if (pi.peers.empty)
			return "{NULL}"

		var peer = pi.peers.get(0)
		var peerInst = pi.peers.get(0).eContainer() as ActorInstance
		var instName = peerInst.path.pathName
			
		"{&"+instName+"."+peer.name+"}"
	}
	
	def private String genReplSubPortInitializers(Root root, ActorInstance ai, InterfaceItemInstance pi) {
		var result = ""
		
		for (p: pi.peers) {
			var idx = pi.peers.indexOf(p)
			var comma = if (idx<pi.peers.size-1) "," else ""
			var iiiD = getInterfaceItemInstanceData(pi)
			iiiD = if (iiiD.equals("0")) iiiD+"," else iiiD+"["+idx+"],"
			result = result +
				"{"+iiiD 
				+"&msgService_Thread1, "
				+p.objId+", "
				+(root.getExpandedActorClass(ai).getInterfaceItemLocalId(pi.interfaceItem)+1)+", "
				+idx
				+"}"+comma+" /* Repl Sub Port "+pi.name+" idx +"+idx+"*/\n"
		}
		
		return result
	}
	
	def private generateDispatcherFile(Root root, SubSystemInstance ssi, SubSystemClass ssc) {'''
		/**
		 * @author generated by eTrice
		 *
		 * Dispatcher File of SubSystemClass «ssc.name»
		 * - one generated dispatcher for each MessageService (Thread)
		 */

		#include "messaging/etMessageReceiver.h"
		#include "debugging/etLogger.h"
		#include "debugging/etMSCLogger.h"
		
		static void MsgDispatcher_Thread1_receiveMessage(const etMessage* msg){
			ET_MSC_LOGGER_SYNC_ENTRY("MsgDispatcher_Thread1", "receiveMessage")
			switch(msg->address){
			
				«FOR ai : ssi.allContainedInstances»
					/* interface items of «ai.path» */
					«FOR pi : ai. orderedIfItemInstances.filter(p|p.interfaceItem.protocol.commType==CommunicationType::EVENT_DRIVEN)»
						«IF pi.replicated»
							«FOR peer: pi.peers»
								case «pi.objId+pi.peers.indexOf(peer)»:
								«IF (pi.interfaceItem.protocol.handlesReceive(pi.isConjugated()))»
									switch (msg->evtID){
										«FOR h:getReceiveHandlers(pi.interfaceItem.protocol,pi.isConjugated())»
											case «pi.interfaceItem.protocol.name»_«h.msg.codeName»:
												«pi.interfaceItem.protocol.getPortClassName(pi.isConjugated)»_«h.msg.name»_receiveHandler((etPort *)&«ai.path.pathName»_const.«pi.name».ports[«pi.peers.indexOf(peer)»],msg,(void*)&«ai.path.pathName»,«ai.actorClass.name»_receiveMessage);
											break;
										«ENDFOR»
										default: «ai.actorClass.name»_receiveMessage((void*)&«ai.path.pathName»,(etPort*)&«ai.path.pathName»_const.«pi.name».ports[«pi.peers.indexOf(peer)»], msg);
										break;
										}										
								«ELSE»
									«ai.actorClass.name»_receiveMessage((void*)&«ai.path.pathName»,(etPort*)&«ai.path.pathName»_const.«pi.name».ports[«pi.peers.indexOf(peer)»], msg);
								«ENDIF»
								break;
							«ENDFOR»
						«ELSE»
							case «pi.objId»:
							«IF (pi.interfaceItem.protocol.handlesReceive(pi.isConjugated()))» 
								switch (msg->evtID){
								«FOR h:getReceiveHandlers(pi.interfaceItem.protocol,pi.isConjugated())»
									case «pi.interfaceItem.protocol.name»_«h.msg.codeName»:
										«pi.interfaceItem.protocol.getPortClassName(pi.isConjugated)»_«h.msg.name»_receiveHandler((etPort *)&«ai.path.pathName»_const.«pi.name»,msg,(void*)&«ai.path.pathName»,«ai.actorClass.name»_receiveMessage);
									break;
								«ENDFOR»
								default: «ai.actorClass.name»_receiveMessage((void*)&«ai.path.pathName»,(etPort*)&«ai.path.pathName»_const.«pi.name», msg);
								break;
								}
							«ELSE»
								«ai.actorClass.name»_receiveMessage((void*)&«ai.path.pathName»,(etPort*)&«ai.path.pathName»_const.«pi.name», msg);
							«ENDIF»
							break;
						«ENDIF»
					«ENDFOR»
				«ENDFOR»

				default:
					etLogger_logErrorF("MessageService_Thread1_receiveMessage: address %d does not exist ", msg->address);
				break;
			}
			ET_MSC_LOGGER_SYNC_EXIT
		}
		'''
	}
	
	def private generateDatadrivenExecutes(Root root, SubSystemInstance ssi) {'''
		«FOR ai : ssi.allContainedInstances»
			«IF ai.actorClass.commType == ActorCommunicationType::ASYNCHRONOUS || ai.actorClass.commType == ActorCommunicationType::DATA_DRIVEN»
				«ai.actorClass.name»_execute(&«ai.path.getPathName()»);
			«ENDIF»
		«ENDFOR»
	'''
	}
	
}