void MatlabTemplateComponentImpl<Tin,Tout>::initialize()
{
  inBuf_ = castToType<T>(inputBuffers[0]);
  if(hasOutput_x || passThrough_x)
  {
    outBuf_ = castToType<T>(outputBuffers[0]);
  }

  //Open Matlab Engine
  if(!matlab_.open(""))
  {
    throw ResourceNotFoundException("Failed to start Matlab engine");
  }

  //Clear Matlab WorkSpace
  matlab_.evalString("clear all;");

  //Write the matlab command
  command_ = "matlab_output = ";
  command_ += scriptName_x;
  command_ += ";";

  //Setup an initial mxArray
  matlabInput_ = mxCreateDoubleMatrix(1, 10, mxREAL);
}
Esempio n. 2
0
boost::shared_ptr<ResourceInfo> Resource::LoadResource(const std::string& name)
{
    boost::shared_ptr<ResourceInfo> resource_info = m_resources.LoadResource(name);

    if (resource_info.get() == NULL)
    {
        const char* name_cstr = name.c_str();

        // Check if resource exists
        if (PHYSFS_exists(name_cstr) && !PHYSFS_isDirectory(name_cstr))
        {
            // Load the resource
            PHYSFS_File* fp = PHYSFS_openRead(name_cstr);

            // Load file data into ResourceInfo class
            Sint64 length = (Sint64)PHYSFS_fileLength(fp);
            char* data = new char[length];
            PHYSFS_read(fp, (void*)data, (PHYSFS_uint32)length, 1);
            resource_info = m_resources.Construct(name, data, length);

            // Close PHYSFS_File
            PHYSFS_close(fp);
            fp = NULL;
        }
        else
        {
            BOOST_THROW_EXCEPTION(ResourceNotFoundException()
                                  << StringErrorInfo("The requested resource could not be found: " + name));
        }
    }

    return resource_info;
}
Esempio n. 3
0
void Sprite::spriteIs(string fileName){
  spriteFileName = fileName;
  sprite = surfaceLoader->loadImage(spriteFileName);

  if (sprite == NULL){
    throw ResourceNotFoundException(fileName);
  }
}
    void StackComponentManager::addRepository(std::string repoPath)
    {
        while(!repoPath.empty())
        {
            //Extract paths from the repository string
            size_t pos = repoPath.find_first_of(';');
            string str(repoPath, 0, pos);
            repoPath.erase(0, pos);
            // break out of the while if str is empty (e.g. with a repos="/path/to/1;")
            if (str.empty())
                break;

            bfs::path currentPath(str);

            //Check that the path exists and is a directory
            if(!bfs::exists(currentPath) || !bfs::is_directory(currentPath))
            {
                LOG(LFATAL) << "Could not add repository " << str << " path does not exist or is not a directory.";
                throw ResourceNotFoundException("Could not add repository " + str + " path does not exist or is not a directory.");
            }

            //Create a repository object
            Repository tmp;
            tmp.path = currentPath;

            //Go through files in the repository and add to the repository vector of component libraries
            bfs::directory_iterator dir_iter(currentPath), dir_end;
            for(;dir_iter != dir_end; ++dir_iter)
            {
                //Check that the file path contains the system library extension
#if BOOST_FILESYSTEM_VERSION == 2
                string filename = dir_iter->path().leaf();
#else
                string filename = dir_iter->path().filename().string();
#endif
                size_t pos = filename.find_last_of('.');
                if(pos != string::npos)
                {
                    string extension = filename.substr(pos);
                    if(extension == SharedLibrary::getSystemExtension())
                    {
                        size_t pre = SharedLibrary::getSystemPrefix().length();
                        string stem = filename.substr(pre,pos-pre); //Remove library prefix and postfix
                        ComponentLibrary current;
                        current.path = dir_iter->path();
                        current.name = stem;
                        boost::to_lower(current.name);
                        tmp.componentLibs.push_back(current);
                    }
                }
            }

            //Add to vector of repository paths
            repositories_.push_back(tmp);
        }
    }
