-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathComponentCppWriter.scala
More file actions
1099 lines (1034 loc) · 36.4 KB
/
ComponentCppWriter.scala
File metadata and controls
1099 lines (1034 loc) · 36.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fpp.compiler.codegen
import fpp.compiler.analysis._
import fpp.compiler.ast._
import fpp.compiler.codegen._
import fpp.compiler.util._
/** Writes out C++ for component definitions */
case class ComponentCppWriter (
s: CppWriterState,
aNode: Ast.Annotated[AstNode[Ast.DefComponent]]
) extends ComponentCppWriterUtils(s, aNode) {
private val fileName = ComputeCppFiles.FileNames.getComponent(componentName)
private val dpWriter = ComponentDataProducts(s, aNode)
private val portWriter = ComponentPorts(s, aNode)
private val cmdWriter = ComponentCommands(s, aNode)
private val internalPortWriter = ComponentInternalPort(s, aNode)
private val eventWriter = ComponentEvents(s, aNode)
private val tlmWriter = ComponentTelemetry(s, aNode)
private val paramWriter = ComponentParameters(s, aNode)
private val externalStateMachineWriter = ComponentExternalStateMachines(s, aNode)
private val stateMachineWriter = ComponentStateMachines(s, aNode)
private val kindStr = componentData.kind match {
case Ast.ComponentKind.Active => "Active"
case Ast.ComponentKind.Passive => "Passive"
case Ast.ComponentKind.Queued => "Queued"
}
private val baseClassName = s"${kindStr}ComponentBase"
private val exitConstantName = s"${componentName.toUpperCase}_COMPONENT_EXIT"
private def writeIncludeDirectives: List[String] = {
val Right(a) = UsedSymbols.defComponentAnnotatedNode(s.a, aNode)
s.writeIncludeDirectives(a.usedSymbolSet)
}
def write: CppDoc = {
val includeGuard = s.includeGuardFromQualifiedName(componentSymbol, fileName)
CppWriter.createCppDoc(
s"$componentName component base class",
fileName,
includeGuard,
getMembers,
s.toolName
)
}
private def getMembers: List[CppDoc.Member] = {
val hppIncludes = getHppIncludes
val cppIncludes = getCppIncludes
val externalSmInterfaces = externalStateMachineWriter.getSmInterfaces
val cls = classMember(
Some(
addSeparatedString(
s"\\class $componentClassName\n\\brief Auto-generated base for $componentName component",
AnnotationCppWriter.asStringOpt(aNode)
)
),
componentClassName,
Some(s"public Fw::$baseClassName$externalSmInterfaces"),
getClassMembers
)
List(
List(hppIncludes, cppIncludes),
getStaticAssertion,
wrapInNamespaces(componentNamespaceIdentList, List(cls))
).flatten
}
private def getHppIncludes: CppDoc.Member = {
// Conditional headers
val dpHeaders =
guardedList (hasDataProducts) (List("Fw/Dp/DpContainer.hpp"))
val mutexHeaders =
guardedList (hasGuardedInputPorts || hasGuardedCommands || hasParameters) (
List("Os/Mutex.hpp")
)
val cmdStrHeaders =
guardedList (hasCommands || hasParameters) (List("Fw/Cmd/CmdString.hpp"))
val tlmStrHeaders =
guardedList (hasChannels) (List("Fw/Tlm/TlmString.hpp"))
val prmStrHeaders =
guardedList (hasParameters) (List("Fw/Prm/PrmString.hpp"))
val prmExtHeaders =
guardedList (hasExternalParameters) (List("Fw/Prm/PrmExternalTypes.hpp"))
val logStrHeaders =
guardedList (hasEvents) (List("Fw/Log/LogString.hpp"))
val internalStrHeaders =
guardedList (hasInternalPorts) (List("Fw/Types/InternalInterfaceString.hpp"))
val systemHeaders =
(guardedList (hasEvents) (
List("atomic")
)).map(CppWriter.systemHeaderString).sortBy(_.toLowerCase()).map(line)
val userHeaders = {
val standardHeaders = List.concat(
List(
"Fw/FPrimeBasicTypes.hpp",
"Fw/Port/InputSerializePort.hpp",
"Fw/Port/OutputSerializePort.hpp",
"Fw/Comp/ActiveComponentBase.hpp"
),
dpHeaders,
mutexHeaders,
cmdStrHeaders,
tlmStrHeaders,
prmStrHeaders,
prmExtHeaders,
logStrHeaders,
internalStrHeaders
).map(CppWriter.headerString)
val symbolHeaders = writeIncludeDirectives
def addConditional(condition: String, header: String) = lines(
s"""|$condition
|$header
|#endif
|""".stripMargin
)
(standardHeaders ++ symbolHeaders).sorted.flatMap({
case h: "#include \"Fw/Log/LogTextPortAc.hpp\"" =>
addConditional("#if FW_ENABLE_TEXT_LOGGING == 1", h)
case h: "#include \"Fw/Port/InputSerializePort.hpp\"" =>
addConditional("#if !FW_DIRECT_PORT_CALLS", h)
case h: "#include \"Fw/Port/OutputSerializePort.hpp\"" =>
addConditional("#if !FW_DIRECT_PORT_CALLS", h)
case h => lines(h)
})
}
linesMember(
List.concat(
addBlankPrefix(systemHeaders),
addBlankPrefix(userHeaders)
)
)
}
private def getCppIncludes: CppDoc.Member = {
val userHeaders = List(
"Fw/Types/Assert.hpp",
"Fw/Types/ExternalString.hpp",
"Fw/Types/String.hpp",
s.getIncludePath(componentSymbol, fileName)
).sorted.map(CppWriter.headerString).flatMap({
case s: "#include \"Fw/Types/String.hpp\"" =>
lines(
s"""|#if FW_ENABLE_TEXT_LOGGING
|$s
|#endif
|""".stripMargin
)
case s => lines(s)
})
linesMember(Line.blank :: userHeaders, CppDoc.Lines.Cpp)
}
private def getStaticAssertion: List[CppDoc.Member] = {
if serialInputPorts.isEmpty && serialOutputPorts.isEmpty then Nil
else List(
linesMember(
Line.blank :: lines(
s"""|static_assert(
| FW_PORT_SERIALIZATION == 1,
| \"$componentName component requires serialization\"
|);
|"""
)
)
)
}
private def getClassMembers: List[CppDoc.Class.Member] = {
List.concat(
// Friend classes
getFriendClassMembers,
// Constants
getConstantMembers,
// Anonymous namespace members
getAnonymousNamespaceMembers,
// Types
dpWriter.getTypeMembers,
stateMachineWriter.getTypeMembers,
// Public function members
getPublicComponentFunctionMembers,
portWriter.getPublicFunctionMembers,
cmdWriter.getPublicFunctionMembers,
paramWriter.getPublicFunctionMembers,
// Protected function members
getProtectedComponentFunctionMembers,
portWriter.getProtectedFunctionMembers,
internalPortWriter.getFunctionMembers,
stateMachineWriter.getProtectedFunctionMembers,
cmdWriter.getProtectedFunctionMembers,
eventWriter.getFunctionMembers,
tlmWriter.getFunctionMembers,
paramWriter.getProtectedFunctionMembers,
dpWriter.getProtectedDpFunctionMembers,
dpWriter.getVirtualFunctionMembers,
getTimeFunctionMember,
getMutexOperationMembers,
// Protected/private function members
getDispatchFunctionMember,
guardedList (componentData.kind == Ast.ComponentKind.Queued) (getDispatchCurrentMembers),
// Private function members
portWriter.getPrivateFunctionMembers,
stateMachineWriter.getPrivateFunctionMembers,
paramWriter.getPrivateFunctionMembers,
dpWriter.getPrivateDpFunctionMembers,
// Member variables
portWriter.getVariableMembers,
eventWriter.getVariableMembers,
tlmWriter.getVariableMembers,
paramWriter.getVariableMembers,
stateMachineWriter.getVariableMembers,
getMsgSizeVariableMember,
getMutexVariableMembers,
)
}
private def getConstantMembers: List[CppDoc.Class.Member] = {
val constants = List(
portWriter.getConstantMembers,
cmdWriter.getConstantMembers,
eventWriter.getConstantMembers,
tlmWriter.getConstantMembers,
paramWriter.getConstantMembers,
dpWriter.getConstantMembers,
stateMachineWriter.getConstantMembers
).flatten
if constants.isEmpty then Nil
else List(
List(
linesClassMember(
List(
CppDocHppWriter.writeAccessTag("protected"),
CppDocWriter.writeBannerComment(
"Constants"
),
).flatten
)
),
constants
).flatten
}
private def getFriendClassMembers: List[CppDoc.Class.Member] = {
List(
linesClassMember(
List(
CppDocWriter.writeBannerComment(
"Friend classes"
),
lines(
s"""|
|//! Friend class tester to support autocoded test harness
|friend class ${componentName}TesterBase;
|//! Friend class tester implementation to support white-box testing
|friend class ${componentName}Tester;
|"""
)
).flatten
)
)
}
private def getAnonymousNamespaceMembers: List[CppDoc.Class.Member] =
componentData.kind match {
case Ast.ComponentKind.Passive => Nil
case _ => {
val buffUnion = getBuffUnion
List(
linesClassMember(
Line.blank :: wrapInAnonymousNamespace(
intersperseBlankLines(
List(
stateMachineWriter.getAnonymousNamespaceLines,
getMsgTypeEnum,
buffUnion,
getComponentIpcSerializableBufferClass(buffUnion)
)
)
),
CppDoc.Lines.Cpp
)
)
}
}
private def getMsgTypeEnum: List[Line] = {
wrapInScope(
"enum MsgTypeEnum {",
List.concat(
lines(s"$exitConstantName = Fw::ActiveComponentBase::ACTIVE_COMPONENT_EXIT"),
dataProductAsyncInputPorts.map(portCppConstantName),
typedAsyncInputPorts.map(portCppConstantName),
serialAsyncInputPorts.map(portCppConstantName),
asyncCmds.map((_, cmd) => commandCppConstantName(cmd)),
internalPorts.map(internalPortCppConstantName),
guardedList (hasExternalStateMachineInstances) (List(externalStateMachineCppConstantName)),
guardedList (hasInternalStateMachineInstances) (List(internalStateMachineMsgType))
).map(s => line(s"$s,")),
"};"
)
}
/** Generates a union type that lets the compiler calculate
* the max serialized size of any list of arguments that goes
* on the queue */
private def getBuffUnion: List[Line] = {
// Collect the serialized sizes of all the async port arguments
// For each one, add a byte array of that size as a member
val internalPortsWithFormalParams: List[PortInstance.Internal] =
internalPorts.filter(p => getPortParams(p).size > 0)
val asyncInputPortsWithFormalParams =
(dataProductAsyncInputPorts ++ typedAsyncInputPorts).
filter(p => getPortParams(p).size > 0)
val members = List.concat(
// Data product and typed async input ports
asyncInputPortsWithFormalParams.flatMap(p => {
val portName = p.getUnqualifiedName
val _ @ Some(PortInstance.Type.DefPort(symbol)) = p.getType
val cppPortName = s.writeSymbol(symbol)
val cppPortBufferName = PortCppWriterUtils.getPortBufferName(cppPortName)
lines(s"BYTE ${portName}PortSize[$cppPortBufferName::CAPACITY];")
}),
// Command input port
{
val cppPortBufferName = PortCppWriterUtils.getPortBufferName("Fw::Cmd")
guardedList (cmdRecvPort.isDefined)
(lines(s"BYTE cmdPortSize[$cppPortBufferName::CAPACITY];"))
},
// Internal ports
// Sum the sizes of the port arguments
internalPortsWithFormalParams.flatMap(p =>
line(s"// Size of ${p.getUnqualifiedName} argument list") ::
wrapInScope(
s"BYTE ${p.getUnqualifiedName}IntIfSize[",
lines(
p.aNode._2.data.params.map(param =>
writeStaticSerializedSizeExpr(
s,
s.a.typeMap(param._2.data.typeName.id),
writeInternalPortParamType(param._2.data)
)
).mkString(" +\n")
),
"];"
)
),
guardedList (hasExternalStateMachineInstances) (
lines(
s"""|// Size of buffer for external state machine signals
|// The external SmSignalBuffer stores the signal data
|BYTE externalSmBufferSize[
| 2 * sizeof(FwEnumStoreType) + Fw::SmSignalBuffer::SERIALIZED_SIZE
|];"""
)
),
guardedList (hasInternalStateMachineInstances) (
lines(
s"""|// Size of buffer for internal state machine signals
|// The internal SmSignalBuffer stores the state machine id, the
|// signal id, and the signal data
|BYTE internalSmBufferSize[SmSignalBuffer::SERIALIZED_SIZE];"""
)
)
)
wrapInScope(
"""|// Get the max size by constructing a union of the async input, command, and
|// internal port serialization sizes
|union BuffUnion {""",
members,
"};"
)
}
private def getComponentIpcSerializableBufferClass(buffUnion: List[Line]): List[Line] = {
val maxDataSize = if buffUnion.nonEmpty then "sizeof(BuffUnion)" else "0"
lines(
s"""|// Define a message buffer class large enough to handle all the
|// asynchronous inputs to the component
|class ComponentIpcSerializableBuffer :
| public Fw::LinearBufferBase
|{
|
| public:
|
| enum {
| // Offset into data in buffer: Size of message ID and port number
| DATA_OFFSET = sizeof(FwEnumStoreType) + sizeof(FwIndexType),
| // Max data size
| MAX_DATA_SIZE = $maxDataSize,
| // Max message size: Size of message id + size of port + max data size
| SERIALIZATION_SIZE = DATA_OFFSET + MAX_DATA_SIZE
| };
|
| Fw::Serializable::SizeType getCapacity() const {
| return sizeof(m_buff);
| }
|
| U8* getBuffAddr() {
| return m_buff;
| }
|
| const U8* getBuffAddr() const {
| return m_buff;
| }
|
| private:
| // Should be the max of all the input ports serialized sizes...
| U8 m_buff[SERIALIZATION_SIZE];
|
|};
|"""
)
}
private def getPublicComponentFunctionMembers: List[CppDoc.Class.Member] = {
def writePortConnections(port: PortInstance) =
ComponentCppWriter.writePortConnections(
port,
portNumGetterName,
portVariableName,
inputPortCallbackName,
(p: PortInstance) => s"${p.getUnqualifiedName}_${p.getDirection.get.toString.capitalize}Port"
)
def writeStateMachineInit(smi: StateMachineInstance, name: String) =
smi.getSmKind match {
case StateMachine.Kind.External =>
line(s"this->m_stateMachine_$name.init(static_cast<FwEnumStoreType>(${writeSmIdName(name)}));")
case StateMachine.Kind.Internal =>
line(s"this->m_stateMachine_$name.init(${writeSmIdName(name)});")
}
val body = intersperseBlankLines(
List(
lines(
s"""|// Initialize base class
|Fw::$baseClassName::init(instance);
|"""
),
Line.addPrefixLine
(line("// Initialize state machine instances"))
(smInstancesByName.map((name, smi) => writeStateMachineInit(smi, name))),
intersperseBlankLines(specialInputPorts.map(writePortConnections)),
intersperseBlankLines(typedInputPorts.map(writePortConnections)),
intersperseBlankLines(serialInputPorts.map(writePortConnections)),
intersperseBlankLines(specialOutputPorts.map(writePortConnections)),
intersperseBlankLines(typedOutputPorts.map(writePortConnections)),
intersperseBlankLines(serialOutputPorts.map(writePortConnections)),
componentData.kind match {
case Ast.ComponentKind.Passive => Nil
case _ => List.concat(
if hasSerialAsyncInputPorts then lines(
"""|// Passed-in size added to port number and message type enumeration sizes.
|this->m_msgSize = FW_MAX(
| msgSize +
| static_cast<FwSizeType>(sizeof(FwIndexType)) +
| static_cast<FwSizeType>(sizeof(FwEnumStoreType)),
| static_cast<FwSizeType>(ComponentIpcSerializableBuffer::SERIALIZATION_SIZE)
|);
|
|// Create the queue
|Os::Queue::Status qStat = this->createQueue(queueDepth, this->m_msgSize);
|"""
)
else lines(
"""|// Create the queue
|Os::Queue::Status qStat = this->createQueue(
| queueDepth,
| static_cast<FwSizeType>(ComponentIpcSerializableBuffer::SERIALIZATION_SIZE)
|);
|"""
),
lines(
"""|FW_ASSERT(
| Os::Queue::Status::OP_OK == qStat,
| static_cast<FwAssertArgType>(qStat)
|);
|"""
)
)
}
)
)
addAccessTagAndComment(
"public",
"Component initialization",
List(
functionClassMember(
Some(s"Initialize $componentClassName object"),
"init",
initParams,
CppDoc.Type("void"),
body
)
)
)
}
private def getProtectedComponentFunctionMembers: List[CppDoc.Class.Member] = {
addAccessTagAndComment(
"protected",
"Component construction and destruction",
List(
constructorClassMember(
Some(s"Construct $componentClassName object"),
List(
CppDoc.Function.Param(
CppDoc.Type("const char*"),
"compName",
Some("The component name"),
Some("\"\"")
)
),
List(s"Fw::${kindStr}ComponentBase(compName)") :::
smInstancesByName.map { (name, smi) =>
val sm = s.a.stateMachineMap(smi.symbol)
val hasActionsOrGuards = sm.hasActions || sm.hasGuards
val args = (smi.getSmKind, hasActionsOrGuards) match {
case (StateMachine.Kind.External, _) => "this"
case (StateMachine.Kind.Internal, true) => "*this"
case (StateMachine.Kind.Internal, false) => ""
}
s"m_stateMachine_$name($args)"
},
intersperseBlankLines(
List(
throttledEvents.map((_, event) => line(
s"this->${eventThrottleCounterName(event.getName)} = 0;"
)),
throttledEventsWithTimeout.map((_, event) => line(
s"this->${eventThrottleTimeName(event.getName)} = Fw::Time();"
)),
)
)
),
destructorClassMember(
Some(s"Destroy $componentClassName object"),
Nil,
CppDoc.Class.Destructor.Virtual
)
)
)
}
private def getMutexOperationMembers: List[CppDoc.Class.Member] = {
if !(hasGuardedInputPorts || hasGuardedCommands) then Nil
else addAccessTagAndComment(
"protected",
"""|Mutex operations for guarded ports
|
|You can override these operations to provide more sophisticated
|synchronization
|""",
List(
functionClassMember(
Some("Lock the guarded mutex"),
"lock",
Nil,
CppDoc.Type("void"),
lines(
"this->m_guardedPortMutex.lock();"
),
CppDoc.Function.Virtual
),
functionClassMember(
Some("Unlock the guarded mutex"),
"unLock",
Nil,
CppDoc.Type("void"),
lines(
"this->m_guardedPortMutex.unLock();"
),
CppDoc.Function.Virtual
)
)
)
}
private def getDispatchFunctionMember: List[CppDoc.Class.Member] = {
def writeAsyncPortDispatch(p: PortInstance) = {
val body = p.getType.get match {
case PortInstance.Type.DefPort(_) =>
List(
intersperseBlankLines(
portParamTypeMap(p.getUnqualifiedName).map((n, tn, t) => {
val varDecl = writeVarDecl(s, tn, n, t)
lines(
s"""|// Deserialize argument $n
|$varDecl
|_deserStatus = _msg.deserializeTo($n);
|FW_ASSERT(
| _deserStatus == Fw::FW_SERIALIZE_OK,
| static_cast<FwAssertArgType>(_deserStatus)
|);
|"""
)
})
),
line("// Call handler function") ::
writeFunctionCall(
s"this->${inputPortHandlerName(p.getUnqualifiedName)}",
List("portNum"),
getPortParams(p).map(_._1)
),
Line.blank :: lines("break;")
).flatten
case PortInstance.Type.Serial => lines(
s"""|// Deserialize serialized buffer into new buffer
|U8 handBuff[this->m_msgSize];
|Fw::ExternalSerializeBuffer serHandBuff(
| handBuff,
| static_cast<Fw::Serializable::SizeType>(this->m_msgSize)
|);
|_deserStatus = _msg.deserializeTo(serHandBuff);
|FW_ASSERT(
| _deserStatus == Fw::FW_SERIALIZE_OK,
| static_cast<FwAssertArgType>(_deserStatus)
|);
|this->${inputPortHandlerName(p.getUnqualifiedName)}(portNum, serHandBuff);
|
|break;
|"""
)
}
line(s"// Handle async input port ${p.getUnqualifiedName}") ::
wrapInScope(
s"case ${portCppConstantName(p)}: {",
body,
"}"
)
}
def writeAsyncCommandDispatch(opcode: Command.Opcode, cmd: Command) = {
val cmdRespName = cmdRespPort.get.getUnqualifiedName
val cmdRespVarName = portVariableName(cmdRespPort.get)
val cmdRespIsConnectedName = outputPortIsConnectedName(cmdRespName)
val body = intersperseBlankLines(
List(
lines(
"""|// Deserialize opcode
|FwOpcodeType _opCode = 0;
|_deserStatus = _msg.deserializeTo(_opCode);
|FW_ASSERT (
| _deserStatus == Fw::FW_SERIALIZE_OK,
| static_cast<FwAssertArgType>(_deserStatus)
|);
|
|// Deserialize command sequence
|U32 _cmdSeq = 0;
|_deserStatus = _msg.deserializeTo(_cmdSeq);
|FW_ASSERT (
| _deserStatus == Fw::FW_SERIALIZE_OK,
| static_cast<FwAssertArgType>(_deserStatus)
|);
|
|// Deserialize command argument buffer
|Fw::CmdArgBuffer args;
|_deserStatus = _msg.deserializeTo(args);
|FW_ASSERT (
| _deserStatus == Fw::FW_SERIALIZE_OK,
| static_cast<FwAssertArgType>(_deserStatus)
|);
|
|// Reset buffer
|args.resetDeser();
|"""
),
intersperseBlankLines(
cmdParamTypeMap(opcode).map((n, tn, _) =>
lines(
s"""|// Deserialize argument $n
|$tn $n;
|_deserStatus = args.deserializeTo($n);
|if (_deserStatus != Fw::FW_SERIALIZE_OK) {
| if (this->$cmdRespIsConnectedName(0)) {
| this->cmdResponse_out(
| _opCode,
| _cmdSeq,
| Fw::CmdResponse::FORMAT_ERROR
| );
| }
| // Don't crash the task if bad arguments were passed from the ground
| break;
|}
|"""
)
)
),
lines(
s"""|// Make sure there was no data left over.
|// That means the argument buffer size was incorrect.
|#if FW_CMD_CHECK_RESIDUAL
|if (args.getDeserializeSizeLeft() != 0) {
| if (this->$cmdRespIsConnectedName(0)) {
| this->cmdResponse_out(_opCode, _cmdSeq, Fw::CmdResponse::FORMAT_ERROR);
| }
| // Don't crash the task if bad arguments were passed from the ground
| break;
|}
|#endif
|"""
),
line("// Call handler function") ::
writeFunctionCall(
s"this->${commandHandlerName(cmd.getName)}",
List("_opCode, _cmdSeq"),
cmdParamTypeMap(opcode).map(_._1)
),
lines("break;")
)
)
line(s"// Handle command ${cmd.getName}") ::
wrapInScope(
s"case ${commandCppConstantName(cmd)}: {",
body,
"}"
)
}
def writeInternalPortDispatch(p: PortInstance.Internal) = {
val body = intersperseBlankLines(
List(
intersperseBlankLines(
portParamTypeMap(p.getUnqualifiedName).map((n, tn, _) =>
lines(
s"""|$tn $n;
|_deserStatus = _msg.deserializeTo($n);
|
|// Internal interface should always deserialize
|FW_ASSERT(
| Fw::FW_SERIALIZE_OK == _deserStatus,
| static_cast<FwAssertArgType>(_deserStatus)
|);
|"""
)
)
),
lines(
"""|// Make sure there was no data left over.
|// That means the buffer size was incorrect.
|FW_ASSERT(
| _msg.getDeserializeSizeLeft() == 0,
| static_cast<FwAssertArgType>(_msg.getDeserializeSizeLeft())
|);
|"""
),
line("// Call handler function") ::
writeFunctionCall(
s"this->${internalInterfaceHandlerName(p.getUnqualifiedName)}",
Nil,
getPortParams(p).map(_._1)
),
lines("break;")
)
)
line(s"// Handle internal interface ${p.getUnqualifiedName}") ::
wrapInScope(
s"case ${internalPortCppConstantName(p)}: {",
body,
"}"
)
}
if componentData.kind == Ast.ComponentKind.Passive then Nil
else {
val assertMsgStatus = lines(
"""|FW_ASSERT(
| _msgStatus == Os::Queue::OP_OK,
| static_cast<FwAssertArgType>(_msgStatus)
|);
|"""
)
addAccessTagAndComment(
componentData.kind match {
case Ast.ComponentKind.Active => "private"
case Ast.ComponentKind.Queued => "protected"
case _ => ""
},
"Message dispatch functions",
List(
functionClassMember(
Some("Called in the message loop to dispatch a message from the queue"),
"doDispatch",
Nil,
CppDoc.Type(
"MsgDispatchStatus",
Some("Fw::QueuedComponentBase::MsgDispatchStatus")
),
List(
if hasSerialAsyncInputPorts then lines(
"""|U8 _msgBuff[this->m_msgSize];
|Fw::ExternalSerializeBuffer _msg(
| _msgBuff,
| static_cast<Fw::Serializable::SizeType>(this->m_msgSize)
|);
|"""
)
else lines("ComponentIpcSerializableBuffer _msg;"),
lines(
s"""|FwQueuePriorityType _priority = 0;
|
|Os::Queue::Status _msgStatus = this->m_queue.receive(
| _msg,
| Os::Queue::${if componentData.kind == Ast.ComponentKind.Queued then "NON" else ""}BLOCKING,
| _priority
|);
|""".stripMargin
),
if componentData.kind == Ast.ComponentKind.Queued then wrapInIfElse(
"Os::Queue::Status::EMPTY == _msgStatus",
lines("return Fw::QueuedComponentBase::MSG_DISPATCH_EMPTY;"),
assertMsgStatus
)
else assertMsgStatus,
lines(
"""|
|// Reset to beginning of buffer
|_msg.resetDeser();
|
|FwEnumStoreType _desMsg = 0;
|Fw::SerializeStatus _deserStatus = _msg.deserializeTo(_desMsg);
|FW_ASSERT(
| _deserStatus == Fw::FW_SERIALIZE_OK,
| static_cast<FwAssertArgType>(_deserStatus)
|);
|
|MsgTypeEnum _msgType = static_cast<MsgTypeEnum>(_desMsg);
|"""
),
Line.blank :: wrapInIf(
s"_msgType == $exitConstantName",
lines("return MSG_DISPATCH_EXIT;")
),
lines(
"""|
|FwIndexType portNum = 0;
|_deserStatus = _msg.deserializeTo(portNum);
|FW_ASSERT(
| _deserStatus == Fw::FW_SERIALIZE_OK,
| static_cast<FwAssertArgType>(_deserStatus)
|);
|"""
),
Line.blank :: wrapInSwitch(
"_msgType",
intersperseBlankLines(
List(
intersperseBlankLines(dataProductAsyncInputPorts.map(writeAsyncPortDispatch)),
intersperseBlankLines(typedAsyncInputPorts.map(writeAsyncPortDispatch)),
intersperseBlankLines(serialAsyncInputPorts.map(writeAsyncPortDispatch)),
intersperseBlankLines(asyncCmds.map(writeAsyncCommandDispatch)),
intersperseBlankLines(internalPorts.map(writeInternalPortDispatch)),
stateMachineWriter.writeDispatchCases,
lines(
"""|default:
| return MSG_DISPATCH_ERROR;
|"""
)
)
)
),
Line.blank :: lines("return MSG_DISPATCH_OK;")
).flatten,
CppDoc.Function.Virtual
)
)
)
}
}
private def getDispatchCurrentMembers: List[CppDoc.Class.Member] = {
val body = lines(
"""|// Dispatch all current messages unless ERROR or EXIT occur
|const FwSizeType currentMessageCount = this->m_queue.getMessagesAvailable();
|MsgDispatchStatus messageStatus = MsgDispatchStatus::MSG_DISPATCH_EMPTY;
|for (FwSizeType i = 0; i < currentMessageCount; i++) {
| messageStatus = this->doDispatch();
| if (messageStatus != QueuedComponentBase::MSG_DISPATCH_OK) {
| break;
| }
|}
|return messageStatus;"""
)
addAccessTagAndComment(
"protected",
"Helper functions for dispatching current messages",
List(
functionClassMember(
Some(s"Dispatch all current messages unless ERROR or EXIT occurs"),
"dispatchCurrentMessages",
Nil,
CppDoc.Type(
"MsgDispatchStatus",
Some("Fw::QueuedComponentBase::MsgDispatchStatus")
),
body,
CppDoc.Function.NonSV
)
)
)
}
private def getTimeFunctionMember: List[CppDoc.Class.Member] =
guardedList (hasTimeGetPort) ({
val portName = timeGetPort.get.getUnqualifiedName
val isConnectedFunctionName = outputPortIsConnectedName(portName)
val invokerName = outputPortInvokerName(portName)
addAccessTagAndComment(
"protected",
"Time",
List(
functionClassMember(
Some(
"""|Get the time
|
|\\return The current time
|"""
),
"getTime",
Nil,
CppDoc.Type("Fw::Time"),
wrapInIfElse(
s"this->$isConnectedFunctionName(0)",
lines(
s"""|Fw::Time _time;
|this->$invokerName(0, _time);
|return _time;
|"""
),
lines("return Fw::Time(TimeBase::TB_NONE, 0, 0);")
),
CppDoc.Function.NonSV,
CppDoc.Function.Const
)
)
)
})
private def getMsgSizeVariableMember: List[CppDoc.Class.Member] = {
if !hasSerialAsyncInputPorts then Nil
else List(
linesClassMember(
List(
CppDocHppWriter.writeAccessTag("private"),
lines(
"""|
|//! Stores max message size
|FwSizeType m_msgSize;
|"""
)
).flatten
)
)
}
private def getMutexVariableMembers: List[CppDoc.Class.Member] = {
if !(hasGuardedInputPorts || hasGuardedCommands || hasParameters || hasEventsWithTimeout) then Nil
else List(
linesClassMember(
List(
CppDocHppWriter.writeAccessTag("private"),
CppDocWriter.writeBannerComment(
"Mutexes"
),
if !(hasGuardedInputPorts || hasGuardedCommands) then Nil
else lines(
"""|
|//! Mutex for guarded ports
|Os::Mutex m_guardedPortMutex;
|"""
),
if !hasParameters then Nil
else lines(