forked from Autodesk/AutodeskMachineControlFramework
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlibmc_mccontext.cpp
More file actions
1249 lines (916 loc) · 48.8 KB
/
libmc_mccontext.cpp
File metadata and controls
1249 lines (916 loc) · 48.8 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
/*++
Copyright (C) 2020 Autodesk Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Autodesk Inc. nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AUTODESK INC. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "libmc_mccontext.hpp"
#include "libmc_interfaceexception.hpp"
#include "libmc_apirequesthandler.hpp"
#include "libmc_streamconnection.hpp"
#include "pugixml.hpp"
#include "amc_statemachineinstance.hpp"
#include "amc_logger.hpp"
#include "amc_alerthandler.hpp"
#include "amc_telemetry.hpp"
#include "amc_parameterhandler.hpp"
#include "amc_statemachinedata.hpp"
#include "amc_logger_multi.hpp"
#include "amc_logger_callback.hpp"
#include "amc_logger_database.hpp"
#include "amc_ui_handler.hpp"
#include "amc_resourcepackage.hpp"
#include "amc_accesscontrol.hpp"
#include "amc_statesignalhandler.hpp"
#include "amc_api_factory.hpp"
#include "amc_api_sessionhandler.hpp"
#include "common_importstream_native.hpp"
#include "libmc_exceptiontypes.hpp"
// Include custom headers here.
#include <iostream>
#define MACHINEDEFINITION_XMLSCHEMA "http://schemas.autodesk.com/amc/machinedefinitions/2020/02"
#define MACHINEDEFINITIONTEST_XMLSCHEMA "http://schemas.autodesk.com/amc/testdefinitions/2020/02"
#define LIBMC_SYSTEMTHREAD_INTERVAL_MILLISECONDS 10
using namespace LibMC::Impl;
using namespace AMC;
/*************************************************************************************************************************
Class definition of CMCContext
**************************************************************************************************************************/
CMCContext::CMCContext(LibMCData::PDataModel pDataModel)
: m_bIsTestingEnvironment (false)
{
LibMCAssertNotNull(pDataModel.get());
bool bEnableJournalLogging = false;
// Create Chrono Object
auto pGlobalChrono = std::make_shared<AMCCommon::CChrono>();
m_pEnvironmentWrapper = LibMCEnv::CWrapper::loadLibraryFromSymbolLookupMethod((void*) LibMCEnv::Impl::LibMCEnv_GetProcAddress);
// Create Log Multiplexer to StdOut and Database
auto pMultiLogger = std::make_shared<AMC::CLogger_Multi>(pGlobalChrono);
pMultiLogger->addLogger(std::make_shared<AMC::CLogger_Database> (pDataModel, pGlobalChrono));
if (pDataModel->HasLogCallback())
pMultiLogger->addLogger(std::make_shared<AMC::CLogger_Callback>(pDataModel, pGlobalChrono));
// Create State Journal
m_pStateJournal = std::make_shared<CStateJournal>(std::make_shared<CStateJournalStream>(pDataModel->CreateJournalSession(), pMultiLogger, bEnableJournalLogging), pGlobalChrono);
// Create system state
m_pSystemState = std::make_shared <CSystemState> (pMultiLogger, pDataModel, m_pEnvironmentWrapper, m_pStateJournal, "./testoutput", pGlobalChrono);
// Create API Handlers for data model requests
m_pAPI = std::make_shared<AMC::CAPI>();
CAPIFactory factory (m_pAPI, m_pSystemState, m_InstanceList);
// Create API Documentation handler
m_pAPIDocumentationHandler = std::make_shared <CAPIHandler_APIDocs>(m_pSystemState->getClientHash());
m_pAPI->registerHandler(m_pAPIDocumentationHandler);
// Create Client Dist Handler
m_pClientDistHandler = std::make_shared <CAPIHandler_Root>(m_pSystemState->getClientHash ());
m_pAPI->registerHandler(m_pClientDistHandler);
// Proper threadsafe reading out of Base Temp directory (even if it might not matter at startup).
auto pInstallationInformation = pDataModel->GetInstallationInformationObject();
std::string sTempPath = pInstallationInformation->GetBaseTempDirectory();
if (sTempPath.empty()) {
// Set Temporary Path (as default value)
#ifdef _WIN32
std::vector<wchar_t> TempPathBuffer;
TempPathBuffer.resize(MAX_PATH + 1);
auto nSize = GetTempPathW(MAX_PATH, TempPathBuffer.data());
if (nSize == 0)
throw ELibMCNoContextException(LIBMC_ERROR_COULDNOTGETTEMPPATHFROMWINDOWS);
TempPathBuffer[MAX_PATH] = 0;
sTempPath = AMCCommon::CUtils::UTF16toUTF8(TempPathBuffer.data());
m_pSystemState->driverHandler()->setTempBasePath(sTempPath);
#else
sTempPath = "/tmp";
#endif
}
m_pSystemState->driverHandler()->setTempBasePath(sTempPath);
}
CMCContext::~CMCContext()
{
m_Instances.clear();
m_InstanceList.clear();
m_Plugins.clear();
}
void CMCContext::ParseConfiguration(const std::string & sXMLString)
{
try {
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_string(sXMLString.c_str());
if (!result)
throw ELibMCNoContextException(LIBMC_ERROR_COULDNOTPARSECONFIGURATION);
pugi::xml_node mainNode;
auto machinedefinitionNode = doc.child("machinedefinition");
auto testdefinitionNode = doc.child("testdefinition");
if (!machinedefinitionNode.empty()) {
mainNode = machinedefinitionNode;
m_bIsTestingEnvironment = false;
}
if (!testdefinitionNode.empty()) {
if (!mainNode.empty ())
throw ELibMCNoContextException(LIBMC_ERROR_AMBIGIOUSMAINNODE);
mainNode = testdefinitionNode;
m_bIsTestingEnvironment = true;
}
if (mainNode.empty()) {
throw ELibMCNoContextException(LIBMC_ERROR_MISSINGMAINNODE);
}
auto xmlnsAttrib = mainNode.attribute("xmlns");
if (xmlnsAttrib.empty())
throw ELibMCNoContextException(LIBMC_ERROR_MISSINGXMLSCHEMA);
std::string xmlns(xmlnsAttrib.as_string());
if (m_bIsTestingEnvironment) {
if (xmlns != MACHINEDEFINITIONTEST_XMLSCHEMA)
throw ELibMCCustomException(LIBMC_ERROR_INVALIDXMLSCHEMA, xmlns);
}
else {
if (xmlns != MACHINEDEFINITION_XMLSCHEMA)
throw ELibMCCustomException(LIBMC_ERROR_INVALIDXMLSCHEMA, xmlns);
}
m_pSystemState->logger()->logMessage("Reading access control information", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
auto accessControlNode = mainNode.child("accesscontrol");
if (!accessControlNode.empty()) {
loadAccessControl(accessControlNode);
}
else {
// Fall back is a single role with no specific permissions
m_pSystemState->accessControl()->setToNoAccessControl ();
}
m_pSystemState->logger()->logMessage("Reading alert information", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
auto alertsNode = mainNode.child("alerts");
if (!alertsNode.empty()) {
loadAlertDefinitions(alertsNode);
}
auto sCoreResourcePath = m_pSystemState->getLibraryResourcePath("core");
m_pSystemState->logger()->logMessage("Loading core resources from " + sCoreResourcePath + "...", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
auto pResourcePackageStream = std::make_shared<AMCCommon::CImportStream_Native>(sCoreResourcePath);
m_pCoreResourcePackage = CResourcePackage::makeFromStream(pResourcePackageStream, sCoreResourcePath, AMCPACKAGE_SCHEMANAMESPACE);
m_pSystemState->logger()->logMessage("Loading drivers...", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
auto driversNodes = mainNode.children("driver");
for (pugi::xml_node driversNode : driversNodes)
{
addDriver(driversNode);
}
auto apiNode = mainNode.child("api");
bool bHasDocumentationResource = false;
if (!apiNode.empty()) {
auto documentationResourceAttrib = apiNode.attribute("documentationresource");
std::string sDocumentationResource = documentationResourceAttrib.as_string();
if (!sDocumentationResource.empty()) {
m_pSystemState->logger()->logMessage("Loading documentation resource: " + sDocumentationResource, LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
std::string sAPIDocumentationJSON = m_pCoreResourcePackage->readEntryUTF8String(sDocumentationResource);
m_pAPIDocumentationHandler->setCustomDocumentationJSON(sAPIDocumentationJSON);
bHasDocumentationResource = true;
}
}
if (!bHasDocumentationResource)
m_pSystemState->logger()->logMessage("No custom API definition given.", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
m_pSystemState->logger()->logMessage("Initializing state machines...", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
auto statemachinesNodes = mainNode.children("statemachine");
for (pugi::xml_node instanceNode : statemachinesNodes)
{
addMachineInstance(instanceNode);
}
m_pSystemState->logger()->logMessage("Starting Journal recording...", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
// Start journal recording
m_pStateJournal->startRecording();
// Load persistent parameters
auto pDataModel = m_pSystemState->getDataModelInstance();
auto pPersistencyHandler = pDataModel->CreatePersistencyHandler();
for (auto pStateMachineInstance : m_InstanceList)
pStateMachineInstance->getParameterHandler()->loadPersistentParameters(pPersistencyHandler, m_pSystemState->getAbsoluteTimeStamp ());
// Load User Interface
auto userInterfaceNode = mainNode.child("userinterface");
if (userInterfaceNode.empty()) {
if (!m_bIsTestingEnvironment)
throw ELibMCNoContextException(LIBMC_ERROR_NOUSERINTERFACEDEFINITION);
m_pSystemState->logger()->logMessage("Using default testing UI Handler...", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
m_pSystemState->uiHandler()->setCoreResourcePackage(m_pCoreResourcePackage);
}
else {
// Load user interface
auto uiLibraryAttrib = userInterfaceNode.attribute("library");
if (uiLibraryAttrib.empty())
throw ELibMCNoContextException(LIBMC_ERROR_NOUSERINTERFACEPLUGIN);
auto sUILibraryPath = m_pSystemState->getLibraryPath(uiLibraryAttrib.as_string());
m_pSystemState->logger()->logMessage("Loading UI Handler...", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
m_pSystemState->uiHandler()->setCoreResourcePackage(m_pCoreResourcePackage);
m_pSystemState->uiHandler()->loadFromXML(userInterfaceNode, sUILibraryPath);
}
}
catch (std::exception& E) {
m_pSystemState->logger()->logMessage(std::string ("initialization error: ") + E.what(), LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::CriticalError);
throw E;
}
}
void CMCContext::SetParameterOverride(const std::string& sParameterPath, const std::string& sParameterValue)
{
auto pStateMachineData = m_pSystemState->stateMachineData();
std::string sParameterInstance;
std::string sParameterGroup;
std::string sParameterName;
pStateMachineData->extractParameterDetailsFromDotString(sParameterPath, sParameterInstance, sParameterGroup, sParameterName, false, false);
auto pParameterInstanceHandler = pStateMachineData->getParameterHandler(sParameterInstance);
auto pParameterGroup = pParameterInstanceHandler->findGroup(sParameterGroup, true);
auto eDataType = pParameterGroup->getParameterDataTypeByName(sParameterName);
switch (eDataType) {
case AMC::eParameterDataType::String:
case AMC::eParameterDataType::UUID:
pParameterGroup->setParameterValueByName(sParameterName, sParameterValue);
break;
case AMC::eParameterDataType::Integer:
pParameterGroup->setIntParameterValueByName(sParameterName, AMCCommon::CUtils::stringToInteger(sParameterValue));
break;
case AMC::eParameterDataType::Double:
pParameterGroup->setDoubleParameterValueByName(sParameterName, AMCCommon::CUtils::stringToDouble(sParameterValue));
break;
case AMC::eParameterDataType::Bool:
pParameterGroup->setBoolParameterValueByName(sParameterName, AMCCommon::CUtils::stringToBool(sParameterValue));
break;
default:
throw ELibMCCustomException(LIBMC_ERROR_INVALIDVARIABLETYPE, sParameterPath);
}
}
void CMCContext::RegisterLibraryPath(const std::string& sLibraryName, const std::string& sLibraryPath, const std::string& sLibraryResource)
{
m_pSystemState->logger()->logMessage("mapping " + sLibraryName + " to " + sLibraryPath + "...", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
m_pSystemState->addLibraryPath(sLibraryName, sLibraryPath, sLibraryResource);
}
void CMCContext::SetTempBasePath(const std::string& sTempBasePath)
{
if (sTempBasePath.empty())
throw ELibMCNoContextException(LIBMC_ERROR_TEMPBASEPATHEMPTY);
m_pSystemState->driverHandler()->setTempBasePath(sTempBasePath);
}
void CMCContext::LoadClientPackage(const std::string& sResourcePath)
{
auto pStream = std::make_shared<AMCCommon::CImportStream_Native>(sResourcePath);
auto pPackage = CResourcePackage::makeFromStream(pStream, sResourcePath, AMCPACKAGE_SCHEMANAMESPACE);
m_pClientDistHandler->LoadClientPackage (pPackage);
}
void CMCContext::LoadAPIDocumentation(const std::string& sResourcePath)
{
auto pStream = std::make_shared<AMCCommon::CImportStream_Native>(sResourcePath);
auto pPackage = CResourcePackage::makeFromStream(pStream, sResourcePath, AMCPACKAGE_SCHEMANAMESPACE);
m_pAPIDocumentationHandler->LoadAPIDocsPackage(pPackage);
}
struct xml_sstream_writer : pugi::xml_writer
{
std::stringstream resultStream;
virtual void write(const void* data, size_t size)
{
resultStream << std::string (static_cast<const char*>(data), size);
}
};
void CMCContext::addDriver(const pugi::xml_node& xmlNode)
{
auto nameAttrib = xmlNode.attribute("name");
if (nameAttrib.empty())
throw ELibMCNoContextException(LIBMC_ERROR_MISSINGDRIVERNAME);
std::string sName(nameAttrib.as_string());
auto typeAttrib = xmlNode.attribute("type");
if (typeAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGDRIVERTYPE, sName);
std::string sType(typeAttrib.as_string());
auto libraryAttrib = xmlNode.attribute("library");
if (libraryAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGDRIVERLIBRARY, sName);
std::string sLibraryName(libraryAttrib.as_string());
m_pSystemState->logger()->logMessage("Initializing " + sName + " (" + sType + "@" + sLibraryName + ")", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
std::string sConfigurationData = "";
std::string sConfigSchema = xmlNode.attribute("configurationschema").as_string ();
std::string sConfigResource = xmlNode.attribute("configurationresource").as_string ();
if ((!sConfigResource.empty()) && (!sConfigSchema.empty()))
throw ELibMCCustomException(LIBMC_ERROR_AMBIGUOUSDRIVERCONFIGURATION, sName);
// If configuration schema is given, then the driver configuration is inlined in the config XML.
if (!sConfigSchema.empty()) {
pugi::xml_document config_document;
xml_sstream_writer config_writer;
// Copy driver node content into driver configuration XML.
auto driverNode = config_document.append_child("driverconfiguration");
driverNode.append_attribute("xmlns").set_value(sConfigSchema.c_str());
for (auto subNode : xmlNode.children()) {
driverNode.prepend_copy(subNode);
}
config_document.save(config_writer);
sConfigurationData = config_writer.resultStream.str();
}
if (!sConfigResource.empty()) {
sConfigurationData = m_pCoreResourcePackage->readEntryUTF8String(sConfigResource);
}
try {
m_pSystemState->driverHandler()->registerDriver(sName, sType, sLibraryName, m_pSystemState->getLibraryPath(sLibraryName), m_pSystemState->getLibraryResourcePath(sLibraryName), sConfigurationData, m_pCoreResourcePackage);
m_pSystemState->addDriverVersionInfo(sName);
}
catch (std::exception & E) {
m_pSystemState->logger()->logMessage(std::string ("Driver error: ") + E.what(), LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::FatalError);
}
}
AMC::PStateMachineInstance CMCContext::addMachineInstance(const pugi::xml_node& xmlNode)
{
auto nameAttrib = xmlNode.attribute("name");
if (nameAttrib.empty())
throw ELibMCNoContextException(LIBMC_ERROR_MISSINGINSTANCENAME);
std::string sName (nameAttrib.as_string());
auto descriptionAttrib = xmlNode.attribute("description");
if (descriptionAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGINSTANCEDESCRIPTION, sName);
std::string sDescription(descriptionAttrib.as_string());
auto initstateAttrib = xmlNode.attribute("initstate");
if (initstateAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGINITSTATE, sName);
std::string sInitState(initstateAttrib.as_string());
if (sInitState.length() == 0)
throw ELibMCCustomException(LIBMC_ERROR_EMPTYINITSTATE, sName);
auto failedstateAttrib = xmlNode.attribute("failedstate");
if (failedstateAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGFAILEDSTATE, sName);
std::string sFailedState(failedstateAttrib.as_string());
if (sFailedState.length() == 0)
throw ELibMCCustomException(LIBMC_ERROR_EMPTYFAILEDSTATE, sName);
auto successstateAttrib = xmlNode.attribute("successstate");
std::string sSuccessState = successstateAttrib.as_string ();
auto libraryAttrib = xmlNode.attribute("library");
if (libraryAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPLUGINNAME, sName);
std::string slibraryName (libraryAttrib.as_string());
if (slibraryName.length() == 0)
throw ELibMCCustomException(LIBMC_ERROR_EMPTYPLUGINNAME, sName);
auto pInstance = findMachineInstance(sName, false);
if (pInstance.get() != nullptr)
throw ELibMCCustomException(LIBMC_ERROR_DUPLICATESTATENAME, sName);
if (!AMCCommon::CUtils::stringIsValidAlphanumericNameString(sName))
throw ELibMCCustomException(LIBMC_ERROR_INVALIDSTATEMACHINENAME, sName);
m_pSystemState->logger()->logMessage("Creating state machine \"" + sName + "\"", LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
pInstance = std::make_shared<CStateMachineInstance> (sName, sDescription, m_pEnvironmentWrapper, m_pSystemState, m_pStateJournal);
auto pSystemParameterHandler = m_pSystemState->stateMachineData()->getParameterHandler("system");
auto pSignalInformationGroup = pSystemParameterHandler->addGroup("signals_" + sName, sName + " Signals");
auto pStateSignalHandler = m_pSystemState->stateSignalHandler();
auto pStateSignalInstance = pStateSignalHandler->registerInstance(sName);
auto signalNodes = xmlNode.children("signaldefinition");
for (pugi::xml_node signalNode : signalNodes) {
auto signalNameAttrib = signalNode.attribute("name");
if (signalNameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGSIGNALNAME, "statemachine " + sName);
std::vector<CStateSignalParameter> SignalParameters;
std::vector<CStateSignalParameter> SignalResults;
uint32_t nSignalReactionTimeOut = 0;
uint32_t nAutomaticArchiveTimeInMS = 0;
uint32_t nSignalQueueSize = 0;
std::string sSignalName = signalNameAttrib.as_string();
readSignalParameters(sSignalName, signalNode, SignalParameters, SignalResults, nSignalReactionTimeOut, nAutomaticArchiveTimeInMS, nSignalQueueSize);
pStateSignalInstance->addSignalDefinition(sSignalName, SignalParameters, SignalResults, nSignalReactionTimeOut, nAutomaticArchiveTimeInMS, nSignalQueueSize, pSignalInformationGroup);
}
auto pParameterHandler = pInstance->getParameterHandler();
// Load all value parameters
auto parameterGroupNodes = xmlNode.children("parametergroup");
for (pugi::xml_node parameterGroupNode : parameterGroupNodes) {
auto groupNameAttrib = parameterGroupNode.attribute("name");
if (groupNameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERGROUPNAME, "statemachine " + sName);
auto groupDescriptionAttrib = parameterGroupNode.attribute("description");
if (groupDescriptionAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERGROUPDESCRIPTION, groupNameAttrib.as_string ());
auto pGroup = pParameterHandler->addGroup(groupNameAttrib.as_string(), groupDescriptionAttrib.as_string());
pGroup->setJournal(m_pStateJournal, sName);
loadParameterGroup(parameterGroupNode, pGroup);
}
// Load all driver parameters
auto driverParameterGroupNodes = xmlNode.children("driverparametergroup");
for (pugi::xml_node driverParameterGroupNode : driverParameterGroupNodes) {
auto groupNameAttrib = driverParameterGroupNode.attribute("name");
if (groupNameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERGROUPNAME, "statemachine " + sName);
auto groupDescriptionAttrib = driverParameterGroupNode.attribute("description");
if (groupDescriptionAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERGROUPDESCRIPTION, groupNameAttrib.as_string ());
auto pGroup = pParameterHandler->addGroup(groupNameAttrib.as_string(), groupDescriptionAttrib.as_string());
pGroup->setJournal(m_pStateJournal, sName);
loadDriverParameterGroup(driverParameterGroupNode, pGroup);
}
// Load all derived parameters
for (pugi::xml_node parameterGroupNode : parameterGroupNodes) {
auto groupNameAttrib = parameterGroupNode.attribute("name");
if (groupNameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERGROUPNAME, "statemachine " + sName);
auto pGroup = pParameterHandler->findGroup(groupNameAttrib.as_string(), true);
loadParameterGroupDerives(parameterGroupNode, pGroup, sName);
}
auto statesNodes = xmlNode.children("state");
for (pugi::xml_node stateNode : statesNodes)
{
auto stateNameAttrib = stateNode.attribute("name");
if (stateNameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGSTATENAME, "statemachine " + sName);
uint32_t nRepeatDelay;
auto repeatDelayAttrib = stateNode.attribute("repeatdelay");
if (!repeatDelayAttrib.empty()) {
nRepeatDelay = repeatDelayAttrib.as_int();
}
else {
if (m_bIsTestingEnvironment) {
nRepeatDelay = AMC_DEFAULTREPEATDELAY_FOR_TESTING_MS;
}
else
{
throw ELibMCCustomException(LIBMC_ERROR_MISSINGREPEATDELAY, stateNameAttrib.as_string());
}
}
auto pState = pInstance->addState(stateNameAttrib.as_string(), nRepeatDelay);
}
// Load Out States
for (pugi::xml_node stateNode : statesNodes)
{
auto stateNameAttrib = stateNode.attribute("name");
if (stateNameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGSTATENAME, "statemachine " + sName);
auto pState = pInstance->findState(stateNameAttrib.as_string(), true);
auto outstateNodes = stateNode.children("outstate");
for (pugi::xml_node outstateNode : outstateNodes) {
auto targetAttrib = outstateNode.attribute("target");
if (targetAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGOUTSTATETARGET, pState->getName ());
auto pTargetState = pInstance->findState(targetAttrib.as_string (), false);
if (pTargetState.get() == nullptr)
throw ELibMCCustomException(LIBMC_ERROR_INVALIDOUTSTATETARGET, targetAttrib.as_string());
pState->addOutState(pTargetState);
}
}
// Load all telemetry channels for the state machine
auto pTelemetryHandler = m_pSystemState->getTelemetryHandlerInstance();
auto telemetryNode = xmlNode.child("telemetry");
if (!telemetryNode.empty()) {
auto telemetryNodes = telemetryNode.children("channel");
for (pugi::xml_node telemetryChannelNode : telemetryNodes) {
auto channelIdentifierAttrib = telemetryChannelNode.attribute("identifier");
auto channelDescriptionAttrib = telemetryChannelNode.attribute("description");
auto channelTypeAttrib = telemetryChannelNode.attribute("type");
std::string sChannelIdentifier = channelIdentifierAttrib.as_string();
std::string sChannelDescription = channelDescriptionAttrib.as_string();
std::string sChannelType = channelTypeAttrib.as_string();
if (sChannelIdentifier.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGTELEMETRYCHANNELIDENTIFIER, "state machine " + sName);
if (sChannelDescription.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGTELEMETRYCHANNELDESCRIPTION, "state machine " + sName);
if (!AMCCommon::CUtils::stringIsValidAlphanumericPathString(sChannelIdentifier))
throw ELibMCCustomException(LIBMC_ERROR_INVALIDTELEMETRYCHANNELIDENTIFIER, sChannelIdentifier + " (state machine " + sName + ")");
LibMCData::eTelemetryChannelType eChannelType = LibMCData::eTelemetryChannelType::CustomMarker;
if (!sChannelType.empty())
eChannelType = CTelemetryChannel::mapChannelTypeStringToDataChannelType(sChannelType);
std::string sGlobalChannelIdentifier = sName + "." + sChannelIdentifier;
pTelemetryHandler->registerChannel(sGlobalChannelIdentifier, sChannelDescription, eChannelType);
}
}
pInstance->setInitState(sInitState);
pInstance->setFailedState(sFailedState);
if (!sSuccessState.empty()) {
pInstance->setSuccessState(sSuccessState);
}
// load Plugin DLLs
auto pPlugin = loadPlugin (m_pSystemState->getLibraryPath (slibraryName));
LibMCPlugin::PStateFactory pStateFactory;
try {
pStateFactory = pPlugin->CreateStateFactory(sName);
}
catch (std::exception & E) {
throw new ELibMCInterfaceException (LIBMC_ERROR_COULDNOTCREATESTATEFACTORY, E.what());
}
pInstance->setStateFactory(pStateFactory);
if (m_InstanceList.size() >= MAXSTATEMACHINEINSTANCECOUNT)
throw ELibMCNoContextException(LIBMC_ERROR_TOOMANYMACHINEINSTANCES);
m_Instances.insert(std::make_pair(sName, pInstance));
m_InstanceList.push_back(pInstance);
return pInstance;
}
void CMCContext::readSignalParameters(const std::string& sSignalName, const pugi::xml_node& xmlNode, std::vector<AMC::CStateSignalParameter>& Parameters, std::vector<AMC::CStateSignalParameter>& Results, uint32_t & nSignalReactionTimeOut, uint32_t& nAutomaticArchiveTimeInMS, uint32_t& nSignalQueueSize)
{
auto reactionTimeOutAttrib = xmlNode.attribute("reactiontimeout");
if (!reactionTimeOutAttrib.empty()) {
nSignalReactionTimeOut = reactionTimeOutAttrib.as_uint();
if (nSignalReactionTimeOut < AMC_SIGNAL_MINREACTIONTIMEINMS)
throw ELibMCCustomException(LIBMC_ERROR_INVALIDSIGNALREACTIONTIMEOUT, sSignalName);
if (nSignalReactionTimeOut > AMC_SIGNAL_MAXREACTIONTIMEINMS)
throw ELibMCCustomException(LIBMC_ERROR_INVALIDSIGNALREACTIONTIMEOUT, sSignalName);
}
else {
nSignalReactionTimeOut = 3600000; // Default value is 1 hour
}
auto archiveTimeAttrib = xmlNode.attribute("archivetime");
if (!archiveTimeAttrib.empty()) {
nAutomaticArchiveTimeInMS = archiveTimeAttrib.as_uint();
if (nAutomaticArchiveTimeInMS < AMC_SIGNAL_MINARCHIVETIMEINMS)
throw ELibMCCustomException(LIBMC_ERROR_INVALIDSIGNALARCHIVETIMEOUT, sSignalName);
if (nAutomaticArchiveTimeInMS > AMC_SIGNAL_MAXARCHIVETIMEINMS)
throw ELibMCCustomException(LIBMC_ERROR_INVALIDSIGNALARCHIVETIMEOUT, sSignalName);
}
else {
nAutomaticArchiveTimeInMS = 3600000; // Default value is 1 hour
}
auto queueSizeAttrib = xmlNode.attribute("queuesize");
if (!queueSizeAttrib.empty()) {
nSignalQueueSize = queueSizeAttrib.as_uint();
if (nSignalQueueSize < AMC_SIGNAL_MINQUEUESIZE)
throw ELibMCCustomException(LIBMC_ERROR_INVALIDSIGNALQUEUESIZE, sSignalName);
if (nSignalQueueSize > AMC_SIGNAL_MAXQUEUESIZE)
throw ELibMCCustomException(LIBMC_ERROR_INVALIDSIGNALQUEUESIZE, sSignalName);
}
else {
nSignalQueueSize = 1; // Default value is 1
}
auto signalParameters = xmlNode.children("parameter");
for (pugi::xml_node signalParameter : signalParameters) {
auto parameterNameAttrib = signalParameter.attribute("name");
if (parameterNameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERNAME, sSignalName);
auto parameterTypeAttrib = signalParameter.attribute("type");
if (parameterTypeAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERTYPE, sSignalName + "/" + parameterNameAttrib.as_string ());
Parameters.push_back(CStateSignalParameter(parameterNameAttrib.as_string(), parameterTypeAttrib.as_string(), true));
}
auto optionalParameters = xmlNode.children("optionalparameter");
for (pugi::xml_node signalParameter : optionalParameters) {
auto parameterNameAttrib = signalParameter.attribute("name");
if (parameterNameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERNAME, sSignalName);
auto parameterTypeAttrib = signalParameter.attribute("type");
if (parameterTypeAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERTYPE, sSignalName + "/" + parameterNameAttrib.as_string());
Parameters.push_back(CStateSignalParameter(parameterNameAttrib.as_string(), parameterTypeAttrib.as_string(), false));
}
auto signalResults = xmlNode.children("result");
for (pugi::xml_node signalResult : signalResults) {
auto parameterNameAttrib = signalResult.attribute("name");
if (parameterNameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERNAME, sSignalName);
auto parameterTypeAttrib = signalResult.attribute("type");
if (parameterTypeAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERTYPE, sSignalName + "/" + parameterNameAttrib.as_string());
Results.push_back(CStateSignalParameter(parameterNameAttrib.as_string(), parameterTypeAttrib.as_string(), true));
}
auto optionalResults = xmlNode.children("optionalresult");
for (pugi::xml_node signalResult : optionalResults) {
auto parameterNameAttrib = signalResult.attribute("name");
if (parameterNameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERNAME, sSignalName);
auto parameterTypeAttrib = signalResult.attribute("type");
if (parameterTypeAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERTYPE, sSignalName + "/" + parameterNameAttrib.as_string());
Results.push_back(CStateSignalParameter(parameterNameAttrib.as_string(), parameterTypeAttrib.as_string(), false));
}
}
void CMCContext::loadDriverParameterGroup(const pugi::xml_node& xmlNode, AMC::PParameterGroup pGroup)
{
LibMCAssertNotNull (pGroup.get ())
auto driverNameAttrib = xmlNode.attribute("driver");
if (driverNameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGDRIVERNAME, pGroup->getName ());
auto driverGroup = m_pSystemState->driverHandler()->getDriverParameterGroup(driverNameAttrib.as_string ());
pGroup->addDerivativesFromGroup(driverGroup);
}
void CMCContext::loadAlertDefinitions(const pugi::xml_node& xmlNode)
{
auto alertHandler = m_pSystemState->alertHandler();
auto alertNodes = xmlNode.children("alert");
for (auto alertNode : alertNodes) {
std::string sIdentifier = alertNode.attribute("identifier").as_string();
std::string sLevel = alertNode.attribute("level").as_string();
std::string sAcknowledgePermission = alertNode.attribute("acknowledgepermission").as_string();
if (sIdentifier.empty())
throw ELibMCInterfaceException(LIBMC_ERROR_MISSINGALERTIDENTIFIER);
if (sLevel.empty())
throw ELibMCInterfaceException(LIBMC_ERROR_MISSINGALERTLEVEL);
bool bNeedsAcknowledgement = !sAcknowledgePermission.empty();
LibMCData::eAlertLevel alertLevel = CAlertDefinition::stringToAlertLevel(sLevel, true);
AMC::CLanguageString description(alertNode, "description");
auto pDefinition = alertHandler->addDefinition(sIdentifier, alertLevel, description, bNeedsAcknowledgement);
if (bNeedsAcknowledgement) {
auto accessControl = m_pSystemState->accessControl();
auto pNeededPermission = accessControl->findPermission(sAcknowledgePermission, true);
pDefinition->setAckPermissionIdentifier(pNeededPermission->getIdentifier());
}
}
}
void CMCContext::loadAccessControl(const pugi::xml_node& xmlNode)
{
auto accessControl = m_pSystemState->accessControl();
auto permissionsNode = xmlNode.child("permissions");
if (permissionsNode.empty ())
throw ELibMCInterfaceException(LIBMC_ERROR_MISSINGACCESSCONTROLPERMISSIONS);
auto permissionNodes = permissionsNode.children("permission");
for (pugi::xml_node permissionNode : permissionNodes) {
auto identifierAttrib = permissionNode.attribute("identifier");
CStringResource displaynameAttrib (&permissionNode, "displayname");
CStringResource descriptionAttrib(&permissionNode, "description");
accessControl->addPermission(identifierAttrib.as_string(), displaynameAttrib, descriptionAttrib);
}
auto rolesNode = xmlNode.child("roles");
if (rolesNode.empty())
throw ELibMCInterfaceException(LIBMC_ERROR_MISSINGACCESSCONTROLROLES);
auto defaultRoleAttrib = rolesNode.attribute("default");
if (defaultRoleAttrib.empty ())
throw ELibMCInterfaceException(LIBMC_ERROR_MISSINGDEFAULTACCESSROLE);
std::string sDefaultRole = defaultRoleAttrib.as_string();
if (sDefaultRole.empty ())
throw ELibMCInterfaceException(LIBMC_ERROR_MISSINGDEFAULTACCESSROLE);
auto roleNodes = rolesNode.children("role");
for (pugi::xml_node roleNode : roleNodes) {
auto identifierAttrib = roleNode.attribute("identifier");
CStringResource displaynameAttrib(&roleNode, "displayname");
CStringResource descriptionAttrib(&roleNode, "description");
auto pRole = accessControl->addRole(identifierAttrib.as_string(), displaynameAttrib, descriptionAttrib);
auto rolePermissionsNodes = roleNode.children("permission");
if (!rolePermissionsNodes.empty()) {
for (auto rolePermissionNode : rolePermissionsNodes) {
auto rolePermissionIdentifier = rolePermissionNode.attribute("identifier");
if (rolePermissionIdentifier.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGROLEPERMISSIONIDENTIFIER, pRole->getIdentifier());
auto pPermission = accessControl->findPermission(rolePermissionIdentifier.as_string(), true);
pRole->addPermission(pPermission);
}
}
}
accessControl->setDefaultRole(sDefaultRole);
}
void CMCContext::loadParameterGroup(const pugi::xml_node& xmlNode, AMC::PParameterGroup pGroup)
{
LibMCAssertNotNull(pGroup.get());
auto parameterNodes = xmlNode.children("parameter");
for (pugi::xml_node parameterNode : parameterNodes) {
auto nameAttrib = parameterNode.attribute("name");
if (nameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERNAME, pGroup->getName ());
auto descriptionAttrib = parameterNode.attribute("description");
if (descriptionAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERDESCRIPTION, pGroup->getName () + "/" + nameAttrib.as_string ());
auto defaultValueAttrib = parameterNode.attribute("default");
if (defaultValueAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERDEFAULTVALUE, pGroup->getName() + "/" + nameAttrib.as_string());
auto typeAttrib = parameterNode.attribute("type");
if (typeAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERTYPE, pGroup->getName() + "/" + nameAttrib.as_string());
auto unitsAttrib = parameterNode.attribute("units");
auto persistentAttrib = parameterNode.attribute("persistent");
std::string sName = nameAttrib.as_string();
std::string sPersistentUUID = persistentAttrib.as_string();
pGroup->addNewTypedParameter(sName, typeAttrib.as_string(), descriptionAttrib.as_string(), defaultValueAttrib.as_string(), unitsAttrib.as_string());
if (!sPersistentUUID.empty())
pGroup->setParameterPersistentUUID(sName, sPersistentUUID);
}
}
void CMCContext::loadParameterGroupDerives(const pugi::xml_node& xmlNode, AMC::PParameterGroup pGroup, const std::string& sStateMachineInstance)
{
LibMCAssertNotNull(pGroup.get ());
auto parameterNodes = xmlNode.children("derivedparameter");
for (pugi::xml_node parameterNode : parameterNodes) {
auto nameAttrib = parameterNode.attribute("name");
if (nameAttrib.empty())
throw ELibMCCustomException(LIBMC_ERROR_MISSINGPARAMETERNAME, pGroup->getName ());
AMC::PParameterHandler pParameterHandler;
auto sourceStateMachineAttrib = parameterNode.attribute("statemachine");
if (sourceStateMachineAttrib.empty()) {
pParameterHandler = m_pSystemState->stateMachineData()->getParameterHandler(sStateMachineInstance);
}
else {
pParameterHandler = m_pSystemState->stateMachineData()->getParameterHandler(sourceStateMachineAttrib.as_string());
}
std::string sSourceGroupName;
auto groupAttrib = parameterNode.attribute("group");
if (!groupAttrib.empty()) {
sSourceGroupName = groupAttrib.as_string();
}
else {
sSourceGroupName = pGroup->getName();
}
AMC::PParameterGroup pSourceGroup = pParameterHandler->findGroup (sSourceGroupName, true);
std::string sSourceParameterName;
auto sourceParameterAttrib = parameterNode.attribute("parameter");
if (!sourceParameterAttrib.empty()) {
sSourceParameterName = sourceParameterAttrib.as_string();
}
else {
sSourceParameterName = nameAttrib.as_string();
}
pGroup->addNewDerivedParameter (nameAttrib.as_string(), pSourceGroup, sSourceParameterName);
}
}
AMC::PStateMachineInstance CMCContext::findMachineInstance(std::string sName, bool bFailIfNotExisting)
{
auto iter = m_Instances.find(sName);
if (iter == m_Instances.end()) {
if (bFailIfNotExisting)
throw ELibMCCustomException(LIBMC_ERROR_MACHINEINSTANCENOTFOUND, sName);
return nullptr;
}
return iter->second;
}
LibMCPlugin::PWrapper CMCContext::loadPlugin(std::string sPluginName)
{
m_pSystemState->logger()->logMessage("loading plugin: " + sPluginName, LOG_SUBSYSTEM_SYSTEM, AMC::eLogLevel::Message);
auto iPluginIter = m_Plugins.find(sPluginName);
if (iPluginIter == m_Plugins.end()) {
LibMCPlugin::PWrapper pPlugin;
try {
pPlugin = LibMCPlugin::CWrapper::loadLibrary(sPluginName);
pPlugin->InjectComponent("LibMCEnv", (void*) LibMCEnv::Impl::LibMCEnv_GetProcAddress);
} catch (std::exception& E) {
throw ELibMCInterfaceException (LIBMC_ERROR_COULDNOTLOADPLUGIN, E.what ());
}
m_Plugins.insert(std::make_pair (sPluginName, pPlugin));
return pPlugin;
}
else {
return iPluginIter->second ;
}
}
void CMCContext::executeSystemThread()