CComBSTR BSTRFromUTF8(const std::string& utf8)
	{
		if (utf8.empty())
			return CComBSTR();

		// Fail if an invalid input character is encountered
		const DWORD conversionFlags = MB_ERR_INVALID_CHARS;

		const int utf16Length = ::MultiByteToWideChar(CP_UTF8, conversionFlags, utf8.data(), utf8.length(), NULL, 0);
		if (utf16Length == 0)
		{
			DWORD error = ::GetLastError();

			throw udm_exception(
				(error == ERROR_NO_UNICODE_TRANSLATION) ? 
					"Invalid UTF-8 sequence found in input string." :
					"Can't get length of UTF-16 string (MultiByteToWideChar failed).");
		}

		BSTR utf16 = SysAllocStringByteLen(NULL, utf16Length*2);
		if (utf16 == NULL)
			throw std::bad_alloc();

		if (!::MultiByteToWideChar(CP_UTF8, 0, utf8.data(), utf8.length(), utf16, utf16Length))
		{
			DWORD error = ::GetLastError();
			SysFreeString(utf16);
			throw udm_exception("Can't convert string from UTF-8 to UTF-16 (MultiByteToWideChar failed).");
		}

		CComBSTR ret;
		ret.m_str = utf16;
		return ret;
	}
CString ModelHandler::extractPortType(Udm::Object portObj)
{
	// whenever the connected port found is derived from DataPort then extract type from the enum attribute of the dstPort
	if(Udm::IsDerivedFrom(portObj.type(), SignalFlow::DataPort::meta))
	{
		return CString(((string) SignalFlow::DataPort::Cast(portObj).DataType()).c_str()).Trim();
	}
	// whenever the connected Port is derived from SF_Port then find the contained TypeRef Port to get the type
	else if(Udm::IsDerivedFrom(portObj.type(), Simulink::SF_Port::meta) ||
			Udm::IsDerivedFrom(portObj.type(), Simulink::SFStateDE::meta) ||
			Udm::IsDerivedFrom(portObj.type(), Simulink::StateDE::meta)
		)
	{
		// find type from the contained type ref
		set<Udm::Object> typerefSet = portObj.GetChildObjects(Simulink::TypeBaseRef::meta);
		// a port can have only a single type
		if(typerefSet.size() == 1)
		{
			Simulink::TypeBaseRef typeBaseRef = Simulink::TypeBaseRef::Cast(*(typerefSet.begin()));
			try
			{
				return CString(((string) Simulink::SF_Matrix::Cast(typeBaseRef.getReferencedObject()).Type()).c_str()).Trim();
			} catch(udm_exception e)
			{
				throw udm_exception(_T("Simulink::TypeBaseRef is currently allowed to refer to objects of only Simulink::SF_Matrix type! @[OBJECT:]") +
									MyUdmUtil::getHyperLinkPath_StdString(typeBaseRef));
			}
		}
		else if(typerefSet.size() > 1)
		{
			throw udm_exception(MyUdmUtil::getHyperLinkPath_StdString(portObj) + _T(" contains more than 1 Simulink::TypeBaseRef type objects. "));
		}
	}
	// the portObj is an InputSignalInterface of a ModelicaComponent
	else if(portObj.type().name() == "InputSignalInterface")
	{
		return CString(((string) InputSignalInterface::Cast(portObj).Class()).c_str()).Trim();
	}
	// the portObj is an OutputSignalInterface of a ModelicaComponent
	else if(portObj.type().name() == "OutputSignalInterface")
	{
		return CString(((string) OutputSignalInterface::Cast(portObj).Class()).c_str()).Trim();
	}
	// the portObj is a ParameterRef of a ModelicaComponent
	else if(portObj.type().name() == "ParameterRef")
	{
		return CString(((string) ParameterRef::Cast(portObj).Class()).c_str()).Trim();
	}

	return CString(_T(""));
}
	void Console::setupConsole(CComPtr<IMgaProject> project)
	{
		CComPtr<IMgaClient> client;	
		CComQIPtr<IDispatch> pDispatch;
		HRESULT s1 = project->GetClientByName(CComBSTR(L"GME.Application"),&client);

		if ((SUCCEEDED(s1)) && (client != 0))
		{
			HRESULT s2 = client->get_OLEServer(&pDispatch);
			if ((SUCCEEDED(s2)) && (pDispatch != 0))
			{
				// release here in case setupConsole was called twice
				gmeoleapp.Release();
				HRESULT s3 = pDispatch->QueryInterface(&gmeoleapp);
				if ((SUCCEEDED(s3)) && (gmeoleapp != 0))
				{
					// gmeoleapp->ConsoleClear();
					// gmeoleapp->put_ConsoleContents(NULL);
				}
				else
				{
					throw udm_exception("GME Console could not be accessed.");
				}
			}
		}
	}