void FileWriterComponent::initialize()
{
  hOutFile_.open(fileName_x.c_str(), ios::out|ios::binary);
  if (hOutFile_.fail() || hOutFile_.bad() || !hOutFile_.is_open())
  {
    LOG(LFATAL) << "Could not open file " << fileName_x << " for writing.";
    throw ResourceNotFoundException("Could not open file " + fileName_x + " for writing.");
  }
  LOG(LDEBUG) << "FileWriterComponent:: initialize() [sic] completed successfully.";
}
//! Do any initialization required
void FileReaderComponent::initialize()
{
  hInFile_.open(fileName_x.c_str(), ios::in|ios::binary|ios::ate);
  if (hInFile_.fail() || hInFile_.bad() || !hInFile_.is_open())
  {
      LOG(LFATAL) << "Could not open file " << fileName_x << " for reading.";
      throw ResourceNotFoundException("Could not open file " + fileName_x + " for reading.");
  }
  hInFile_.seekg(0, ios::beg);
}
Esempio n. 7
0
    ProtoFrameInputStream::ProtoFrameInputStream(const char* path) :
        FrameInputStream()
    {
        m_file = fopen(path, "rb");

        if (m_file == nullptr)
        {
            throw ResourceNotFoundException(path);
        }

        m_fileDescriptor = get_file_descriptor(m_file);

        m_fileSize = get_file_size(m_fileDescriptor);

        m_inputStream = astra::make_unique<FileInputStream>(m_fileDescriptor);
    }
Esempio n. 8
0
    EngineInterface* EngineManager::createEngine(EngineDescription& d)
    {
        EngineInterface* current = NULL;

        if(d.type == "phyengine")
        {
            current = new PhyEngine(d.name, reps_.phyRepository);
        }
        else if(d.type == "stackengine")
        {
            current = new StackEngine(d.name, reps_.stackRepository); 
        }
        else
        {
            throw ResourceNotFoundException("Engine type \"" + d.type + "\" does not exist.");
        }

        // Give the engine an interface to this EngineManager
        current->setEngineManager(this);
        return current;
    }
    void ControllerManager::loadController(ControllerDescription desc)
    {
        ControllerLibrary temp;

        //Check if the library has already been loaded
        vector< ControllerLibrary >::iterator libIt;
        for(libIt=loadedLibraries_.begin();libIt!=loadedLibraries_.end();++libIt)
        {
            if(libIt->name == desc.type)
                temp = *(libIt);
        }

        //If the library hasn't already been loaded, look for it in our repositories
        if(temp.name == "")
        {
          vector< ControllerRepository >::iterator repIt;
          for(repIt=repositories_.begin();repIt!=repositories_.end();++repIt)
          {
              vector< ControllerLibrary >::iterator compIt;
              for(compIt=repIt->controllerLibs.begin();compIt!=repIt->controllerLibs.end();++compIt)
              {
                  if(compIt->name == desc.type)
                  {
                    if(temp.name == "")
                    {   //First component found which matches
                        temp = *compIt;
                    }
                    else if(bfs::last_write_time(compIt->path) > bfs::last_write_time(temp.path))
                    {   //Found more than one component which matches - choose the more recent one
                        temp = *compIt;
                    }
                  }
              }
          }
        }

        //Check that we found it
        if(temp.name == "")
        {
          LOG(LFATAL) << "Could not find controller " << desc.name << " in repositories.";
          throw ResourceNotFoundException("Could not find controller " + desc.type + " in repositories.");
        }

        //Load if necessary
        if(temp.libPtr == NULL)
        {
          temp.libPtr.reset(new SharedLibrary(temp.path));
          loadedLibraries_.push_back(temp);
        }

        //Pull a Controller class out of the library
        CREATECONTROLLERFUNCTION createFunction = (CREATECONTROLLERFUNCTION)temp.libPtr->getSymbol("CreateController");
        DESTROYCONTROLLERFUNCTION destroyFunction = (DESTROYCONTROLLERFUNCTION)temp.libPtr->getSymbol("ReleaseController");
        GETAPIVERSIONFUNCTION getApiFunction = (GETAPIVERSIONFUNCTION)temp.libPtr->getSymbol("GetApiVersion");

        //Check API version numbers match
        string coreVer, moduleVer;
        coreVer = Version::getApiVersion();
        moduleVer = getApiFunction();
        if(coreVer != moduleVer)
        {
            stringstream message;
            message << "API version mismatch between core and controller " << desc.type << \
                ". Core API version = " << coreVer << ". Module API version = " << moduleVer << ".";
            throw ApiVersionException(message.str());
        }

        //Create a shared_ptr and use a custom deallocator so the component is destroyed from the library
        boost::shared_ptr<Controller> cont(createFunction(), destroyFunction);

        //Set the LoggingPolicy and EngineManagerControllerInterface
        cont->setLoggingPolicy(Logger::getPolicy());
        cont->setCallbackInterface(this);

        //Set the parameter values here
        vector<ParameterDescription>::iterator i = desc.parameters.begin();
        for(;i != desc.parameters.end(); ++i)
        {
          cont->setValue(i->name, i->value);
        }

        //Call load on the controller
        cont->load();

        //Add to loadedControllers_
        LoadedController l(temp.name, cont);
        loadedControllers_.push_back(l);

        return;
    }
