-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathIoTFleetWiseEngine.cpp
1808 lines (1701 loc) · 84.4 KB
/
IoTFleetWiseEngine.cpp
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#include "IoTFleetWiseEngine.h"
#include "AwsBootstrap.h"
#include "AwsIotConnectivityModule.h"
#include "AwsSDKMemoryManager.h"
#include "CollectionInspectionAPITypes.h"
#include "DataSenderManager.h"
#include "DataSenderProtoWriter.h"
#include "DataSenderTypes.h"
#include "ILogger.h"
#include "IoTFleetWiseConfig.h"
#include "LogLevel.h"
#include "LoggingModule.h"
#include "MqttClientWrapper.h"
#include "QueueTypes.h"
#include "SignalTypes.h"
#include "TelemetryDataSender.h"
#include "TraceModule.h"
#include <algorithm>
#include <aws/crt/Api.h>
#include <aws/crt/Types.h>
#include <aws/iot/Mqtt5Client.h>
#include <boost/optional/optional.hpp>
#include <cstddef>
#include <exception>
#include <fstream>
#include <functional>
#include <unordered_map>
#ifdef FWE_FEATURE_GREENGRASSV2
#include "AwsGreengrassV2ConnectivityModule.h"
#ifdef FWE_FEATURE_S3
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#endif
#endif
#ifdef FWE_FEATURE_S3
#include "Credentials.h"
#include "TransferManagerWrapper.h"
#include <aws/core/client/ClientConfiguration.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/S3ServiceClientModel.h>
#include <aws/transfer/TransferManager.h>
#endif
#ifdef FWE_FEATURE_VISION_SYSTEM_DATA
#include "DataSenderIonWriter.h"
#include "VisionSystemDataSender.h"
#endif
#ifdef FWE_FEATURE_REMOTE_COMMANDS
#include "CommandResponseDataSender.h"
#endif
#ifdef FWE_FEATURE_SOMEIP
#include "ExampleSomeipInterfaceWrapper.h"
#include <CommonAPI/CommonAPI.hpp>
#include <vsomeip/vsomeip.hpp>
#endif
#ifdef FWE_FEATURE_LAST_KNOWN_STATE
#include "LastKnownStateDataSender.h"
#include "LastKnownStateInspector.h"
#endif
#ifdef FWE_FEATURE_STORE_AND_FORWARD
#include "RateLimiter.h"
#include "StreamForwarder.h"
#endif
#ifdef FWE_FEATURE_CUSTOM_FUNCTION_EXAMPLES
#include "CustomFunctionMath.h"
#endif
#ifdef FWE_FEATURE_UDS_DTC_EXAMPLE
#include <stdexcept>
#endif
namespace Aws
{
namespace IoTFleetWise
{
static constexpr uint64_t DEFAULT_RETRY_UPLOAD_PERSISTED_INTERVAL_MS = 10000;
static const std::string CAN_INTERFACE_TYPE = "canInterface";
static const std::string EXTERNAL_CAN_INTERFACE_TYPE = "externalCanInterface";
static const std::string OBD_INTERFACE_TYPE = "obdInterface";
static const std::string NAMED_SIGNAL_INTERFACE_TYPE = "namedSignalInterface";
#ifdef FWE_FEATURE_ROS2
static const std::string ROS2_INTERFACE_TYPE = "ros2Interface";
#endif
#ifdef FWE_FEATURE_SOMEIP
static const std::string SOMEIP_TO_CAN_BRIDGE_INTERFACE_TYPE = "someipToCanBridgeInterface";
static const std::string SOMEIP_COLLECTION_INTERFACE_TYPE = "someipCollectionInterface";
#endif
#ifdef FWE_FEATURE_REMOTE_COMMANDS
#ifdef FWE_FEATURE_SOMEIP
static const std::string SOMEIP_COMMAND_INTERFACE_TYPE = "someipCommandInterface";
#endif
static const std::string CAN_COMMAND_INTERFACE_TYPE = "canCommandInterface";
static const std::unordered_map<std::string, CanCommandDispatcher::CommandConfig>
EXAMPLE_CAN_INTERFACE_SUPPORTED_ACTUATOR_MAP = {
{ "Vehicle.actuator6", { 0x00000123, 0x00000456, SignalType::INT32 } },
{ "Vehicle.actuator7", { 0x80000789, 0x80000ABC, SignalType::DOUBLE } },
};
#endif
#ifdef FWE_FEATURE_IWAVE_GPS
static const std::string IWAVE_GPS_INTERFACE_TYPE = "iWaveGpsInterface";
#endif
#ifdef FWE_FEATURE_EXTERNAL_GPS
static const std::string EXTERNAL_GPS_INTERFACE_TYPE = "externalGpsInterface";
#endif
#ifdef FWE_FEATURE_AAOS_VHAL
static const std::string AAOS_VHAL_INTERFACE_TYPE = "aaosVhalInterface";
#endif
#ifdef FWE_FEATURE_UDS_DTC_EXAMPLE
static const std::string UDS_DTC_INTERFACE = "exampleUDSInterface";
#endif
namespace
{
/**
* @brief Get the File Contents including whitespace characters
*
* @param p The file path
* @return std::string File contents
*/
std::string
getFileContents( const std::string &p )
{
constexpr auto NUM_CHARS = 1;
std::string ret;
std::ifstream fs{ p };
// False alarm: uninit_use_in_call: Using uninitialized value "fs._M_streambuf_state" when calling "good".
// coverity[uninit_use_in_call : SUPPRESS]
while ( fs.good() )
{
auto c = static_cast<char>( fs.get() );
ret.append( NUM_CHARS, c );
}
return ret;
}
/**
* @brief Get the absolute file path, if the path is already absolute its returned.
*
* @param p The file path
* @param basePath Base path to which the p is relative
* @return boost::filesystem::path Absolute file path
*/
boost::filesystem::path
getAbsolutePath( const std::string &p, const boost::filesystem::path &basePath )
{
boost::filesystem::path filePath( p );
if ( !filePath.is_absolute() )
{
return basePath / filePath;
}
return filePath;
}
} // namespace
#ifdef FWE_FEATURE_S3
std::shared_ptr<Aws::Utils::Threading::PooledThreadExecutor>
IoTFleetWiseEngine::getTransferManagerExecutor()
{
std::lock_guard<std::mutex> lock( mTransferManagerExecutorMutex );
if ( mTransferManagerExecutor == nullptr )
{
mTransferManagerExecutor = Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>( "executor", 25 );
}
return mTransferManagerExecutor;
}
#endif
IoTFleetWiseEngine::IoTFleetWiseEngine()
{
TraceModule::get().sectionBegin( TraceSection::FWE_STARTUP );
}
IoTFleetWiseEngine::~IoTFleetWiseEngine()
{
// To make sure the thread stops during teardown of tests.
if ( isAlive() )
{
stop();
}
setLogForwarding( nullptr );
}
#ifdef FWE_FEATURE_SOMEIP
static std::shared_ptr<ExampleSomeipInterfaceWrapper>
createExampleSomeipInterfaceWrapper( const std::string &applicationName,
const std::string &exampleInstance,
std::shared_ptr<RawData::BufferManager> rawBufferManager,
bool subscribeToLongRunningCommandStatus )
{
return std::make_shared<ExampleSomeipInterfaceWrapper>(
"local",
exampleInstance,
applicationName,
[]( std::string domain,
std::string instance,
std::string connection ) -> std::shared_ptr<v1::commonapi::ExampleSomeipInterfaceProxy<>> {
return CommonAPI::Runtime::get()->buildProxy<v1::commonapi::ExampleSomeipInterfaceProxy>(
domain, instance, connection );
},
std::move( rawBufferManager ),
subscribeToLongRunningCommandStatus );
}
#endif
bool
IoTFleetWiseEngine::connect( const Json::Value &jsonConfig, const boost::filesystem::path &configFileDirectoryPath )
{
// Main bootstrap sequence.
try
{
IoTFleetWiseConfig config( jsonConfig );
uint64_t persistencyUploadRetryIntervalMs = 0;
if ( ( config["staticConfig"].isMember( "persistency" ) ) )
{
const auto persistencyPath = config["staticConfig"]["persistency"]["persistencyPath"].asStringRequired();
/*************************Payload Manager and Persistency library bootstrap begin*********/
// Create an object for Persistency
mPersistDecoderManifestCollectionSchemesAndData = std::make_shared<CacheAndPersist>(
getAbsolutePath( persistencyPath, configFileDirectoryPath ).string(),
config["staticConfig"]["persistency"]["persistencyPartitionMaxSize"].asSizeRequired() );
if ( !mPersistDecoderManifestCollectionSchemesAndData->init() )
{
FWE_LOG_ERROR( "Failed to init persistency library" );
}
persistencyUploadRetryIntervalMs =
config["staticConfig"]["persistency"]["persistencyUploadRetryIntervalMs"].asU64Optional().get_value_or(
DEFAULT_RETRY_UPLOAD_PERSISTED_INTERVAL_MS );
// Payload Manager for offline data management
mPayloadManager = std::make_shared<PayloadManager>( mPersistDecoderManifestCollectionSchemesAndData );
}
else
{
FWE_LOG_INFO( "Persistency feature is disabled in the configuration." );
#ifdef FWE_FEATURE_STORE_AND_FORWARD
FWE_LOG_INFO( "Disabling Store and Forward feature as persistency is disabled." );
mStoreAndForwardEnabled = false;
#endif
}
/*************************Payload Manager and Persistency library bootstrap end************/
/*************************CAN InterfaceID to InternalID Translator begin*********/
for ( unsigned i = 0; i < config["networkInterfaces"].getArraySizeRequired(); i++ )
{
auto networkInterface = config["networkInterfaces"][i];
auto networkInterfaceType = networkInterface["type"].asStringRequired();
if ( ( networkInterfaceType == CAN_INTERFACE_TYPE ) ||
( networkInterfaceType == EXTERNAL_CAN_INTERFACE_TYPE )
#ifdef FWE_FEATURE_SOMEIP
|| ( networkInterfaceType == SOMEIP_TO_CAN_BRIDGE_INTERFACE_TYPE )
#endif
)
{
mCANIDTranslator.add( networkInterface["interfaceId"].asStringRequired() );
}
}
/*************************CAN InterfaceID to InternalID Translator end*********/
/**************************Connectivity bootstrap begin*******************************/
// Pass on the AWS SDK Bootstrap handle to the IoTModule.
auto bootstrapPtr = AwsBootstrap::getInstance().getClientBootStrap();
std::size_t maxAwsSdkHeapMemoryBytes = 0U;
if ( config["staticConfig"]["internalParameters"].isMember( "maximumAwsSdkHeapMemoryBytes" ) )
{
maxAwsSdkHeapMemoryBytes =
config["staticConfig"]["internalParameters"]["maximumAwsSdkHeapMemoryBytes"].asSizeRequired();
if ( ( maxAwsSdkHeapMemoryBytes != 0U ) &&
AwsSDKMemoryManager::getInstance().setLimit( maxAwsSdkHeapMemoryBytes ) )
{
FWE_LOG_INFO( "Maximum AWS SDK Heap Memory Bytes has been configured:" +
std::to_string( maxAwsSdkHeapMemoryBytes ) );
}
else
{
FWE_LOG_TRACE( "Maximum AWS SDK Heap Memory Bytes will use default value" );
}
}
else
{
FWE_LOG_TRACE( "Maximum AWS SDK Heap Memory Bytes will use default value" );
}
auto mqttConfig = config["staticConfig"]["mqttConnection"];
auto clientId = mqttConfig["clientId"].asStringRequired();
std::string connectionType = mqttConfig["connectionType"].asStringOptional().get_value_or( "iotCore" );
TopicConfigArgs topicConfigArgs;
topicConfigArgs.iotFleetWisePrefix = mqttConfig["iotFleetWiseTopicPrefix"].asStringOptional();
topicConfigArgs.commandsPrefix = mqttConfig["commandsTopicPrefix"].asStringOptional();
topicConfigArgs.deviceShadowPrefix = mqttConfig["deviceShadowTopicPrefix"].asStringOptional();
topicConfigArgs.jobsPrefix = mqttConfig["jobsTopicPrefix"].asStringOptional();
topicConfigArgs.metricsTopic = mqttConfig["metricsUploadTopic"].asStringOptional().get_value_or( "" );
topicConfigArgs.logsTopic = mqttConfig["loggingUploadTopic"].asStringOptional().get_value_or( "" );
mTopicConfig = std::make_unique<TopicConfig>( clientId, topicConfigArgs );
if ( connectionType == "iotCore" )
{
std::string privateKey;
std::string certificate;
std::string rootCA;
FWE_LOG_INFO( "ConnectionType is iotCore" );
// fetch connection parameters from config
if ( mqttConfig.isMember( "privateKey" ) )
{
privateKey = mqttConfig["privateKey"].asStringRequired();
}
else if ( mqttConfig.isMember( "privateKeyFilename" ) )
{
auto privKeyPathAbs =
getAbsolutePath( mqttConfig["privateKeyFilename"].asStringRequired(), configFileDirectoryPath )
.string();
privateKey = getFileContents( privKeyPathAbs );
}
if ( mqttConfig.isMember( "certificate" ) )
{
certificate = mqttConfig["certificate"].asStringRequired();
}
else if ( mqttConfig.isMember( "certificateFilename" ) )
{
auto certPathAbs =
getAbsolutePath( mqttConfig["certificateFilename"].asStringRequired(), configFileDirectoryPath )
.string();
certificate = getFileContents( certPathAbs );
}
if ( mqttConfig.isMember( "rootCA" ) )
{
rootCA = mqttConfig["rootCA"].asStringRequired();
}
else if ( mqttConfig.isMember( "rootCAFilename" ) )
{
auto rootCAPathAbs =
getAbsolutePath( mqttConfig["rootCAFilename"].asStringRequired(), configFileDirectoryPath )
.string();
rootCA = getFileContents( rootCAPathAbs );
}
// coverity[autosar_cpp14_a20_8_5_violation] - can't use make_unique as the constructor is private
auto builder = std::unique_ptr<Aws::Iot::Mqtt5ClientBuilder>(
Aws::Iot::Mqtt5ClientBuilder::NewMqtt5ClientBuilderWithMtlsFromMemory(
mqttConfig["endpointUrl"].asStringRequired().c_str(),
Crt::ByteCursorFromCString( certificate.c_str() ),
Crt::ByteCursorFromCString( privateKey.c_str() ) ) );
std::unique_ptr<MqttClientBuilderWrapper> builderWrapper;
if ( builder == nullptr )
{
FWE_LOG_ERROR( "Failed to setup mqtt5 client builder with error code " +
std::to_string( Aws::Crt::LastError() ) + ": " +
Aws::Crt::ErrorDebugString( Aws::Crt::LastError() ) );
return false;
}
else
{
builder->WithBootstrap( bootstrapPtr );
builderWrapper = std::make_unique<MqttClientBuilderWrapper>( std::move( builder ) );
}
AwsIotConnectivityConfig mqttConnectionConfig;
mqttConnectionConfig.keepAliveIntervalSeconds =
static_cast<uint16_t>( mqttConfig["keepAliveIntervalSeconds"].asU32Optional().get_value_or(
MQTT_KEEP_ALIVE_INTERVAL_SECONDS ) );
mqttConnectionConfig.pingTimeoutMs =
mqttConfig["pingTimeoutMs"].asU32Optional().get_value_or( MQTT_PING_TIMEOUT_MS );
mqttConnectionConfig.sessionExpiryIntervalSeconds =
mqttConfig["sessionExpiryIntervalSeconds"].asU32Optional().get_value_or(
MQTT_SESSION_EXPIRY_INTERVAL_SECONDS );
mConnectivityModule = std::make_shared<AwsIotConnectivityModule>(
rootCA, clientId, std::move( builderWrapper ), *mTopicConfig, mqttConnectionConfig );
#ifdef FWE_FEATURE_S3
if ( config["staticConfig"].isMember( "credentialsProvider" ) )
{
auto crtCredentialsProvider = createX509CredentialsProvider(
bootstrapPtr,
clientId,
privateKey,
certificate,
config["staticConfig"]["credentialsProvider"]["endpointUrl"].asStringRequired(),
config["staticConfig"]["credentialsProvider"]["roleAlias"].asStringRequired() );
mAwsCredentialsProvider = std::make_shared<CrtCredentialsProviderAdapter>( crtCredentialsProvider );
}
#endif
}
#ifdef FWE_FEATURE_GREENGRASSV2
else if ( connectionType == "iotGreengrassV2" )
{
FWE_LOG_INFO( "ConnectionType is iotGreengrassV2" );
mConnectivityModule = std::make_shared<AwsGreengrassV2ConnectivityModule>( bootstrapPtr, *mTopicConfig );
#ifdef FWE_FEATURE_S3
mAwsCredentialsProvider = std::make_shared<Aws::Auth::DefaultAWSCredentialsProviderChain>();
#endif
}
#endif
else
{
FWE_LOG_ERROR( "Unknown connection type: " + connectionType );
return false;
}
mReceiverCollectionSchemeList = mConnectivityModule->createReceiver( mTopicConfig->collectionSchemesTopic );
mReceiverDecoderManifest = mConnectivityModule->createReceiver( mTopicConfig->decoderManifestTopic );
#ifdef FWE_FEATURE_STORE_AND_FORWARD
if ( mStoreAndForwardEnabled )
{
// Receivers to receive Store and Forward Data Upload Requests
mReceiverIotJob = mConnectivityModule->createReceiver( mTopicConfig->jobNotificationTopic );
mReceiverJobDocumentAccepted =
mConnectivityModule->createReceiver( mTopicConfig->getJobExecutionAcceptedTopic );
mReceiverJobDocumentRejected =
mConnectivityModule->createReceiver( mTopicConfig->getJobExecutionRejectedTopic );
mReceiverPendingJobsAccepted =
mConnectivityModule->createReceiver( mTopicConfig->getPendingJobExecutionsAcceptedTopic );
mReceiverPendingJobsRejected =
mConnectivityModule->createReceiver( mTopicConfig->getPendingJobExecutionsRejectedTopic );
mReceiverUpdateIotJobStatusAccepted =
mConnectivityModule->createReceiver( mTopicConfig->updateJobExecutionAcceptedTopic );
mReceiverUpdateIotJobStatusRejected =
mConnectivityModule->createReceiver( mTopicConfig->updateJobExecutionRejectedTopic );
mReceiverCanceledIoTJobs =
mConnectivityModule->createReceiver( mTopicConfig->jobCancellationInProgressTopic );
}
#endif
mMqttSender = mConnectivityModule->createSender();
#ifdef FWE_FEATURE_REMOTE_COMMANDS
std::shared_ptr<IReceiver> receiverCommandRequest;
std::shared_ptr<IReceiver> receiverRejectedCommandResponse;
std::shared_ptr<IReceiver> receiverAcceptedCommandResponse;
receiverCommandRequest = mConnectivityModule->createReceiver( mTopicConfig->commandRequestTopic );
// The accepted/rejected messages are always sent regardless of whether we are subscribing to the topics or
// not. So even if we don't need to receive them, we subscribe to them just to ensure we don't log any
// error.
receiverAcceptedCommandResponse =
mConnectivityModule->createReceiver( mTopicConfig->commandResponseAcceptedTopic );
receiverRejectedCommandResponse =
mConnectivityModule->createReceiver( mTopicConfig->commandResponseRejectedTopic );
#endif
#ifdef FWE_FEATURE_LAST_KNOWN_STATE
std::shared_ptr<IReceiver> receiverLastKnownStateConfig =
mConnectivityModule->createReceiver( mTopicConfig->lastKnownStateConfigTopic );
#endif
#ifdef FWE_FEATURE_SOMEIP
if ( !config["staticConfig"].isMember( "deviceShadowOverSomeip" ) )
{
FWE_LOG_TRACE( "DeviceShadowOverSomeip is disabled as no deviceShadowOverSomeip member in staticConfig" );
}
else
{
std::shared_ptr<IReceiver> receiverDeviceShadow =
mConnectivityModule->createReceiver( mTopicConfig->deviceShadowPrefix + "#" );
mDeviceShadowOverSomeip = std::make_shared<DeviceShadowOverSomeip>( mMqttSender );
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
receiverDeviceShadow->subscribeToDataReceived( std::bind(
&DeviceShadowOverSomeip::onDataReceived, mDeviceShadowOverSomeip.get(), std::placeholders::_1 ) );
mDeviceShadowOverSomeipInstanceName =
config["staticConfig"]["deviceShadowOverSomeip"]["someipInstance"].asStringOptional().get_value_or(
"commonapi.DeviceShadowOverSomeipInterface" );
if ( !CommonAPI::Runtime::get()->registerService(
"local",
mDeviceShadowOverSomeipInstanceName,
mDeviceShadowOverSomeip,
config["staticConfig"]["deviceShadowOverSomeip"]["someipApplicationName"].asStringRequired() ) )
{
FWE_LOG_ERROR( "Failed to register DeviceShadowOverSomeip service" );
return false;
}
}
#endif
boost::optional<RawData::BufferManagerConfig> rawDataBufferManagerConfig;
auto rawDataBufferJsonConfig = config["staticConfig"]["visionSystemDataCollection"]["rawDataBuffer"];
auto rawBufferSize = rawDataBufferJsonConfig["maxSize"].asSizeOptional();
if ( rawBufferSize.get_value_or( SIZE_MAX ) > 0 )
{
// Create a Raw Data Buffer Manager
std::vector<RawData::SignalBufferOverrides> rawDataBufferOverridesPerSignal;
for ( auto i = 0U; i < rawDataBufferJsonConfig["overridesPerSignal"].getArraySizeOptional(); i++ )
{
auto signalOverridesJson = rawDataBufferJsonConfig["overridesPerSignal"][i];
RawData::SignalBufferOverrides signalOverrides;
signalOverrides.interfaceId = signalOverridesJson["interfaceId"].asStringRequired();
signalOverrides.messageId = signalOverridesJson["messageId"].asStringRequired();
signalOverrides.reservedBytes = signalOverridesJson["reservedSize"].asSizeOptional();
signalOverrides.maxNumOfSamples = signalOverridesJson["maxSamples"].asSizeOptional();
signalOverrides.maxBytesPerSample = signalOverridesJson["maxSizePerSample"].asSizeOptional();
signalOverrides.maxBytes = signalOverridesJson["maxSize"].asSizeOptional();
rawDataBufferOverridesPerSignal.emplace_back( signalOverrides );
}
rawDataBufferManagerConfig =
RawData::BufferManagerConfig::create( rawBufferSize,
rawDataBufferJsonConfig["reservedSizePerSignal"].asSizeOptional(),
rawDataBufferJsonConfig["maxSamplesPerSignal"].asSizeOptional(),
rawDataBufferJsonConfig["maxSizePerSample"].asSizeOptional(),
rawDataBufferJsonConfig["maxSizePerSignal"].asSizeOptional(),
rawDataBufferOverridesPerSignal );
if ( !rawDataBufferManagerConfig )
{
FWE_LOG_ERROR( "Failed to create raw data buffer manager config" );
return false;
}
mRawBufferManager = std::make_shared<RawData::BufferManager>( rawDataBufferManagerConfig.get() );
}
/*************************Connectivity bootstrap end***************************************/
/*************************Remote Profiling bootstrap begin**********************************/
if ( config["staticConfig"].isMember( "remoteProfilerDefaultValues" ) )
{
LogLevel logThreshold = LogLevel::Off;
/*
* logging-upload-level-threshold specifies which log messages normally output to STDOUT are also
* uploaded over MQTT. Default is OFF which means no messages are uploaded. If its for example
* "Warning" all log messages with this or a higher log level are mirrored over MQTT
*/
stringToLogLevel(
config["staticConfig"]["remoteProfilerDefaultValues"]["loggingUploadLevelThreshold"].asStringRequired(),
logThreshold );
/*
* metrics-upload-interval-ms defines the interval in which all metrics should be uploaded
* 0 means metrics upload is disabled which should be the default. Currently the metrics are
* uploaded every given interval independent if the value changed or not
*
* logging-upload-max-wait-before-upload-ms to avoid to many separate mqtt messages the log messages
* are aggregated and sent out delayed. The maximum allowed delay is specified here
*
* profiler-prefix metrics names uploaded will be prefixed with this string which could
* be set different for every vehicle
*/
// These parameters need to be added to the Config file to enable the feature :
// metricsUploadIntervalMs
// loggingUploadMaxWaitBeforeUploadMs
// profilerPrefix
mRemoteProfiler = std::make_unique<RemoteProfiler>(
mMqttSender,
config["staticConfig"]["remoteProfilerDefaultValues"]["metricsUploadIntervalMs"].asU32Required(),
config["staticConfig"]["remoteProfilerDefaultValues"]["loggingUploadMaxWaitBeforeUploadMs"]
.asU32Required(),
logThreshold,
config["staticConfig"]["remoteProfilerDefaultValues"]["profilerPrefix"].asStringRequired() );
setLogForwarding( mRemoteProfiler.get() );
}
/*************************Remote Profiling bootstrap ends**********************************/
/*************************Inspection Engine bootstrap begin*********************************/
auto signalBufferSize = config["staticConfig"]["bufferSizes"]["decodedSignalsBufferSize"].asSizeRequired();
auto signalBuffer =
std::make_shared<SignalBuffer>( signalBufferSize,
"Signal Buffer",
TraceAtomicVariable::QUEUE_CONSUMER_TO_INSPECTION_DATA_FRAMES,
// Notify listeners when 10% of the buffer is full so that we don't
// let it grow too much.
signalBufferSize / 10 );
auto signalBufferDistributor = std::make_shared<SignalBufferDistributor>();
signalBufferDistributor->registerQueue( signalBuffer );
// Create the Data Inspection Queue
mCollectedDataReadyToPublish = std::make_shared<DataSenderQueue>(
config["staticConfig"]["internalParameters"]["readyToPublishDataBufferSize"].asSizeRequired(),
"Collected Data",
TraceAtomicVariable::QUEUE_INSPECTION_TO_SENDER );
auto dataSenderProtoWriter = std::make_shared<DataSenderProtoWriter>( mCANIDTranslator, mRawBufferManager );
auto payloadConfigUncompressed = config["staticConfig"]["payloadAdaption"]["uncompressed"];
PayloadAdaptionConfig payloadAdaptionConfigUncompressed{
payloadConfigUncompressed["transmitThresholdStartPercent"].asU32Optional().get_value_or( 80 ),
payloadConfigUncompressed["payloadSizeLimitMinPercent"].asU32Optional().get_value_or( 70 ),
payloadConfigUncompressed["payloadSizeLimitMaxPercent"].asU32Optional().get_value_or( 90 ),
payloadConfigUncompressed["transmitThresholdAdaptPercent"].asU32Optional().get_value_or( 10 ) };
auto payloadConfigCompressed = config["staticConfig"]["payloadAdaption"]["compressed"];
// Snappy typically compresses to around 30% of original size, so set the starting compressed transmit threshold
// to double the maximum payload size:
PayloadAdaptionConfig payloadAdaptionConfigCompressed{
payloadConfigCompressed["transmitThresholdStartPercent"].asU32Optional().get_value_or( 200 ),
payloadConfigCompressed["payloadSizeLimitMinPercent"].asU32Optional().get_value_or( 70 ),
payloadConfigCompressed["payloadSizeLimitMaxPercent"].asU32Optional().get_value_or( 90 ),
payloadConfigCompressed["transmitThresholdAdaptPercent"].asU32Optional().get_value_or( 10 ) };
auto telemetryDataSender = std::make_shared<TelemetryDataSender>(
mMqttSender, dataSenderProtoWriter, payloadAdaptionConfigUncompressed, payloadAdaptionConfigCompressed );
std::unordered_map<SenderDataType, std::shared_ptr<DataSender>> dataSenders;
dataSenders[SenderDataType::TELEMETRY] = telemetryDataSender;
#ifdef FWE_FEATURE_STORE_AND_FORWARD
if ( mStoreAndForwardEnabled )
{
const auto persistencyPath = config["staticConfig"]["persistency"]["persistencyPath"].asStringRequired();
mStreamManager = std::make_shared<Aws::IoTFleetWise::Store::StreamManager>(
persistencyPath,
dataSenderProtoWriter,
config["staticConfig"]["publishToCloudParameters"]["maxPublishMessageCount"].asU32Required() );
auto rateLimiter = std::make_shared<RateLimiter>(
config["staticConfig"]["storeAndForward"]["forwardMaxTokens"].asU32Optional().get_value_or(
DEFAULT_MAX_TOKENS ),
config["staticConfig"]["storeAndForward"]["forwardTokenRefillsPerSecond"].asU32Optional().get_value_or(
DEFAULT_TOKEN_REFILLS_PER_SECOND ) );
mStreamForwarder = std::make_shared<Aws::IoTFleetWise::Store::StreamForwarder>(
mStreamManager, telemetryDataSender, rateLimiter );
// Start the forwarder
if ( !mStreamForwarder->start() )
{
FWE_LOG_ERROR( "Failed to init and start the Stream Forwarder" );
return false;
}
}
#endif
// Init and start the Inspection Engine
auto minFetchTriggerIntervalMs =
config["staticConfig"]["internalParameters"]["minFetchTriggerIntervalMs"].asU32Optional().get_value_or(
MIN_FETCH_TRIGGER_MS );
mCollectionInspectionEngine = std::make_shared<CollectionInspectionEngine>( minFetchTriggerIntervalMs );
mCollectionInspectionWorkerThread =
std::make_shared<CollectionInspectionWorkerThread>( *mCollectionInspectionEngine );
if ( ( !mCollectionInspectionWorkerThread->init(
signalBuffer,
mCollectedDataReadyToPublish,
config["staticConfig"]["threadIdleTimes"]["inspectionThreadIdleTimeMs"].asU32Required(),
mRawBufferManager
#ifdef FWE_FEATURE_STORE_AND_FORWARD
,
mStreamForwarder,
mStreamManager
#endif
) ) ||
( !mCollectionInspectionWorkerThread->start() ) )
{
FWE_LOG_ERROR( "Failed to init and start the Inspection Engine" );
return false;
}
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
signalBuffer->subscribeToNewDataAvailable( std::bind( &CollectionInspectionWorkerThread::onNewDataAvailable,
mCollectionInspectionWorkerThread.get() ) );
/*************************Inspection Engine bootstrap end***********************************/
/*************************Store and Forward IoT Jobs bootstrap begin************************/
#ifdef FWE_FEATURE_STORE_AND_FORWARD
if ( mStoreAndForwardEnabled )
{
mIoTJobsDataRequestHandler =
std::make_unique<IoTJobsDataRequestHandler>( mMqttSender,
mReceiverIotJob,
mReceiverJobDocumentAccepted,
mReceiverJobDocumentRejected,
mReceiverPendingJobsAccepted,
mReceiverPendingJobsRejected,
mReceiverUpdateIotJobStatusAccepted,
mReceiverUpdateIotJobStatusRejected,
mReceiverCanceledIoTJobs,
mStreamManager,
mStreamForwarder,
clientId );
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mConnectivityModule->subscribeToConnectionEstablished(
std::bind( &IoTJobsDataRequestHandler::onConnectionEstablished, mIoTJobsDataRequestHandler.get() ) );
}
#endif
/*************************Store and Forward IoT Jobs bootstrap end**************************/
/*************************DataSender bootstrap begin*********************************/
#ifdef FWE_FEATURE_VISION_SYSTEM_DATA
std::shared_ptr<DataSenderIonWriter> ionWriter;
std::shared_ptr<VisionSystemDataSender> visionSystemDataSender;
if ( ( mAwsCredentialsProvider == nullptr ) || ( !config["staticConfig"].isMember( "s3Upload" ) ) )
{
FWE_LOG_INFO( "S3 sender not initialized so no vision-system-data data upload will be supported. Add "
"'credentialsProvider' and 's3Upload' section to the config to initialize it." )
}
else
{
auto s3MaxConnections = config["staticConfig"]["s3Upload"]["maxConnections"].asU32Required();
s3MaxConnections = s3MaxConnections > 0U ? s3MaxConnections : 1U;
auto createTransferManagerWrapper =
[this, s3MaxConnections]( Aws::Client::ClientConfiguration &clientConfiguration,
Aws::Transfer::TransferManagerConfiguration &transferManagerConfiguration )
-> std::shared_ptr<TransferManagerWrapper> {
clientConfiguration.maxConnections = s3MaxConnections;
transferManagerConfiguration.transferExecutor = getTransferManagerExecutor().get();
auto s3Client =
std::make_shared<Aws::S3::S3Client>( mAwsCredentialsProvider,
Aws::MakeShared<Aws::S3::S3EndpointProvider>( "S3Client" ),
clientConfiguration );
transferManagerConfiguration.s3Client = s3Client;
return std::make_shared<TransferManagerWrapper>(
Aws::Transfer::TransferManager::Create( transferManagerConfiguration ) );
};
mS3Sender = std::make_shared<S3Sender>(
createTransferManagerWrapper, config["staticConfig"]["s3Upload"]["multipartSize"].asSizeRequired() );
ionWriter = std::make_shared<DataSenderIonWriter>( mRawBufferManager, clientId );
visionSystemDataSender = std::make_shared<VisionSystemDataSender>(
mCollectedDataReadyToPublish, mS3Sender, ionWriter, clientId );
dataSenders[SenderDataType::VISION_SYSTEM] = visionSystemDataSender;
}
#endif
#ifdef FWE_FEATURE_REMOTE_COMMANDS
mCommandResponses = std::make_shared<DataSenderQueue>(
config["staticConfig"]["internalParameters"]["readyToPublishCommandResponsesBufferSize"]
.asSizeOptional()
.get_value_or( 100 ),
"Command Responses",
TraceAtomicVariable::QUEUE_PENDING_COMMAND_RESPONSES );
size_t maxConcurrentCommandRequests =
config["staticConfig"]["internalParameters"]["maxConcurrentCommandRequests"].asSizeOptional().get_value_or(
100 );
mActuatorCommandManager = std::make_shared<ActuatorCommandManager>(
mCommandResponses, maxConcurrentCommandRequests, mRawBufferManager );
dataSenders[SenderDataType::COMMAND_RESPONSE] = std::make_shared<CommandResponseDataSender>( mMqttSender );
#endif
#ifdef FWE_FEATURE_LAST_KNOWN_STATE
mLastKnownStateDataReadyToPublish = std::make_shared<DataSenderQueue>(
config["staticConfig"]["internalParameters"]["readyToPublishDataBufferSize"].asSizeRequired(),
"LastKnownState data",
TraceAtomicVariable::QUEUE_LAST_KNOWN_STATE_INSPECTION_TO_SENDER );
dataSenders[SenderDataType::LAST_KNOWN_STATE] = std::make_shared<LastKnownStateDataSender>(
mMqttSender,
config["staticConfig"]["publishToCloudParameters"]["maxPublishLastKnownStateMessageCount"]
.asU32Optional()
.get_value_or( 1000 ) );
#endif
mDataSenderManager =
std::make_shared<DataSenderManager>( std::move( dataSenders ), mMqttSender, mPayloadManager );
std::vector<std::shared_ptr<DataSenderQueue>> dataToSendQueues = {
#ifdef FWE_FEATURE_REMOTE_COMMANDS
mCommandResponses,
#endif
#ifdef FWE_FEATURE_LAST_KNOWN_STATE
mLastKnownStateDataReadyToPublish,
#endif
mCollectedDataReadyToPublish };
mDataSenderManagerWorkerThread = std::make_shared<DataSenderManagerWorkerThread>(
mConnectivityModule, mDataSenderManager, persistencyUploadRetryIntervalMs, dataToSendQueues );
if ( !mDataSenderManagerWorkerThread->start() )
{
FWE_LOG_ERROR( "Failed to init and start the Data Sender" );
return false;
}
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectedDataReadyToPublish->subscribeToNewDataAvailable(
std::bind( &DataSenderManagerWorkerThread::onDataReadyToPublish, mDataSenderManagerWorkerThread.get() ) );
#ifdef FWE_FEATURE_LAST_KNOWN_STATE
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mLastKnownStateDataReadyToPublish->subscribeToNewDataAvailable(
std::bind( &DataSenderManagerWorkerThread::onDataReadyToPublish, mDataSenderManagerWorkerThread.get() ) );
#endif
/*************************DataSender bootstrap end*********************************/
/*************************CollectionScheme Ingestion bootstrap begin*********************************/
// CollectionScheme Ingestion module executes in the context for the offboardconnectivity thread. Upcoming
// messages are expected to come either on the decoder manifest topic or the collectionScheme topic or both
// ( eventually ).
mSchemaPtr = std::make_shared<Schema>( mReceiverDecoderManifest, mReceiverCollectionSchemeList, mMqttSender );
#ifdef FWE_FEATURE_LAST_KNOWN_STATE
if ( receiverLastKnownStateConfig != nullptr )
{
mLastKnownStateSchema = std::make_unique<LastKnownStateSchema>( receiverLastKnownStateConfig );
}
#endif
/*****************************CollectionScheme Management bootstrap begin*****************************/
// Allow CollectionSchemeManagement to send checkins through the Schema Object Callback
mCheckinSender = std::make_shared<CheckinSender>(
mSchemaPtr,
config["staticConfig"]["publishToCloudParameters"]["collectionSchemeManagementCheckinIntervalMs"]
.asU32Required() );
// Create and connect the CollectionScheme Manager
mCollectionSchemeManagerPtr = std::make_shared<CollectionSchemeManager>(
mPersistDecoderManifestCollectionSchemesAndData,
mCANIDTranslator,
mCheckinSender,
mRawBufferManager
#ifdef FWE_FEATURE_REMOTE_COMMANDS
,
[this]() -> std::unordered_map<InterfaceID, std::vector<std::string>> {
return mActuatorCommandManager->getActuatorNames();
}
#endif
);
// Make sure the CollectionScheme Ingestion can notify the CollectionScheme Manager about the arrival
// of new artifacts over the offboardconnectivity receiver.
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mSchemaPtr->subscribeToCollectionSchemeUpdate( std::bind( &CollectionSchemeManager::onCollectionSchemeUpdate,
mCollectionSchemeManagerPtr.get(),
std::placeholders::_1 ) );
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mSchemaPtr->subscribeToDecoderManifestUpdate( std::bind( &CollectionSchemeManager::onDecoderManifestUpdate,
mCollectionSchemeManagerPtr.get(),
std::placeholders::_1 ) );
#ifdef FWE_FEATURE_LAST_KNOWN_STATE
if ( mLastKnownStateSchema != nullptr )
{
mLastKnownStateSchema->subscribeToLastKnownStateReceived(
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
std::bind( &CollectionSchemeManager::onStateTemplatesChanged,
mCollectionSchemeManagerPtr.get(),
std::placeholders::_1 ) );
}
#endif
// Make sure the CollectionScheme Manager can notify the Inspection Engine about the availability of
// a new set of collection CollectionSchemes.
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionSchemeManagerPtr->subscribeToInspectionMatrixChange(
std::bind( &CollectionInspectionWorkerThread::onChangeInspectionMatrix,
mCollectionInspectionWorkerThread.get(),
std::placeholders::_1 ) );
#ifdef FWE_FEATURE_VISION_SYSTEM_DATA
// Make sure the CollectionScheme Manager can notify the Data Sender about the availability of
// a new set of collection CollectionSchemes.
if ( visionSystemDataSender != nullptr )
{
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionSchemeManagerPtr->subscribeToCollectionSchemeListChange(
std::bind( &VisionSystemDataSender::onChangeCollectionSchemeList,
visionSystemDataSender.get(),
std::placeholders::_1 ) );
}
if ( ionWriter != nullptr )
{
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionSchemeManagerPtr->subscribeToActiveDecoderDictionaryChange(
std::bind( &DataSenderIonWriter::onChangeOfActiveDictionary,
ionWriter.get(),
std::placeholders::_1,
std::placeholders::_2 ) );
}
#endif
#ifdef FWE_FEATURE_STORE_AND_FORWARD
if ( mStoreAndForwardEnabled )
{
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionSchemeManagerPtr->subscribeToCollectionSchemeListChange(
std::bind( &Aws::IoTFleetWise::Store::StreamManager::onChangeCollectionSchemeList,
mStreamManager.get(),
std::placeholders::_1 ) );
}
#endif
/*************************DataFetchManager bootstrap begin*********************************/
mDataFetchManager = std::make_shared<DataFetchManager>();
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionInspectionEngine->subscribeToFetchConditionEvaluationUpdate(
std::bind( &DataFetchManager::onFetchRequest,
mDataFetchManager.get(),
std::placeholders::_1,
std::placeholders::_2 ) );
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionSchemeManagerPtr->subscribeToFetchMatrixChange(
std::bind( &DataFetchManager::onChangeFetchMatrix, mDataFetchManager.get(), std::placeholders::_1 ) );
/********************************Data source bootstrap start*******************************/
auto obdOverCANModuleInit = false;
mCANDataConsumer = std::make_unique<CANDataConsumer>( signalBufferDistributor );
for ( unsigned i = 0; i < config["networkInterfaces"].getArraySizeRequired(); i++ )
{
const auto networkInterfaceConfig = config["networkInterfaces"][i];
const auto interfaceType = networkInterfaceConfig["type"].asStringRequired();
const auto interfaceId = networkInterfaceConfig["interfaceId"].asStringRequired();
if ( interfaceType == CAN_INTERFACE_TYPE )
{
CanTimestampType canTimestampType = CanTimestampType::KERNEL_SOFTWARE_TIMESTAMP; // default
auto canConfig = networkInterfaceConfig[CAN_INTERFACE_TYPE];
if ( canConfig.isMember( "timestampType" ) )
{
auto timestampTypeInput = canConfig["timestampType"].asStringRequired();
bool success = stringToCanTimestampType( timestampTypeInput, canTimestampType );
if ( !success )
{
FWE_LOG_WARN( "Invalid can timestamp type provided: " + timestampTypeInput +
" so default to Software" );
}
}
auto canChannelId = mCANIDTranslator.getChannelNumericID( interfaceId );
auto canSourcePtr = std::make_unique<CANDataSource>(
canChannelId,
canTimestampType,
canConfig["interfaceName"].asStringRequired(),
canConfig["protocolName"].asStringRequired() == "CAN-FD",
config["staticConfig"]["threadIdleTimes"]["socketCANThreadIdleTimeMs"].asU32Required(),
*mCANDataConsumer );
if ( !canSourcePtr->init() )
{
FWE_LOG_ERROR( "Failed to initialize CANDataSource" );
return false;
}
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionSchemeManagerPtr->subscribeToActiveDecoderDictionaryChange(
std::bind( &CANDataSource::onChangeOfActiveDictionary,
canSourcePtr.get(),
std::placeholders::_1,
std::placeholders::_2 ) );
mCANDataSources.push_back( std::move( canSourcePtr ) );
}
else if ( interfaceType == OBD_INTERFACE_TYPE )
{
if ( !obdOverCANModuleInit )
{
auto obdOverCANModule = std::make_shared<OBDOverCANModule>();
obdOverCANModuleInit = true;
auto obdConfig = networkInterfaceConfig[OBD_INTERFACE_TYPE];
if ( obdOverCANModule->init(
signalBufferDistributor,
obdConfig["interfaceName"].asStringRequired(),
obdConfig["pidRequestIntervalSeconds"].asU32Required(),
obdConfig["dtcRequestIntervalSeconds"].asU32Required(),
// Broadcast mode is enabled by default if not defined in config:
obdConfig["broadcastRequests"].asBoolOptional().get_value_or( true ) ) )
{
// Connect the OBD Module
mOBDOverCANModule = obdOverCANModule;
if ( !mOBDOverCANModule->connect() )
{
FWE_LOG_ERROR( "Failed to connect OBD over CAN module" );
return false;
}
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionSchemeManagerPtr->subscribeToActiveDecoderDictionaryChange(
std::bind( &OBDOverCANModule::onChangeOfActiveDictionary,
mOBDOverCANModule.get(),
std::placeholders::_1,
std::placeholders::_2 ) );
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionSchemeManagerPtr->subscribeToInspectionMatrixChange(
std::bind( &OBDOverCANModule::onChangeInspectionMatrix,
mOBDOverCANModule.get(),
std::placeholders::_1 ) );
}
}
else
{
FWE_LOG_ERROR( "obdOverCANModule already initialised" );
}
}
else if ( interfaceType == EXTERNAL_CAN_INTERFACE_TYPE )
{
if ( mExternalCANDataSource != nullptr )
{
continue;
}
mExternalCANDataSource = std::make_unique<ExternalCANDataSource>( *mCANDataConsumer );
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionSchemeManagerPtr->subscribeToActiveDecoderDictionaryChange(
std::bind( &ExternalCANDataSource::onChangeOfActiveDictionary,
mExternalCANDataSource.get(),
std::placeholders::_1,
std::placeholders::_2 ) );
}
else if ( interfaceType == NAMED_SIGNAL_INTERFACE_TYPE )
{
if ( mNamedSignalDataSource != nullptr )
{
continue;
}
mNamedSignalDataSource =
std::make_shared<NamedSignalDataSource>( interfaceId, signalBufferDistributor );
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionSchemeManagerPtr->subscribeToActiveDecoderDictionaryChange(
std::bind( &NamedSignalDataSource::onChangeOfActiveDictionary,
mNamedSignalDataSource.get(),
std::placeholders::_1,
std::placeholders::_2 ) );
}
#ifdef FWE_FEATURE_SOMEIP
else if ( interfaceType == SOMEIP_COLLECTION_INTERFACE_TYPE )
{
if ( mSomeipDataSource != nullptr )
{
continue;
}
// coverity[autosar_cpp14_a20_8_4_violation] Shared pointer interface required for unit testing
auto namedSignalDataSource =
std::make_shared<NamedSignalDataSource>( interfaceId, signalBufferDistributor );
// coverity[autosar_cpp14_a18_9_1_violation] std::bind is easier to maintain than extra lambda
mCollectionSchemeManagerPtr->subscribeToActiveDecoderDictionaryChange(
std::bind( &NamedSignalDataSource::onChangeOfActiveDictionary,
namedSignalDataSource.get(),
std::placeholders::_1,
std::placeholders::_2 ) );