void createCWCReference(CyPhyML::DesignContainer &container)
{
	if(container == cfgs_model.parent()) return;

	set<CyPhyML::CWCReference> cwcrefs = container.CWCReference_kind_children();
	for(set<CyPhyML::CWCReference>::iterator i=cwcrefs.begin();i!=cwcrefs.end();++i)
	{
		CyPhyML::Configurations cfgmodels = (*i).ref();
		if(cfgmodels == cfgs_model)
			return;
	}

	string tmp = container.name();
	if(!container.isInstance())
	{
		CyPhyML::CWCReference cwc_ref = CyPhyML::CWCReference::Create(container);
		cwc_ref.name() = "configurations ref";
		cwc_ref.ref() = cfgs_model;
	}
	else
	{
		cfg_model.DeleteObject();
		throw udm_exception((string)container.name()+" cannot be instance model.");
	}
}
void SFUtils::ZeroInit( SFC::Function function, SFC::ArgDeclBase argDeclBase ) {
	std::string argDeclBaseName = argDeclBase.name();

	getSFCSymbolTable().push( argDeclBaseName, argDeclBase );

	SFC::DT sdt = argDeclBase.dt();
	if(!sdt)
		throw udm_exception("SFC::DT is null");

	std::string zeroInitStatement = ZeroInit( argDeclBase.dt(), argDeclBaseName, "" );
	mstat2SFC( function, zeroInitStatement, true );

	getSFCSymbolTable().clear();
}
Exemple #6
0
 void Console::writeLine(const std::wstring& message, msgtype_enum type)
 {
     if (gmeoleapp == 0) {
         switch (type) {
         case MSG_NORMAL:
         case MSG_INFO:
         case MSG_WARNING:
             wprintf(L"%s", message.c_str());
             break;
         case MSG_ERROR:
             fwprintf(stderr, L"%s", message.c_str());
             break;
         }
     }
     else {
         if (S_OK != gmeoleapp->ConsoleMessage(CComBSTR((int)message.length(), message.c_str()), type))
             throw udm_exception("Could not write to GME console.");
     }
 }