void MatlabTemplateComponentImpl<Tin,Tout>::process()
{
  //Get the input buffer
  inBuf_->getReadData(readDataSet_);

  //Check dimensions of our matlab matrix
  const mwSize* dims = mxGetDimensions(matlabInput_);
  size_t s = readDataSet_->data.size();
  if(s != dims[0])
  {
    mxDestroyArray(matlabInput_);
    if(TypeInfo<T>::isComplex)
    {
      matlabInput_ = mxCreateDoubleMatrix(1, s, mxCOMPLEX);
    }
    else
    {
      matlabInput_ = mxCreateDoubleMatrix(1, s, mxREAL);
    }
  }

  //Copy data into our matlab matrix
  copyInData(readDataSet_->data, matlabInput_);

//bug in matlab windows - has to be reopened every time
#ifdef _WIN32 // _WIN32 is defined by all Windows 32 compilers, but not by others.
  if(!matlab_.open(""))
  {
    throw ResourceNotFoundException("Failed to start Matlab engine");
  }
#endif

  //Send data to matlab
  matlab_.putVariable("matlab_input", matlabInput_);

  //Use OutputBuffer to capture MATLAB output
  memset(buffer_, 0, 256 * sizeof(char));
  matlab_.outputBuffer(buffer_, 256);

  //Process in Matlab
  matlab_.evalString(command_.c_str());

  //The evaluate string returns the result into the output buffer
  if (buffer_[0] != 0)
  {
    LOG(LWARNING) << buffer_;
  }

  //Output data if required
  if(hasOutput_x || passThrough_x)
  {
    if(passThrough_x)
    {
      //Get a write data set
      outBuf_->getWriteData(writeDataSet_, readDataSet_->data.size());
      //Copy data through
      copy(readDataSet_->data.begin(), readDataSet_->data.end(), writeDataSet_->data.begin());
      writeDataSet_->sampleRate = readDataSet_->sampleRate;
      writeDataSet_->timeStamp = readDataSet_->timeStamp;
    }
    else
    {
      //Get the matlab output
      mxArray* matlab_output = matlab_.getVariable("matlab_output");
      size_t m = mxGetM(matlab_output);
      size_t n = mxGetN(matlab_output);
      //Get a write data set of the correct size and copy data
      outBuf_->getWriteData(writeDataSet_, m>n?m:n);
      copyOutData(matlab_output, writeDataSet_->data);
    }

    //Release write data set
    outBuf_->releaseWriteData(writeDataSet_);
  }

  //Release read data set
  inBuf_->releaseReadData(readDataSet_);
}
Esempio n. 11
0
    void PhyEngine::buildEngineGraph(RadioGraph& graph)
    {
        //Create the components
        VertexIterator i, iend;
        for(b::tie(i,iend) = vertices(graph); i != iend; ++i)
        {
            //Load the component and add to vector
            ComponentDescription current = graph[*i];
            b::shared_ptr<PhyComponent> comp = compManager_->loadComponent(current);
            comp->setEngine(this);    //Provide an interface to the component
            components_.push_back(comp);
        }

        //Do a topological sort of the graph
        deque<unsigned> topoOrder;
        topological_sort(graph, front_inserter(topoOrder), b::vertex_index_map(b::identity_property_map()));

        //Set up some containers
        vector< ReadBufferBase* > currentInBufs;
        vector< WriteBufferBase* > currentOutBufs;
        map<string, int> inputTypes, outputTypes;

        //The external input buffers feed the source component of the graph
        for( vector< b::shared_ptr< DataBufferBase > >::iterator i = engInputBuffers_.begin(); i != engInputBuffers_.end(); ++i)
        {
            DataBufferBase* buf = (*i).get();
            LinkDescription desc = buf->getLinkDescription();
            inputTypes[desc.sinkPort] = buf->getTypeIdentifier();
            currentInBufs.push_back(dynamic_cast<ReadBufferBase*>(buf));
        }

        //Set buffers on the components
        for(deque<unsigned>::iterator i = topoOrder.begin(); i != topoOrder.end(); ++i)
        {
            //Get the internal input buffer details
            InEdgeIterator edgeIt, edgeItEnd;
            for(b::tie(edgeIt, edgeItEnd) = in_edges(*i, graph); edgeIt != edgeItEnd; ++edgeIt)
            {
                inputTypes[graph[*edgeIt].sinkPort] =  graph[*edgeIt].theBuffer->getTypeIdentifier();
                currentInBufs.push_back(dynamic_cast<ReadBufferBase*>(graph[*edgeIt].theBuffer.get()));
            }

            //TODO: Check that the input port names from the xml match existing input ports
            //TODO: Check that inputs exist for each of the registered input port names

            //Get output buffer types from component
            components_[*i]->calculateOutputTypes(inputTypes, outputTypes);

            // temporary shell for testing template components
            std::vector<int> inTypes, outTypes;
            for (std::map<std::string, int>::iterator j = inputTypes.begin(); j != inputTypes.end(); ++j)
            {
                inTypes.push_back(j->second);
            }
            for (std::map<std::string, int>::iterator j = outputTypes.begin(); j != outputTypes.end(); ++j)
            {
                outTypes.push_back(j->second);
            }

            PhyComponent* x = components_[*i]->setupIO(inTypes, outTypes);
            if (x != components_[*i].get())
            {
                components_[*i].reset(x);
            }

            //Create internal output buffers and add to graph edges
            OutEdgeIterator outEdgeIt, outEdgeItEnd;
            for(b::tie(outEdgeIt, outEdgeItEnd) = out_edges(*i, graph); outEdgeIt != outEdgeItEnd; ++outEdgeIt)
            {
                //Check that the port name exists
                string srcPort = graph[*outEdgeIt].sourcePort;
                if(outputTypes.find(srcPort) == outputTypes.end())
                {
                    throw ResourceNotFoundException("Output port " + srcPort + \
                        " could not be found on PhyComponent " + components_[*i]->getName());
                }

                //Create a PhyDataBuffer of the correct type
                int currentType = outputTypes[srcPort];
                b::shared_ptr< DataBufferBase > buf = createPhyDataBuffer(currentType);
                graph[*outEdgeIt].theBuffer = buf;
                graph[*outEdgeIt].theBuffer->setLinkDescription(graph[*outEdgeIt]);
                internalBuffers_.push_back( buf );

                currentOutBufs.push_back( dynamic_cast<WriteBufferBase*>( buf.get() ) );

                //Remove from the outputTypes map
                outputTypes.erase( outputTypes.find( srcPort ) );
            }

            //Anything left in the outputTypes map must be an external output buffer
            for( map<string, int>::iterator j = outputTypes.begin(); j != outputTypes.end(); ++j)
            {
                //Create a DataBuffer and add to exOutputBuffers
                b::shared_ptr< DataBufferBase > buf = createDataBuffer( j->second );
                LinkDescription l;
                l.sourceEngine = engineName_;
                l.sourceComponent = components_[*i]->getName();
                l.sourcePort = j->first;
                buf->setLinkDescription(l);
                engOutputBuffers_.push_back(buf);
                currentOutBufs.push_back( dynamic_cast<WriteBufferBase*>( buf.get() ) );
            }

            //Set the buffers in the component
            components_[*i]->setBuffers(currentInBufs, currentOutBufs);

            //Initialize the component
            components_[*i]->initialize();

            currentInBufs.clear();
            currentOutBufs.clear();
        }

    }