std::string SFUtils::TopLevelTopologicalSort( const SLSF::Subsystem & subsystem ) {

	std::string loopReport("");
	CyberCycles cc( subsystem );

	cc.FindCycles();

	std::vector< std::vector< std::string > > cycleList;
	cc.CollectCycleList( cycleList );

	unsigned long loopNum = 0;
	// If we found any cycles
	if ( cycleList.size() > 0 )
	{
		std::string error( "Dataflow Graph '" + static_cast< std::string >( subsystem.Name() ) + "' has unhandled loops: " );
		
		for ( std::vector< std::vector< std::string > >::iterator loopIter = cycleList.begin(); loopIter != cycleList.end(); loopIter++ )
		{
			loopNum++;
			std::ostringstream oss;
			oss << std::endl << "Loop " << loopNum << ": ";

			for ( std::vector< std::string >::iterator nodeIter = (*loopIter).begin(); nodeIter != (*loopIter).end(); nodeIter++ )
			{
				oss << (*nodeIter) << " ";
			}

			error += oss.str();
		}

		loopReport = error;
		throw udm_exception( error );
	}

	return loopReport;

}
void SFUtils::DoTopologicalSort( SLSF::Subsystem subsystem ) {

    int vertexIndex = 0;
    VertexIndexBlockMap vertexIndexBlockMap;
    BlockVertexIndexMap blockVertexIndexMap;
    BlockVector blockVector = subsystem.Block_kind_children();
    for( BlockVector::iterator blvItr = blockVector.begin(); blvItr != blockVector.end(); ++blvItr, ++vertexIndex ) {
        SLSF::Block block = *blvItr;
        vertexIndexBlockMap[ vertexIndex ] = block;
        blockVertexIndexMap[ block ] = vertexIndex;

        std::string blockType = block.BlockType();
        if ( blockType == "UnitDelay" )	{  // check on other delay blocks as well ...
            ++vertexIndex;	               // UnitDelay is vertexed twice - one for outputs (timestep n-1), and one for inputs: vertexIndex is as destination, vertexIndex + 1 is as source
        }
    }

    Graph graph( vertexIndex );
    LineSet lineSet = subsystem.Line_kind_children();
    for( LineSet::iterator lnsItr = lineSet.begin(); lnsItr != lineSet.end() ; ++lnsItr ) {

        SLSF::Line line = *lnsItr;
        SLSF::Port sourcePort = line.srcLine_end();
        SLSF::Port destinationPort = line.dstLine_end();
        SLSF::Block sourceBlock = sourcePort.Block_parent();
        SLSF::Block destinationBlock = destinationPort.Block_parent();

        if ( sourceBlock == subsystem || destinationBlock == subsystem ) continue;

        int sourceBlockVertexIndex = blockVertexIndexMap[ sourceBlock ];
        if (  static_cast< std::string >( sourceBlock.BlockType() ) == "UnitDelay"  ) {
            ++sourceBlockVertexIndex;
        }

        int destinationBlockVertexIndex = blockVertexIndexMap[ destinationBlock ];

        boost::add_edge( sourceBlockVertexIndex, destinationBlockVertexIndex, graph );
    }

    LoopDetector loopDetector( graph );

    if ( loopDetector.check() ) {
        // TODO: add support for loops involving integrator and other stateful blocks

        // Determine what Blocks caused the loop
        typedef std::map< Vertex, int > VertexStrongComponentIndexMap;
        VertexStrongComponentIndexMap vertexStrongComponentIndexMap;
        boost::associative_property_map< VertexStrongComponentIndexMap > apmVertexStrongComponentIndexMap( vertexStrongComponentIndexMap );
        strong_components( graph, apmVertexStrongComponentIndexMap );

        typedef std::vector< Vertex > VertexVector;
        typedef std::map< int, VertexVector > StrongComponentIndexVertexGroupMap;
        StrongComponentIndexVertexGroupMap strongComponentIndexVertexGroupMap;
        for( VertexStrongComponentIndexMap::iterator vsmItr = vertexStrongComponentIndexMap.begin(); vsmItr != vertexStrongComponentIndexMap.end(); ++vsmItr ) {
            strongComponentIndexVertexGroupMap[ vsmItr->second ].push_back( vsmItr->first );
        }

        std::string error( "Dataflow Graph '" + static_cast< std::string >( subsystem.Name() ) + "' has unhandled loops: " );
        for( StrongComponentIndexVertexGroupMap::iterator svmItr = strongComponentIndexVertexGroupMap.begin(); svmItr != strongComponentIndexVertexGroupMap.end(); ++svmItr ) {
            VertexVector vertexVector = svmItr->second;
            if ( vertexVector.size() <= 1 ) continue;
            error.append( "\n" );
            for( VertexVector::iterator vtvItr = vertexVector.begin(); vtvItr != vertexVector.end(); ++vtvItr ) {
                error.append( blockVector[ *vtvItr ].getPath("/") );
                error.append( ", " );
            }
            error.erase( error.size() - 2 );
        }

        throw udm_exception(error);
    }

    typedef std::set< Vertex > VertexSet;
    typedef std::map< int, VertexSet > PriorityVertexSetMap;

    PriorityVertexSetMap priorityVertexSetMap;
    for( BlockVector::iterator blvItr = blockVector.begin() ; blvItr != blockVector.end() ; ++blvItr ) {

        SLSF::Block block = *blvItr;
        int priority = block.Priority();
        if ( priority == 0 ) continue;

        Vertex vertex = blockVertexIndexMap[ block ];
        priorityVertexSetMap[ priority ].insert( vertex );
    }

    if ( priorityVertexSetMap.size() > 1 ) {
        PriorityVertexSetMap::iterator lstPvmItr = priorityVertexSetMap.end();
        --lstPvmItr;
        for( PriorityVertexSetMap::iterator pvmItr = priorityVertexSetMap.begin() ; pvmItr != lstPvmItr ; ) {
            PriorityVertexSetMap::iterator nxtPvmItr = pvmItr;
            ++nxtPvmItr;

            VertexSet &higherPriorityVertexSet = pvmItr->second;
            VertexSet &lowerPriorityVertexSet = nxtPvmItr->second;

            for( VertexSet::iterator hvsItr = higherPriorityVertexSet.begin() ; hvsItr != higherPriorityVertexSet.end() ; ++hvsItr ) {
                for( VertexSet::iterator lvsItr = lowerPriorityVertexSet.begin() ; lvsItr != lowerPriorityVertexSet.end() ; ++lvsItr ) {
                    boost::add_edge( *hvsItr, *lvsItr, graph );
                    LoopDetector loopDetector( graph );
                    if (  loopDetector.check( *hvsItr )  ) {
                        SLSF::Block higherPriorityBlock = vertexIndexBlockMap[ *hvsItr ];
                        SLSF::Block lowerPriorityBlock = vertexIndexBlockMap[ *lvsItr ];

                        std::cerr << "WARNING:  Cannot implement priority difference between block \"" << higherPriorityBlock.getPath( "/" ) << "\" (Priority = " << *hvsItr << ") and " << std::endl;
                        std::cerr << "          block \"" << lowerPriorityBlock.getPath( "/" ) << "\" (Priority = " << *lvsItr << "): contradicts topology of subsystem or other implemented block priority order." << std::endl;
                        boost::remove_edge( *hvsItr, *lvsItr, graph );
                    }
                }
            }
            pvmItr = nxtPvmItr;
        }
    }

    VertexList vertexList;
    boost::topological_sort(  graph, std::back_inserter( vertexList )  );


    /* PUT ALL "DataStoreMemory" BLOCKS AT END OF "C" SO THEY HAVE HIGHEST PRIORITY */
    VertexList::reverse_iterator vtlRit = vertexList.rbegin();
    while( vtlRit != vertexList.rend() ) {
        int index = *vtlRit;
        SLSF::Block block = vertexIndexBlockMap[ index ];

        (void)++vtlRit;
        if ( block != Udm::null && static_cast< std::string >( block.BlockType() ) == "DataStoreMemory"  ) {
            VertexList::reverse_iterator vtlRit2 = vtlRit;
            vertexList.splice( vertexList.end(), vertexList, vtlRit2.base() );
        }
    }

    int priority = 0;
    for( VertexList::reverse_iterator vtlRit = vertexList.rbegin() ; vtlRit != vertexList.rend() ; ++vtlRit ) {
        int index = *vtlRit;
        SLSF::Block block = vertexIndexBlockMap[ index ];
        if ( block == Udm::null ) { // unit delay as source is not registered - we will invoke it initially, and invoke it as destination in the priority order
            // const std::string& bt = blk.BlockType();
            // assert(bt.compare("UnitDelay") == 0);
            /* Unit Delay Block as destination */
            continue;
        }
        block.Priority() = priority++;
    }
}
void traverseContainerForMorphMatrix(CyPhyML::DesignContainer &container, MorphMatrix& morphMatrix, set<CyPhyML::DesignEntity>& allEntities)
{
	set<CyPhyML::DesignEntity> entities = container.DesignEntity_kind_children();

	// First, populate the Morph Matrix
	set<CyPhyML::DesignEntity>* curEntities = 0;
	MorphMatrix::iterator pos;
	try {
		pos = morphMatrix.find(config);
	} catch (...) {
		// shouldn't normally occur
		pos = morphMatrix.end();
	}
	if(pos==morphMatrix.end()) {
		curEntities = new set<CyPhyML::DesignEntity>(); // FIXME: need to delete this
		morphMatrix.insert(MorphMatrix::value_type(config, curEntities));
	} else {
		curEntities = morphMatrix[config];
	}

	// Continue with configurations
	if((std::string)container.ContainerType()!="Compound")
	{
		map<int, int>::iterator pos = alternativeMap.find(container.ID());
		if(pos==alternativeMap.end())
			return;
		
		//get object by id
		int altId = (*pos).second;
		if(altId<=0) return;

		CyPhyML::DesignEntity selectedCom;
		for(set<CyPhyML::DesignEntity>::iterator i=entities.begin();i!=entities.end();++i)
		{
			if((*i).ID() == altId)
			{
				selectedCom = *i;
				break;
			}
		}
		if(selectedCom == Udm::null) 
		{
			char buffer[10];
			_itoa(altId, buffer, 10);
			std::string err = "Cannot find the Component with ID: "+(std::string)buffer+" in DesignContainer: "+(std::string)container.name();
			throw udm_exception(err.c_str());
		}

		addSelectedEntity(allEntities, curEntities, selectedCom, container);

		//if(Uml::IsDerivedFrom(selectedCom.type(), CyPhyML::DesignContainer::meta))
		if((std::string)selectedCom.type().name()=="DesignContainer")
		{
			traverseContainerForMorphMatrix(CyPhyML::DesignContainer::Cast(selectedCom), morphMatrix, allEntities);
		}
	}
	else 
	{
		for(set<CyPhyML::DesignEntity>::iterator i=entities.begin();i!=entities.end();++i)
		{
			const CyPhyML::DesignEntity &com = *i;
			addSelectedEntity(allEntities, curEntities, com, container);
			//if(Uml::IsDerivedFrom(com.type(), CyPhyML::DesignContainer::meta))
			if((std::string)com.type().name()=="DesignContainer")
			{
				traverseContainerForMorphMatrix(CyPhyML::DesignContainer::Cast(com), morphMatrix, allEntities);
			}
		}
	}
}
Exemple #10
0
 void Console::setContents(const std::wstring& contents)
 {
     if (gmeoleapp != 0)
         if (S_OK != gmeoleapp->put_ConsoleContents(CComBSTR((int)contents.length(), contents.c_str())))
             throw udm_exception("Could not set the contents of GME console.");
 }