Ejemplo n.º 1
0
void OdeSdlSimulation::init(RobotStreamer *streamer, 
                            RobotConfig *config) {
    OdeInit& odeinit = OdeInit::get();
    if (video!=NULL) {
        fprintf(stderr, "Only one Simulation object allowed\n");
        yarp::os::exit(1);
    }
    robot_streamer = streamer;
    robot_config = config;

    ode_step_length = config->getWorldTimestep();
    dstep = ode_step_length*1e-3;

    video = new VideoTexture;
    string moduleName = odeinit.getName();
    video->setName( moduleName ); 
    odeinit._iCub->eyeLidsPortName = moduleName;
    Property options;

    //get the camera calibration parameters
    string camcalib_context=robot_config->getFinder().check("camcalib_context",
                                                            Value("cameraCalibration")).asString().c_str();
    string camcalib_file=robot_config->getFinder().check("camcalib_file",
                                                         Value("icubSimEyes.ini")).asString().c_str();

    ResourceFinder rf_camcalib;
    rf_camcalib.setVerbose();
    rf_camcalib.setDefaultContext(camcalib_context.c_str());
    rf_camcalib.setDefaultConfigFile(camcalib_file.c_str());
    rf_camcalib.configure(0,NULL);

    //left
    Bottle &bCalibLeft=rf_camcalib.findGroup("CAMERA_CALIBRATION_LEFT");
    width_left=bCalibLeft.check("w",Value(320)).asInt();
    height_left=bCalibLeft.check("h",Value(240)).asInt();

    cameraSizeWidth=width_left;
    cameraSizeHeight=height_left;

    double focal_length_left=bCalibLeft.check("fy",Value(257.34)).asDouble();
    fov_left=2*atan2((double)height_left,2*focal_length_left)*180.0/M_PI;

    //right
    Bottle &bCalibRight=rf_camcalib.findGroup("CAMERA_CALIBRATION_RIGHT");
    width_right=bCalibRight.check("w",Value(320)).asInt();
    height_right=bCalibRight.check("h",Value(240)).asInt();

    double focal_length_right=bCalibRight.check("fy",Value(257.34)).asDouble();
    fov_right=2*atan2((double)height_right,2*focal_length_right)*180.0/M_PI;
    //--------------------------------------//


    ConstString videoconf = robot_config->getFinder().findFile("video");
    options.fromConfigFile(videoconf.c_str());

    Bottle textures = *options.find("textures").asList();
    for (int i=0; i<textures.size(); i++) {
        ConstString name = textures.get(i).asString();
        printf("Adding video texture %s\n", name.c_str());
        video->add(options.findGroup(name.c_str()));
    }
}
Ejemplo n.º 2
0
bool Item::mouseDoubleClickEvent( const EventInfo & eventInfo )
{
	Q_UNUSED(eventInfo);
	
	Property * property = 0l;
	Variant::Type::Value type = Variant::Type::None;
	
	const VariantDataMap::iterator variantDataEnd = m_variantData.end();
	for ( VariantDataMap::iterator it = m_variantData.begin(); it != variantDataEnd; ++it )
	{
		Property * current = *it;
		
		if ( current->type() == Variant::Type::Multiline ||
				   current->type() == Variant::Type::RichText )
		{
			property = current;
			type = current->type();
			break;
		}
	}
	if ( !property )
		return false;
	
	if ( type == Variant::Type::Multiline )
	{
		//KDialog * dlg = new KDialog( 0l, "", true, property->editorCaption(), KDialog::Ok|KDialog::Cancel|KDialog::User1, KDialog::Ok,
        //                             false, KStandardGuiItem::clear() );
        KDialog * dlg = new KDialog( 0 );
        dlg->setModal(true);
        dlg->setCaption( property->editorCaption() );
        dlg->setButtons(KDialog::Ok|KDialog::Cancel|KDialog::User1);
        dlg->setDefaultButton(KDialog::Ok);
        dlg->showButtonSeparator(false);
        dlg->setButtonText(KDialog::User1, KStandardGuiItem::clear().text());
        //QFrame *frame = dlg->makeMainWidget();
		QFrame *frame = new QFrame(dlg);
        dlg->setMainWidget(frame);
		QVBoxLayout *layout = new QVBoxLayout( frame );
        layout->setMargin(0);
        layout->setSpacing(dlg->spacingHint());
		KTextEdit *textEdit = new KTextEdit( frame );
		//textEdit->setTextFormat( Qt::PlainText ); // 2018.12.02
        textEdit->setAcceptRichText(false);
		textEdit->setText( property->value().toString() );
		layout->addWidget( textEdit, 10 );
		textEdit->setFocus();
		connect( dlg, SIGNAL( user1Clicked() ), textEdit, SLOT( clear() ) );
		dlg->setMinimumWidth( 600 );
		
		if ( dlg->exec() == KDialog::Accepted )
		{
			property->setValue( textEdit->toPlainText() );
			dataChanged();
			p_itemDocument->setModified(true);
		}
		delete dlg;
	}
	else
	{
		// Is rich text
		RichTextEditorDlg * dlg = new RichTextEditorDlg( 0l, property->editorCaption() );
		dlg->setText( property->value().toString() );
		
		if ( dlg->exec() == KDialog::Accepted )
		{
			property->setValue( dlg->text() );
			dataChanged();
			p_itemDocument->setModified(true);
		}
		delete dlg;
	}
	
	return true;
}
Ejemplo n.º 3
0
bool AnalogServer::open(yarp::os::Searchable &config)
{
     yTrace() << "AnalogServer param = " << config.toString().c_str();

    Property params;
    params.fromString(config.toString().c_str());
    bool correct=true;

//     if(params.check("ports"))
//     {
//       Bottle *ports=params.find("ports").asList();
//       setId(ports->get(0).asString().c_str());
//     }

    // Verify minimum set of parameters required
    if(!params.check("robotName") )   // ?? qui dentro, da dove lo pesco ??
    {
        correct=false;
        yError() << "AnalogServer missing robot Name, check your configuration file!! Quitting\n";
        return false;
    }

    if(params.check("deviceId"))
    {
      string tmp(params.find("deviceId").asString());// .asList();
//       string tmp(deviceId->get(0).asString());
      cout << tmp;
      setId(tmp);
    }

    if (params.check("period"))
    {
        _rate=params.find("period").asInt();
    }
    else
    {
        _rate=20;
        std::cout<<"Warning: part "<< id <<" using default period ("<<_rate<<")\n";
    }

    // Read the list of ports
    std::string robotName=params.find("robotName").asString().c_str();
    std::string root_name;
    root_name+="/";
    root_name+=robotName;
    root_name+= "/" + this->id + "/analog";
    rpcPortName = root_name + "/rpc:i";

    // port names are optional, do not check for correctness.
    if(!params.check("ports"))
    {
     // if there is no "ports" section take the name of the "skin" group as the only port name
        createPort((root_name+":o" ).c_str(), _rate );

//         tmpPorts.resize( (size_t) 1);
//         tmpPorts[0].offset = 0;
//         tmpPorts[0].length = -1;
//         tmpPorts[0].port_name = root_name + this->id;
    }
    else
    {
        Bottle *ports=params.find("ports").asList();

        if (!params.check("total_taxels", "number of taxels of the part"))
            return false;
        int total_taxels=params.find("total_taxels").asInt();
        int nports=ports->size();
        int totalT = 0;
        std::vector<AnalogPortEntry> tmpPorts;
        tmpPorts.resize(nports);

        for(int k=0;k<ports->size();k++)
        {
            Bottle parameters=params.findGroup(ports->get(k).asString().c_str());

            if (parameters.size()!=5)
            {
                yError () <<"check skin port parameters in part description";
                yError() << "--> I was expecting "<<ports->get(k).asString().c_str() << " followed by four integers";
                return false;
            }

            int wBase=parameters.get(1).asInt();
            int wTop=parameters.get(2).asInt();
            int base=parameters.get(3).asInt();
            int top=parameters.get(4).asInt();

            cout<<"--> "<<wBase<<" "<<wTop<<" "<<base<<" "<<top<<endl;

            //check consistenty
            if(wTop-wBase != top-base){
                cerr<<"Error: check skin port parameters in part description"<<endl;
                cerr<<"Numbers of mapped taxels do not match.\n";
                return false;
            }
            int taxels=top-base+1;

            tmpPorts[k].length = taxels;
            tmpPorts[k].offset = wBase;
            tmpPorts[k].port_name = root_name+":o"+string(ports->get(k).asString().c_str());

            createPorts(tmpPorts, _rate);
            totalT+=taxels;
        }

        if (totalT!=total_taxels)
        {
            yError() << "Error total number of mapped taxels does not correspond to total taxels";
            return false;
        }
    }
    return true;
}
Ejemplo n.º 4
0
void BaseTestProperty::testIsValidEntity() {
    Property p = section.createProperty("testProperty", DataType::Double);
    CPPUNIT_ASSERT(p.isValidEntity());
    section.deleteProperty(p.name());
    CPPUNIT_ASSERT(!p.isValidEntity());
}
Ejemplo n.º 5
0
/**
 *
 * @param object
 * @param parent
 * @return
 */
ClassDialog::ClassDialog( Object *object, QWidget *parent) :
	KDialog(parent)
{
	m_object = object;
	setModal( false );

	showButtonOK( true );
	showButtonCancel( true );
	showButtonApply( false );

	m_tab = new KTabWidget( this );
	setMainWidget( m_tab );
	QWidget *widget = new QWidget( this );
	
	m_tab->addTab( widget, object->classInfo()->name() );
	
	
	//connect( this, SIGNAL(okClicked()), SLOT(slotOkClicked()) );

	QVBoxLayout *layout = new QVBoxLayout( widget );

	LabelsMetaInfo *labels = dynamic_cast<LabelsMetaInfo*>( object->classInfo()->metaInfo( "labels" ) );

	QLabel *label;
	label = new QLabel( widget );
	label->setAlignment( Qt::AlignCenter );
	if ( labels )
		label->setText( "<b>"  + labels->label( object->classInfo()->name() ) + "</b>" );
	else
		label->setText( "<b>" + object->classInfo()->name() + "</b>" );

	if ( labels )
		setCaption( labels->label( object->classInfo()->name() )  + " (" + oidToString(object->oid()) + ")" );
	else
		setCaption( object->classInfo()->name() + " (" + oidToString(object->oid()) + ")" );

	layout->addWidget( label );
	layout->addSpacing( 10 );

	QGridLayout *gridLayout = new QGridLayout( layout, object->numProperties() + object->numObjects() + object->numCollections(), 2, 5 );

	int row = 0;
	PropertiesIterator it( object->propertiesBegin() );
	PropertiesIterator end( object->propertiesEnd() );
	for ( ; it != end; ++it, ++row ) {
		Property p = *it;
		label = new QLabel( widget );
		if ( labels )
			label->setText( labels->label( p.name() ) );
		else
			label->setText( p.name() );
		gridLayout->addWidget( label, row, 0 );
		PropertyWidget *tmp = new PropertyWidget( p, widget );
		m_mapProperties.insert( p.name(), tmp );
		gridLayout->addWidget( tmp, row, 1 );
	}

	const ClassInfo *classInfo = object->classInfo();
	RelationInfosConstIterator it2( classInfo->relationsBegin() );
	RelationInfosConstIterator end2( classInfo->relationsEnd() );
	for ( ; it2 != end2; ++it2, ++row ) {
		RelationInfo *relObj = it2.data();
		label = new QLabel( widget );
		if ( labels )
			label->setText( labels->label( it2.data()->name() ) );
		else
			label->setText( it2.data()->name() );
		gridLayout->addWidget( label, row, 0 );

		QHBoxLayout *lay = new QHBoxLayout();
		gridLayout->addLayout( lay, row, 1 );
		KurlLabel *objLabel = new KurlLabel(widget);
		objLabel->setAlignment( Qt::AlignCenter );
		Object* obj = object->object( relObj->name() );
		updateObjectLabel( objLabel, obj );
		connect( objLabel, SIGNAL(leftClickedURL(const QString&)), SLOT(slotObjectSelected(const QString&)) );
		m_mapObjects.insert( relObj->name(), objLabel );
		QPushButton *but = new QPushButton( widget );
		but->setText( i18n( "Change" ) );
		connect( but, SIGNAL(clicked()), SLOT(slotChangeClicked()) );
		m_mapChangeButtons.insert( but, relObj );
		lay->addWidget( objLabel );
		lay->addWidget( but );

		Notifier *notifier = dynamic_cast<Notifier*>( Manager::self()->notificationHandler() );
//		if ( notifier && obj )
//			notifier->registerSlot( this, SLOT( slotObjectModified(const ClassInfo*,const OidType&,const PropertyInfo*,const QVariant&) ), 0, obj->oid() );
	}
	
	CollectionInfosConstIterator it3( classInfo->collectionsBegin() );
	CollectionInfosConstIterator end3( classInfo->collectionsEnd() );
	for ( ; it3 != end3; ++it3 ) {
		const CollectionInfo *info = it3.data();
		CollectionChooser *chooser = new CollectionChooser( m_tab );
		chooser->setObject( m_object );
		chooser->setCollectionName( info->name() );
		m_tab->addTab( chooser, info->name() );
	}
}
Ejemplo n.º 6
0
void UPnpCDSTv::AddItem( const UPnpCDSRequest    *pRequest, 
                         const QString           &sObjectId,
                         UPnpCDSExtensionResults *pResults,
                         bool                     bAddRef,
                         MSqlQuery               &query )
{
    int            nChanid      = query.value( 0).toInt();
    QDateTime      dtStartTime  = MythDate::as_utc(query.value(1).toDateTime());
    QDateTime      dtEndTime    = MythDate::as_utc(query.value(2).toDateTime());
    QString        sTitle       = query.value( 3).toString();
    QString        sSubtitle    = query.value( 4).toString();
    QString        sDescription = query.value( 5).toString();
    QString        sCategory    = query.value( 6).toString();
    QString        sHostName    = query.value( 7).toString();
    QString        sRecGroup    = query.value( 8).toString();
    uint64_t       nFileSize    = query.value( 9).toULongLong();
    QString        sBaseName    = query.value(10).toString();

    QDateTime      dtProgStart  =
        MythDate::as_utc(query.value(11).toDateTime());
    QDateTime      dtProgEnd    =
        MythDate::as_utc(query.value(12).toDateTime());
    QString        sStorageGrp  = query.value(13).toString();

    QString        sInetRef     = query.value(14).toString();

    // ----------------------------------------------------------------------
    // Cache Host ip Address & Port
    // ----------------------------------------------------------------------

    if (!m_mapBackendIp.contains( sHostName ))
        m_mapBackendIp[ sHostName ] = gCoreContext->GetBackendServerIP4(sHostName);

    if (!m_mapBackendPort.contains( sHostName ))
        m_mapBackendPort[ sHostName ] = gCoreContext->GetBackendStatusPort(sHostName);

    // ----------------------------------------------------------------------
    // Build Support Strings
    // ----------------------------------------------------------------------

    QString sName      = sTitle + ": " + (sSubtitle.isEmpty() ? sDescription.left(128) : sSubtitle);

    QString sURIBase   = QString( "http://%1:%2/Content/" )
                            .arg( m_mapBackendIp  [ sHostName ] )
                            .arg( m_mapBackendPort[ sHostName ] );

    QString sURIParams = QString( "?ChanId=%1&amp;StartTime=%2" )
                            .arg( nChanid )
                            .arg( dtStartTime.toString(Qt::ISODate));

    QString sId        = QString( "RecTv/0/item%1")
                            .arg( sURIParams );

    CDSObject *pItem   = CDSObject::CreateVideoItem( sId,
                                                     sName,
                                                     sObjectId );
    pItem->m_bRestricted  = false;
    pItem->m_bSearchable  = true;
    pItem->m_sWriteStatus = "WRITABLE";

    if ( bAddRef )
    {
        QString sRefId = QString( "%1/0/item%2")
                            .arg( m_sExtensionId )
                            .arg( sURIParams     );

        pItem->SetPropValue( "refID", sRefId );
    }

    pItem->SetPropValue( "genre"          , sCategory    );
    pItem->SetPropValue( "longDescription", sDescription );
    pItem->SetPropValue( "description"    , sSubtitle    );

    //pItem->SetPropValue( "producer"       , );
    //pItem->SetPropValue( "rating"         , );
    //pItem->SetPropValue( "actor"          , );
    //pItem->SetPropValue( "director"       , );
    //pItem->SetPropValue( "publisher"      , );
    //pItem->SetPropValue( "language"       , );
    //pItem->SetPropValue( "relation"       , );
    //pItem->SetPropValue( "region"         , );

    // ----------------------------------------------------------------------
    // Needed for Microsoft Media Player Compatibility
    // (Won't display correct Title without them)
    // ----------------------------------------------------------------------

    pItem->SetPropValue( "creator"       , "[Unknown Author]" );
    pItem->SetPropValue( "artist"        , "[Unknown Author]" );
    pItem->SetPropValue( "album"         , "[Unknown Series]" );
    pItem->SetPropValue( "actor"         , "[Unknown Author]" );
    pItem->SetPropValue( "date"          , dtStartTime.toString(Qt::ISODate));

    pResults->Add( pItem );

    // ----------------------------------------------------------------------
    // Add Video Resource Element based on File contents/extension (HTTP)
    // ----------------------------------------------------------------------

    StorageGroup sg(sStorageGrp, sHostName);
    QString sFilePath = sg.FindFile(sBaseName);
    QString sMimeType;

    if ( QFile::exists(sFilePath) )
        sMimeType = HTTPRequest::TestMimeType( sFilePath );
    else
        sMimeType = HTTPRequest::TestMimeType( sBaseName );


    // If we are dealing with Window Media Player 12 (i.e. Windows 7)
    // then fake the Mime type to place the recorded TV in the
    // recorded TV section.
    if (pRequest->m_eClient == CDS_ClientWMP &&
        pRequest->m_nClientVersion >= 12.0)
    {
        sMimeType = "video/x-ms-dvr";
    }

    // If we are dealing with a Sony Blu-ray player then we fake the
    // MIME type to force the video to appear
    if ( pRequest->m_eClient == CDS_ClientSonyDB )
    {
        sMimeType = "video/avi";
    }


    // DLNA string below is temp fix for ps3 seeking.
    QString sProtocol = QString( "http-get:*:%1:DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01500000000000000000000000000000" ).arg( sMimeType  );
    QString sURI      = QString( "%1GetRecording%2").arg( sURIBase   )
                                                    .arg( sURIParams );

    // Sony BDPS370 requires a DLNA Profile Name
    // FIXME: detection to determine the correct DLNA Profile Name
    if (sMimeType == "video/mpeg")
    {
        sProtocol += ";DLNA.ORG_PN=MPEG_TS_SD_NA_ISO";
    }

    Resource *pRes = pItem->AddResource( sProtocol, sURI );

    uint uiStart = dtProgStart.toTime_t();
    uint uiEnd   = dtProgEnd.toTime_t();
    uint uiDur   = uiEnd - uiStart;
    
    MSqlQuery query2(MSqlQuery::InitCon());
    query2.prepare( "SELECT data FROM recordedmarkup WHERE chanid=:CHANID AND "
                    "starttime=:STARTTIME AND type = 33" );
    query2.bindValue(":CHANID", (int)nChanid);
    query2.bindValue(":STARTTIME", dtStartTime);
    if (query2.exec() && query2.next())
        uiDur = query2.value(0).toUInt() / 1000;

    QString sDur;

    sDur.sprintf("%02d:%02d:%02d",
                  (uiDur / 3600) % 24,
                  (uiDur / 60) % 60,
                   uiDur % 60);

    LOG(VB_UPNP, LOG_DEBUG, "Duration: " + sDur );

    pRes->AddAttribute( "duration"  , sDur      );
    pRes->AddAttribute( "size"      , QString::number( nFileSize) );

/*
    // ----------------------------------------------------------------------
    // Add Video Resource Element based on File extension (mythtv)
    // ----------------------------------------------------------------------

    sProtocol = QString( "myth:*:%1:*"     ).arg( sMimeType  );
    sURI      = QString( "myth://%1/%2" )
                   .arg( m_mapBackendIp  [ sHostName ] )
                   .arg( sBaseName );

    pRes = pItem->AddResource( sProtocol, sURI );

    pRes->AddAttribute( "duration"  , sDur      );
    pRes->AddAttribute( "size"      , QString::number( nFileSize) );
*/

    // ----------------------------------------------------------------------
    // Add Preview URI as <res>
    // MUST be _TN and 160px
    // ----------------------------------------------------------------------

    sURI = QString( "%1GetPreviewImage%2%3").arg( sURIBase   )
                                            .arg( sURIParams )
                                            .arg( "&amp;Width=160" );

    // TODO: Must be JPG for minimal compliance
    sProtocol = QString( "http-get:*:image/png:DLNA.ORG_PN=PNG_TN");
    pItem->AddResource( sProtocol, sURI );

    // ----------------------------------------------------------------------
    // Add Artwork URI as albumArt
    // ----------------------------------------------------------------------

    sURI = QString( "%1GetRecordingArtwork?Type=coverart&amp;Inetref=%3")
                                              .arg( sURIBase   )
                                              .arg( sInetRef   );

    QList<Property*> propList = pItem->GetProperties("albumArtURI");
    if (propList.size() >= 4)
    {
        // Prefer JPEG over PNG here, although PNG is allowed JPEG probably
        // has wider device support and crucially the filesizes are smaller
        // which speeds up loading times over the network

        // We MUST include the thumbnail size, but since some clients may use the
        // first image they see and the thumbnail is tiny, instead return the
        // medium first. The large could be very large, which is no good if the
        // client is pulling images for an entire list at once!

        // Medium
        Property *pProp = propList.at(0);
        if (pProp)
        {
            // Must be no more than 1024x768
            pProp->m_sValue = sURI;
            pProp->m_sValue.append("&amp;Width=1024&amp;Height=768");
            pProp->AddAttribute("dlna:profileID", "JPG_MED");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        // Thumbnail
        pProp = propList.at(1);
        if (pProp)
        {
            // At least one albumArtURI must be a ThumbNail (TN) no larger
            // than 160x160, and it must also be a jpeg
            pProp->m_sValue = sURI;
            pProp->m_sValue.append("&amp;Width=160&amp;Height=160");
            pProp->AddAttribute("dlna:profileID", "JPG_TN");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        // Medium
        pProp = propList.at(2);
        if (pProp)
        {
            // Must be no more than 1024x768
            pProp->m_sValue = sURI;
            pProp->m_sValue.append("&amp;Width=1024&amp;Height=768");
            pProp->AddAttribute("dlna:profileID", "JPG_MED");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        // Large
        pProp = propList.at(3);
        if (pProp)
        {
            // Must be no more than 4096x4096 - for our purposes, just return
            // a fullsize image
            pProp->m_sValue = sURI;
            pProp->AddAttribute("dlna:profileID", "JPG_LRG");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }
    }


}
Ejemplo n.º 7
0
    virtual bool configure(yarp::os::ResourceFinder &rf)
    {
        Property options;
        options.fromString(rf.toString());
        char robotName[255];
        Bottle *jointsList=0;
        std::string moduleName = "directPositionControl";
        Time::turboBoost();

        options.put("device", "remote_controlboard");
        if(options.check("robot"))
            strncpy(robotName, options.find("robot").asString().c_str(),sizeof(robotName));
        else
            strncpy(robotName, "icub", sizeof(robotName));

        if (options.check("name"))
        {
            moduleName = options.find("name").asString();
        }

        if(options.check("part"))
        {
            sprintf(partName, "%s", options.find("part").asString().c_str());

            char tmp[255];
            sprintf(tmp, "/%s/%s/%s/client", moduleName.c_str(), robotName, partName);
            options.put("local",tmp);
        
            sprintf(tmp, "/%s/%s", robotName, partName);
            options.put("remote", tmp);
        
            sprintf(tmp, "/%s/%s/rpc", moduleName.c_str(), partName);
            rpc_port.open(tmp);
            
            options.put("carrier", "tcp");
            
            attach(rpc_port);
        }
        else
        {
            yError("Please specify part (e.g. --part head)\n");
            return false;
        }

        if(options.check("joints"))
        {
            jointsList = options.find("joints").asList();
            if (jointsList==0) yError("Unable to parts 'joints' parameter\n");
        }
        else
        {
            yError("Please specify the joints to control (e.g. --joints ""(0 1 2)"" ");
            return false;
        }

        //opening the device driver
        if (!driver.open(options))
        {
            yError("Error opening device, check parameters\n");
            return false;
        }

        ///starting the thread
        int period = CONTROL_PERIOD;
        if(options.check("period"))
            period = options.find("period").asInt();
        
        yInfo("control rate is %d ms",period);

        pThread=new positionDirectControlThread(period);
        pThread->init(&driver, moduleName, partName, robotName, jointsList);
        pThread->start();

        return true;
    }
Ejemplo n.º 8
0
int main(int argc, char *argv[]) 
{
    // just list the devices if no argument given
    if (argc <= 2) {
        printf("You can call %s like this:\n", argv[0]);
        printf("   %s --robot ROBOTNAME --OPTION VALUE ...\n", argv[0]);
        printf("For example:\n");
        printf("   %s --robot icub --local /talkto/james --remote /controlboard/rpc\n", argv[0]);
        printf("Here are devices listed for your system:\n");
        printf("%s", Drivers::factory().toString().c_str());
        return 0;
    }

    // get command line options
    Property options;
    options.fromCommand(argc, argv);
    if (!options.check("robot") || !options.check("part")) {
        printf("Missing either --robot or --part options\n");
        return 0;
    }

    Network::init();
	Time::turboBoost();
    
    std::string name;
    Value& v = options.find("robot");
    Value& part = options.find("part");

    Value *val;
    if (!options.check("device", val)) {
        options.put("device", "remote_controlboard");
    }
    if (!options.check("local", val)) {
		name="/"+std::string(v.asString().c_str())+"/"+std::string(part.asString().c_str())+"/simpleclient";
        //sprintf(&name[0], "/%s/%s/client", v.asString().c_str(), part.asString().c_str());
        options.put("local", name.c_str());
    }
    if (!options.check("remote", val)) {
        name="/"+std::string(v.asString().c_str())+"/"+std::string(part.asString().c_str());    
		//sprintf(&name[0], "/%s/%s", v.asString().c_str(), part.asString().c_str());
        options.put("remote", name.c_str());
    }

	fprintf(stderr, "%s", options.toString().c_str());

    
    // create a device 
    PolyDriver dd(options);
    if (!dd.isValid()) {
        printf("Device not available.  Here are the known devices:\n");
        printf("%s", Drivers::factory().toString().c_str());
        Network::fini();
        return 1;
    }

    IPositionControl *pos;
    IPositionDirect  *posDir;
    IVelocityControl *vel;
    IEncoders *enc;
    IPidControl *pid;
    IAmplifierControl *amp;
    IControlLimits *lim;
//    IControlMode *icm;
    IControlMode2 *iMode2;
    ITorqueControl *itorque;
    IOpenLoopControl *iopenloop;
	IImpedanceControl *iimp;
    IInteractionMode *iInteract;

    bool ok;
    ok = dd.view(pos);
    ok &= dd.view(vel);
    ok &= dd.view(enc);
    ok &= dd.view(pid);
    ok &= dd.view(amp);
    ok &= dd.view(lim);
//    ok &= dd.view(icm);
    ok &= dd.view(itorque);
    ok &= dd.view(iopenloop);
	ok &= dd.view(iimp);
    ok &= dd.view(posDir);
    ok &= dd.view(iMode2);
    ok &= dd.view(iInteract);

    if (!ok) {
        printf("Problems acquiring interfaces\n");
        return 1;
    }

    pos->getAxes(&jnts);
    printf("Working with %d axes\n", jnts);
    double *tmp = new double[jnts];

    printf("Device active...\n");
    while (dd.isValid()) {
        std::string s;
        s.resize(1024);
        
        printf("-> ");
        char c = 0;
        int i = 0;
        while (c != '\n') {
            c = (char)fgetc(stdin);
            s[i++] = c;
        }
        s[i-1] = s[i] = 0;

        Bottle p;
        Bottle response;
        bool ok=false;
        bool rec=false;
        p.fromString(s.c_str());
        printf("Bottle: %s\n", p.toString().c_str());

        switch(p.get(0).asVocab()) {      
        case VOCAB_HELP:
            printf("\n\n");
            printf("Available commands:\n");
			printf("-------------------\n\n");

            printf("IOpenLoop:\ntype [%s] and one of the following:\n", Vocab::decode(VOCAB_IOPENLOOP).c_str());
            printf("	[set] [%s] <int> <float>\n",
                    Vocab::decode(VOCAB_OUTPUT).c_str());
            printf("	[get] [%s] <int>\n",
                    Vocab::decode(VOCAB_OUTPUT).c_str());
            printf("	[get] [%s]\n\n",
                    Vocab::decode(VOCAB_OUTPUTS).c_str());

            printf("IControlMode:\ntype [%s] and one of the following:\n", Vocab::decode(VOCAB_ICONTROLMODE).c_str());
            printf("	[set] [%s]|[%s]|[%s]|[%s]|[%s]|[%s]|[%s]|[%s][%s]|[%s]\n",
                    Vocab::decode(VOCAB_CM_POSITION).c_str(),
                    Vocab::decode(VOCAB_CM_POSITION_DIRECT).c_str(),
                    Vocab::decode(VOCAB_CM_VELOCITY).c_str(),
                    Vocab::decode(VOCAB_CM_MIXED).c_str(),
                    Vocab::decode(VOCAB_CM_TORQUE).c_str(),
                    Vocab::decode(VOCAB_CM_OPENLOOP).c_str(),
                    Vocab::decode(VOCAB_CM_IDLE).c_str(),
                    Vocab::decode(VOCAB_CM_FORCE_IDLE).c_str(),
                    Vocab::decode(VOCAB_CM_IMPEDANCE_POS).c_str(),
                    Vocab::decode(VOCAB_CM_IMPEDANCE_VEL).c_str());
            
            printf("	[get] [%s] <int>\n\n",
                Vocab::decode(VOCAB_CM_CONTROL_MODE).c_str());

            printf("ITorqueControl:\ntype [%s] and one of the following:\n", Vocab::decode(VOCAB_TORQUE).c_str());
            printf("	[get] [%s] <int> to read the measured torque for a single axis\n",                  Vocab::decode(VOCAB_TRQ).c_str());
            printf("	[get] [%s]  to read the measured torque for all axes\n",                      Vocab::decode(VOCAB_TRQS).c_str());
            printf("	[set] [%s] <int> <float> to set the reference torque for a single axis\n",          Vocab::decode(VOCAB_REF).c_str());
            printf("	[set] [%s] <float list> to set the reference torque for all axes\n",        Vocab::decode(VOCAB_REFS).c_str());
            printf("	[get] [%s] <int> to read the reference torque for a single axis\n",                  Vocab::decode(VOCAB_REF).c_str());
            printf("	[get] [%s] to read the reference torque for all axes\n\n",                      Vocab::decode(VOCAB_REFS).c_str());

			printf("IImpedanceControl:\ntype [%s] and one of the following:\n", Vocab::decode(VOCAB_IMPEDANCE).c_str());
            printf("	[set] [%s] <int> <float> <float> \n", 
                Vocab::decode(VOCAB_IMP_PARAM).c_str());
            printf("	[set] [%s] <int> <float>\n\n", 
                Vocab::decode(VOCAB_IMP_OFFSET).c_str());

            printf("	[get] [%s] <int>\n", 
                Vocab::decode(VOCAB_IMP_PARAM).c_str());
            printf("	[get] [%s] <int>\n\n", 
                Vocab::decode(VOCAB_IMP_OFFSET).c_str());

            printf("IInteractionMode:\ntype [%s] and one of the following:\n", Vocab::decode(VOCAB_INTERFACE_INTERACTION_MODE).c_str());
            printf("	[set] [%s]|[%s] <int>\n",
                    Vocab::decode(VOCAB_IM_STIFF).c_str(),
                    Vocab::decode(VOCAB_IM_COMPLIANT).c_str());

            printf("	[get] [%s] <int>\n",
                Vocab::decode(VOCAB_INTERACTION_MODE).c_str());
            printf("	[get] [%s] \n\n",
                Vocab::decode(VOCAB_INTERACTION_MODES).c_str());

			printf("Standard Interfaces:\n");
            printf("type [get] and one of the following:\n");
            printf("	[%s] to read the number of controlled axes\n", Vocab::decode(VOCAB_AXES).c_str());
            printf("	[%s] to read the encoder value for all axes\n", Vocab::decode(VOCAB_ENCODERS).c_str());
            printf("	[%s] to read the PID values for all axes\n", Vocab::decode(VOCAB_PIDS).c_str());
            printf("	[%s] <int> to read the PID values for a single axis\n", Vocab::decode(VOCAB_PID).c_str());
            printf("	[%s] <int> to read the limit values for a single axis\n", Vocab::decode(VOCAB_LIMITS).c_str());
            printf("	[%s] to read the PID error for all axes\n", Vocab::decode(VOCAB_ERRS).c_str());
            printf("	[%s] to read the PID output for all axes\n", Vocab::decode(VOCAB_OUTPUTS).c_str());
            printf("	[%s] to read the reference position for all axes\n", Vocab::decode(VOCAB_REFERENCES).c_str());
			printf("	[%s] <int> to read the reference position for a single axis\n", Vocab::decode(VOCAB_REFERENCE).c_str());
            printf("	[%s] to read the reference speed for all axes\n", Vocab::decode(VOCAB_REF_SPEEDS).c_str());
			printf("	[%s] <int> to read the reference speed for a single axis\n", Vocab::decode(VOCAB_REF_SPEED).c_str());
            printf("	[%s] to read the reference acceleration for all axes\n", Vocab::decode(VOCAB_REF_ACCELERATIONS).c_str());
			printf("	[%s] <int> to read the reference acceleration for a single axis\n", Vocab::decode(VOCAB_REF_ACCELERATION).c_str());
            printf("	[%s] to read the current consumption for all axes\n", Vocab::decode(VOCAB_AMP_CURRENTS).c_str());

            printf("\n");

            printf("type [set] and one of the following:\n");
            printf("	[%s] <int> <double> to move a single axis\n", Vocab::decode(VOCAB_POSITION_MOVE).c_str());
            printf("	[%s] <int> <double> to accelerate a single axis to a given speed\n", Vocab::decode(VOCAB_VELOCITY_MOVE).c_str());            
            printf("	[%s] <int> <double> to set the reference speed for a single axis\n", Vocab::decode(VOCAB_REF_SPEED).c_str());
            printf("	[%s] <int> <double> to set the reference acceleration for a single axis\n", Vocab::decode(VOCAB_REF_ACCELERATION).c_str());
            printf("	[%s] <list> to move multiple axes\n", Vocab::decode(VOCAB_POSITION_MOVES).c_str());
            printf("	[%s] <list> to accelerate multiple axes to a given speed\n", Vocab::decode(VOCAB_VELOCITY_MOVES).c_str());
            printf("	[%s] <list> to set the reference speed for all axes\n", Vocab::decode(VOCAB_REF_SPEEDS).c_str());
            printf("	[%s] <list> to set the reference acceleration for all axes\n", Vocab::decode(VOCAB_REF_ACCELERATIONS).c_str());          
            printf("	[%s] <int> to stop a single axis\n", Vocab::decode(VOCAB_STOP).c_str());
            printf("	[%s] <int> to stop all axes\n", Vocab::decode(VOCAB_STOPS).c_str());
            printf("	[%s] <int> <list> to set the PID values for a single axis\n", Vocab::decode(VOCAB_PID).c_str());
            printf("	[%s] <int> <list> to set the limits for a single axis\n", Vocab::decode(VOCAB_LIMITS).c_str());
            printf("	[%s] <int> to disable the PID control for a single axis\n", Vocab::decode(VOCAB_DISABLE).c_str());
            printf("	[%s] <int> to enable the PID control for a single axis\n", Vocab::decode(VOCAB_ENABLE).c_str());
            printf("	[%s] <int> <double> to set the encoder value for a single axis\n", Vocab::decode(VOCAB_ENCODER).c_str());
            printf("	[%s] <list> to set the encoder value for all axes\n", Vocab::decode(VOCAB_ENCODERS).c_str());
			printf("\n");
			printf("NOTES: - A list is a sequence of numbers in parenthesis, e.g. (10 2 1 10)\n");
			printf("       - Pids are expressed as a list of 7 numbers, type get pid <int> to see an example\n");
            printf("\n");
            break;

        case VOCAB_QUIT:
            goto ApplicationCleanQuit;
            break;

        case VOCAB_ICONTROLMODE:
            {
                handleControlModeMsg(iMode2, p, response, &rec, &ok);
                printf("%s\n", response.toString().c_str());
                break;
            }

        case VOCAB_IMPEDANCE:
            {
                handleImpedanceMsg(iimp, p, response, &rec, &ok);
                printf("%s\n", response.toString().c_str());
                break;
            }

		case VOCAB_TORQUE:
			{
				handleTorqueMsg(itorque, p, response, &rec, &ok);
				printf("%s\n", response.toString().c_str());
				break;
			}

        case VOCAB_INTERFACE_INTERACTION_MODE:
            {
                handleInteractionModeMsg(iInteract, p, response, &rec, &ok);
                printf("%s\n", response.toString().c_str());
                break;
            }

        case VOCAB_GET:
            switch(p.get(1).asVocab()) {
                case VOCAB_AXES: {
                    int nj = 0;
                    enc->getAxes(&nj);
                    printf ("%s: %d\n", Vocab::decode(VOCAB_AXES).c_str(), nj);
                }
                break;

                case VOCAB_ENCODERS: {
                    enc->getEncoders(tmp);
                    printf ("%s: (", Vocab::decode(VOCAB_ENCODERS).c_str());
                    for(i = 0; i < jnts; i++)
                        printf ("%.2f ", tmp[i]);
                    printf (")\n");
                }
                break;

                case VOCAB_PID: {
                    Pid pd;
                    int j = p.get(2).asInt();
                    pid->getPid(j, &pd);
                    printf("%s: ", Vocab::decode(VOCAB_PID).c_str());
                    printf("kp %.2f ", pd.kp);
                    printf("kd %.2f ", pd.kd);
                    printf("ki %.2f ", pd.ki);
                    printf("maxi %.2f ", pd.max_int);
                    printf("maxo %.2f ", pd.max_output);
                    printf("off %.2f ", pd.offset);
                    printf("scale %.2f ", pd.scale);
                    printf("\n");
                }
                break;

               case VOCAB_PIDS: {
                    Pid *p = new Pid[jnts];
                    ok = pid->getPids(p);
                    Bottle& b = response.addList();
                    int i;
                    for (i = 0; i < jnts; i++)
                        {
                          Bottle& c = b.addList();
                          c.addDouble(p[i].kp);
                          c.addDouble(p[i].kd);
                          c.addDouble(p[i].ki);
                          c.addDouble(p[i].max_int);
                          c.addDouble(p[i].max_output);
                          c.addDouble(p[i].offset);
                          c.addDouble(p[i].scale);
                        }
                    printf("%s\n", b.toString().c_str());
                    delete[] p;
                }
                break;

                case VOCAB_LIMITS: {
                    double min, max;
                    int j = p.get(2).asInt();
                    lim->getLimits(j, &min, &max);
                    printf("%s: ", Vocab::decode(VOCAB_LIMITS).c_str());
                    printf("limits: (%.2f %.2f)\n", min, max);
                }
                break;

                case VOCAB_ERRS: {
					pid->getErrors(tmp);
                    printf ("%s: (", Vocab::decode(VOCAB_ERRS).c_str());
                    for(i = 0; i < jnts; i++)
                        printf ("%.2f ", tmp[i]);
                    printf (")\n");
                }
                break;

                case VOCAB_OUTPUTS: {
                    iopenloop->getOutputs(tmp);
                    printf ("%s: (", Vocab::decode(VOCAB_OUTPUTS).c_str());
                    for(i = 0; i < jnts; i++)
                        printf ("%.2f ", tmp[i]);
                    printf (")\n");
                }
                break;

                case VOCAB_OUTPUT: {
                    int j = p.get(2).asInt();
                    double v;
                    iopenloop->getOutput(j, &v);
                    printf("%s: ", Vocab::decode(VOCAB_OUTPUT).c_str());
                    printf("%.2f ", v);
                    printf("\n");
                }
                break;

				case VOCAB_REFERENCE: {
					double ref_pos;
					int j = p.get(2).asInt();
                    pid->getReference(j,&ref_pos);
                    printf ("%s: (", Vocab::decode(VOCAB_REFERENCE).c_str());
                    printf ("%.2f ", ref_pos);
                    printf (")\n");                    
                }
                break;

                case VOCAB_REFERENCES: {
                    pid->getReferences(tmp);
                    printf ("%s: (", Vocab::decode(VOCAB_REFERENCES).c_str());
                    for(i = 0; i < jnts; i++)
                        printf ("%.2f ", tmp[i]);
                    printf (")\n");                    
                }
                break;

                case VOCAB_REF_SPEEDS: {
                    pos->getRefSpeeds(tmp);
                    printf ("%s: (", Vocab::decode(VOCAB_REF_SPEEDS).c_str());
                    for(i = 0; i < jnts; i++)
                        printf ("%.2f ", tmp[i]);
                    printf (")\n");                    
                }
                break;

				case VOCAB_REF_SPEED: {
					double ref_speed;
					int j = p.get(2).asInt();
                    pos->getRefSpeed(j,&ref_speed);
                    printf ("%s: (", Vocab::decode(VOCAB_REF_SPEED).c_str());
                    printf ("%.2f ", ref_speed);
                    printf (")\n");                    
                }
                break;

				case VOCAB_REF_ACCELERATION: {
					double ref_acc;
					int j = p.get(2).asInt();
                    pos->getRefAcceleration(j,&ref_acc);
                    printf ("%s: (", Vocab::decode(VOCAB_REF_ACCELERATION).c_str());
                    printf ("%.2f ", ref_acc);
                    printf (")\n");                    
                }
                break;

                case VOCAB_REF_ACCELERATIONS: {
                    pos->getRefAccelerations(tmp);
                    printf ("%s: (", Vocab::decode(VOCAB_REF_ACCELERATIONS).c_str());
                    for(i = 0; i < jnts; i++)
                        printf ("%.2f ", tmp[i]);
                    printf (")\n");                    
                }
                break;

                case VOCAB_AMP_CURRENTS: {
                    amp->getCurrents(tmp);
                    printf ("%s: (", Vocab::decode(VOCAB_AMP_CURRENTS).c_str());
                    for(i = 0; i < jnts; i++)
                        printf ("%.2f ", tmp[i]);
                    printf (")\n");
                }
                break;
            }
            break;

        case VOCAB_SET:
            switch(p.get(1).asVocab()) {
                case VOCAB_POSITION_MOVE: {
                    int j = p.get(2).asInt();
                    double ref = p.get(3).asDouble();
                    printf("%s: moving %d to %.2f\n", Vocab::decode(VOCAB_POSITION_MOVE).c_str(), j, ref);
                    pos->positionMove(j, ref);
                }
                break;

                case VOCAB_VELOCITY_MOVE: {
                    int j = p.get(2).asInt();
                    double ref = p.get(3).asDouble();
                    printf("%s: accelerating %d to %.2f\n", Vocab::decode(VOCAB_VELOCITY_MOVE).c_str(), j, ref);
                    vel->velocityMove(j, ref);
                }
                break;

                case VOCAB_REF_SPEED: {
                    int j = p.get(2).asInt();
                    double ref = p.get(3).asDouble();
                    printf("%s: setting speed for %d to %.2f\n", Vocab::decode(VOCAB_REF_SPEED).c_str(), j, ref);
                    pos->setRefSpeed(j, ref);
                }
                break;

                case VOCAB_REF_ACCELERATION: {
                    int j = p.get(2).asInt();
                    double ref = p.get(3).asDouble();
                    printf("%s: setting acceleration for %d to %.2f\n", Vocab::decode(VOCAB_REF_ACCELERATION).c_str(), j, ref);
                    pos->setRefAcceleration(j, ref);
                }
                break;

                case VOCAB_POSITION_MOVES: {
                    Bottle *l = p.get(2).asList();
                    for (i = 0; i < jnts; i++) {
                        tmp[i] = l->get(i).asDouble();
                    }
                    printf("%s: moving all joints\n", Vocab::decode(VOCAB_POSITION_MOVES).c_str());
                    pos->positionMove(tmp);
                }
                break;

                case VOCAB_VELOCITY_MOVES: {
                    Bottle *l = p.get(2).asList();
                    for (i = 0; i < jnts; i++) {
                        tmp[i] = l->get(i).asDouble();
                    }
                    printf("%s: moving all joints\n", Vocab::decode(VOCAB_VELOCITY_MOVES).c_str());
                    vel->velocityMove(tmp);
                }
                break;

                case VOCAB_REF_SPEEDS: {
                    Bottle *l = p.get(2).asList();
                    for (i = 0; i < jnts; i++) {
                        tmp[i] = l->get(i).asDouble();
                    }
                    printf("%s: setting speed for all joints\n", Vocab::decode(VOCAB_REF_SPEEDS).c_str());
                    pos->setRefSpeeds(tmp);
                }
                break;

                case VOCAB_REF_ACCELERATIONS: {
                    Bottle *l = p.get(2).asList();
                    for (i = 0; i < jnts; i++) {
                        tmp[i] = l->get(i).asDouble();
                    }
                    printf("%s: setting acceleration for all joints\n", Vocab::decode(VOCAB_REF_ACCELERATIONS).c_str());
                    pos->setRefAccelerations(tmp);
                }
                break;

                case VOCAB_STOP: {
                    int j = p.get(2).asInt();
                    printf("%s: stopping axis %d\n", Vocab::decode(VOCAB_STOP).c_str(), j);
                    pos->stop(j);
                }
                break;

                case VOCAB_STOPS: {
                    printf("%s: stopping all axes\n", Vocab::decode(VOCAB_STOPS).c_str());
                    pos->stop();
                }
                break;

                case VOCAB_ENCODER: {
                    int j = p.get(2).asInt();
                    double ref = p.get(3).asDouble();
                    printf("%s: setting the encoder value for %d to %.2f\n", Vocab::decode(VOCAB_ENCODER).c_str(), j, ref);
                    enc->setEncoder(j, ref);                    
                }
                break; 

                case VOCAB_ENCODERS: {
                    Bottle *l = p.get(2).asList();
                    for (i = 0; i < jnts; i++) {
                        tmp[i] = l->get(i).asDouble();
                    }
                    printf("%s: setting the encoder value for all joints\n", Vocab::decode(VOCAB_ENCODERS).c_str());
                    enc->setEncoders(tmp);
                }
                break;

                case VOCAB_PID: {
                    Pid pd;
                    int j = p.get(2).asInt();
                    Bottle *l = p.get(3).asList();
                    if (l==0)
                        {
                            printf("Check you specify a 7 elements list, e.g. set pid 0 (2000 20 1 300 300 0 0)\n");
                        }
                    else
                        {
                            int elems=l->size();
                            if (elems>=3)
                                {
                                    pd.kp = l->get(0).asDouble();
                                    pd.kd = l->get(1).asDouble();
                                    pd.ki = l->get(2).asDouble();
                                    if (elems>=7)
                                        {
                                            pd.max_int = l->get(3).asDouble();
                                            pd.max_output = l->get(4).asDouble();
                                            pd.offset = l->get(5).asDouble();
                                            pd.scale = l->get(6).asDouble();
                                        }
                                    printf("%s: setting PID values for axis %d\n", Vocab::decode(VOCAB_PID).c_str(), j);
                                    pid->setPid(j, pd);
                                }
                            else
                                {
                                    printf("Error, check you specify at least 7 elements, e.g. set pid 0 (2000 20 1 300 300 0 0)\n");
                                }
                        }
                }
                break;

                case VOCAB_DISABLE: {
                    int j = p.get(2).asInt();
                    printf("%s: disabling control for axis %d\n", Vocab::decode(VOCAB_DISABLE).c_str(), j);
                    pid->disablePid(j);
                    amp->disableAmp(j);
                }
                break;

                case VOCAB_ENABLE: {
                    int j = p.get(2).asInt();
                    printf("%s: enabling control for axis %d\n", Vocab::decode(VOCAB_ENABLE).c_str(), j);
                    amp->enableAmp(j);
                    pid->enablePid(j);
                }
                break;

                case VOCAB_LIMITS: {
                    int j = p.get(2).asInt();
                    printf("%s: setting limits for axis %d\n", Vocab::decode(VOCAB_LIMITS).c_str(), j);
                    Bottle *l = p.get(3).asList();
                    lim->setLimits(j, l->get(0).asDouble(), l->get(1).asDouble());
                }
                break;

                case VOCAB_OUTPUT: {
                    int j=p.get(2).asInt();
                    double v=p.get(3).asDouble();
                    iopenloop->setRefOutput(j,v);
                    printf("%s: setting output for axis %d to %f\n", Vocab::decode(VOCAB_OUTPUT).c_str(), j, v);            
                }
                break;
            }
            break;
        } /* switch get(0) */

    } /* while () */

ApplicationCleanQuit:
    dd.close();
    delete[] tmp;

    Network::fini();
    return 0;
}
Ejemplo n.º 9
0
int main(int argc, char *argv[]) {
    Property p;
    p.fromCommand(argc,argv);

    // check where to put description of device
    ConstString dest = "";
    dest = p.check("doc",Value("")).toString();

    ConstString fileName = p.check("file",Value("default.ini")).asString();

    if (p.check("file")) {
        p.fromConfigFile(fileName);
    }

    ConstString deviceName = p.check("device",Value("")).asString();

    // if no device given, we should be operating a completely
    // standard test harness like for libYARP_OS and libYARP_sig
    if (deviceName=="") {
        return harness_main(argc,argv);
    }

    // device name given - use special device testing procedure

#ifdef CHECK_FOR_LEAKS
    mtrace();
#endif

    int result = 0;

    Network::init();
    Network::setLocalMode(true);

    String seek = fileName.c_str();
    ConstString exampleName = "";
    int pos = seek.rfind('/');
    if (pos==-1) {
        pos = seek.rfind('\\');
    }
    if (pos==-1) {
        pos = 0;
    } else {
        pos++;
    }
    int len = seek.find('.',pos);
    if (len==-1) {
        len = seek.length();
    } else {
        len -= pos;
    }
    exampleName = seek.substr(pos,len).c_str();
    ConstString shortFileName = seek.substr(pos,seek.length()).c_str();

    PolyDriver dd;
	YARP_DEBUG(Logger::get(), "harness opening...");
	
    bool ok = dd.open(p);
    YARP_DEBUG(Logger::get(), "harness opened.");
    result = ok?0:1;

    ConstString wrapperName = "";
    ConstString codeName = "";

    DriverCreator *creator = 
        Drivers::factory().find(deviceName.c_str());
    if (creator!=NULL) {
        wrapperName = creator->getWrapper();
        codeName = creator->getCode();
    }


    if (dest!="") {
        String dest2 = dest.c_str();
        if (result!=0) {
            dest2 += ".fail";
        }
        FILE *fout = fopen(dest2.c_str(),"w");
        if (fout==NULL) {
            printf("Problem writing to %s\n", dest2.c_str());
            exit(1);
        }
        fprintf(fout,"/**\n");
        fprintf(fout," * \\ingroup dev_examples\n");
        fprintf(fout," *\n");
        fprintf(fout," * \\defgroup %s Example for %s (%s)\n\n",
                exampleName.c_str(),
                deviceName.c_str(),
                exampleName.c_str());
        fprintf(fout, "Instantiates \\ref cmd_device_%s \"%s\" device implemented by yarp::dev::%s.\n",
                deviceName.c_str(), deviceName.c_str(), codeName.c_str());
        fprintf(fout, "\\verbatim\n%s\\endverbatim\n",
                getFile(fileName.c_str()).c_str());
        fprintf(fout, "If this text is saved in a file called %s then the device can be created by doing:\n",
                shortFileName.c_str());
        fprintf(fout, "\\verbatim\nyarpdev --file %s\n\\endverbatim\n",
                shortFileName.c_str());
        fprintf(fout, "Of course, the configuration could be passed just as command line options, or as a yarp::os::Property object in a program:\n");
        fprintf(fout, "\\code\n");
        fprintf(fout, "Property p;\n");
        fprintf(fout, "p.fromConfigFile(\"%s\");\n",
                shortFileName.c_str());
        fprintf(fout, "// of course you could construct the Property object on-the-fly\n");
        fprintf(fout, "PolyDriver dev;\n");
        fprintf(fout, "dev.open(p);\n");
        fprintf(fout, "if (dev.isValid()) { /* use the device via view method */ }\n" );
        fprintf(fout, "\\endcode\n");
        fprintf(fout, "Here is a list of properties checked when starting up a device based on this configuration file.  Note that which properties are checked can depend on whether other properties are present.  In some cases properties can also vary between operating systems.  So this is just an example\n\n");
        toDox(dd,fout);
        fprintf(fout, "\n\\sa yarp::dev::%s\n\n",
                codeName.c_str());
        fprintf(fout, " */\n");
        fclose(fout);
        fout = NULL;
    }

    if (ok) {
        YARP_DEBUG(Logger::get(), "harness closing...");
        dd.close();
        YARP_DEBUG(Logger::get(), "harness closed.");
    }

    // just checking for crashes, not device creation
    return result; //result;
}
/**
 * Determine if the property value is the same as the default value.
 * This can be used to determine if the property has not been set.
 * @param propertyName : Name of property to query
 * @return: True only if the property has it's default value.
 */
bool SpecularReflectionAlgorithm::isPropertyDefault(
    const std::string &propertyName) const {
  Property *property = this->getProperty(propertyName);
  return property->isDefault();
}
Ejemplo n.º 11
0
void SGMExporter::CollectProperties(Scene3DMesh *mesh, IGameMesh *gMesh)
{
	IPropertyContainer *propsContainer = gMesh->GetIPropertyContainer();
	if (propsContainer == NULL || propsContainer->GetNumberOfProperties() == 0)
	{
		Log::LogT("Mesh %s has no properties", mesh->name.c_str());
		return;
	}
	
	Log::LogT("properties count: %d", propsContainer->GetNumberOfProperties());

	for (int i = 0; i < propsContainer->GetNumberOfProperties(); i++)
	{
		IGameProperty *gProp = propsContainer->GetProperty(i);
		if (gProp == NULL)
			continue;

		int propType = gProp->GetType();
		std::string propName = StringUtils::ToNarrow(gProp->GetName());

		Log::LogT("eporting %s with type %d", propName.c_str(), propType);

		if (propType == IGAME_UNKNOWN_PROP)
		{
			Log::LogT("property %s has unknown type", propName.c_str());
			continue;
		}

		Property::AnimationType propAnimType = Property::AnimationType_None;

		Property *prop = NULL; 

		if (!gProp->IsPropAnimated())
		{
			Log::LogT("property %s has no animation", propName.c_str());

			prop = new Property(propName, PropTypeConv(propType), Property::AnimationType_None);
			switch (propType)
			{
			case IGAME_FLOAT_PROP:
				{
					float val;	
					gProp->GetPropertyValue(val);
					prop->SetValue(val);
				}
				break;

			case IGAME_INT_PROP:
				{
					int val;
					gProp->GetPropertyValue(val);
					prop->SetValue(val);
				}
				break;

			case IGAME_POINT3_PROP:
				{
					Point3 val;
					gProp->GetPropertyValue(val);
					prop->SetValue(sm::Vec3(val.x, val.y, val.z));
				}
				break;
			}
		}
		else
		{
			IGameControl *ctrl = gProp->GetIGameControl();

			if (ctrl == NULL)
			{
				Log::LogT("%s IGameControl is NULL", propName.c_str());
				continue;
			}

			switch (propType)
			{
			case IGAME_FLOAT_PROP:
				{
					Control *maxControl = ctrl->GetMaxControl(IGAME_FLOAT);
					if (maxControl != NULL && maxControl->IsAnimated())
					{
						if (maxControl->ClassID() == Class_ID(LININTERP_FLOAT_CLASS_ID, 0))
						{	
							Log::LogT("%s float liniowe scierwo", propName.c_str());
							prop = new Property(propName, Property::PropertyType_Float, Property::AnimationType_Linear);
							IGameKeyTab keys;
							if (ctrl->GetLinearKeys(keys, IGAME_FLOAT))
							{
								for (int j = 0; j < keys.Count(); j++)
								{
									prop->SetValue(keys[j].linearKey.fval, TicksToSec(keys[j].t));
								}
							}
						}
						if (maxControl->ClassID() == Class_ID(TCBINTERP_FLOAT_CLASS_ID, 0))
						{
							Log::LogT("%s float tcb scierwo", propName.c_str());
							prop = new Property(propName, Property::PropertyType_Float, Property::AnimationType_TCB);
							IGameKeyTab keys;
							if (ctrl->GetTCBKeys(keys, IGAME_FLOAT))
							{
								for (int j = 0; j < keys.Count(); j++)
								{
									prop->SetValue(keys[j].tcbKey.fval, TicksToSec(keys[j].t));
								}
							}
						}
					}
				}

				break;

			case IGAME_INT_PROP:
				{
					Control *maxControl = ctrl->GetMaxControl(IGAME_FLOAT);
					if (maxControl != NULL && maxControl->IsAnimated())
					{
						if (maxControl->ClassID() == Class_ID(LININTERP_FLOAT_CLASS_ID, 0))
						{
							Log::LogT("%s int liniowe scierwo", propName.c_str());
							//prop = new Property(propName, Property::PropertyType_Int, Property::AnimationType_Linear);
							// it should be always state interpolator for int
							prop = new Property(propName, Property::PropertyType_Int, Property::AnimationType_State);
							IGameKeyTab keys;
							if (ctrl->GetLinearKeys(keys, IGAME_FLOAT))
							{
								Log::LogT("eksportowanie %d keyframow", keys.Count());
								for (int j = 0; j < keys.Count(); j++)
								{
									prop->SetValue((int)keys[j].linearKey.fval, TicksToSec(keys[j].t));
								}
							}
						}
						if (maxControl->ClassID() == Class_ID(TCBINTERP_FLOAT_CLASS_ID, 0))
						{
							Log::LogT("%s int tcb scierwo", propName.c_str());
							//prop = new Property(propName, Property::PropertyType_Int, Property::AnimationType_TCB);
							// it should be always state interpolator for int
							prop = new Property(propName, Property::PropertyType_Int, Property::AnimationType_State);
							IGameKeyTab keys;
							if (ctrl->GetTCBKeys(keys, IGAME_FLOAT))
							{
								for (int j = 0; j < keys.Count(); j++)
								{
									prop->SetValue((int)keys[j].linearKey.fval, TicksToSec(keys[j].t));
								}
							}
						}
					}
					else
					{
					}
				}

				break;
			}
		}

		if (prop != NULL)
			mesh->properties.push_back(prop);
	}
}
bool V4l2Device::V4L2PropertyHandler::set_property (const Property& new_property)
{
    auto f = [&new_property] (const property_description& d)
        {
            return ((*d.prop).get_name().compare(new_property.get_name()) == 0);
        };

    auto desc = std::find_if(properties.begin(), properties.end(),f);

    if (desc == properties.end())
    {
        desc = std::find_if(special_properties.begin(), special_properties.end(), f);

        if (desc != special_properties.end())
        {
            desc->prop->set_struct(new_property.get_struct());

            if (device->changeV4L2Control(*desc))
            {
                return true;
            }
            return false;
        }


        tcam_log(TCAM_LOG_ERROR, "Unable to find Property \"%s\"", new_property.get_name().c_str());
        return false;
    }

    if (desc->id == EMULATED_PROPERTY)
    {
        if (new_property.get_ID() == TCAM_PROPERTY_OFFSET_AUTO)
        {
            auto props = create_property_vector();
            return handle_auto_center(new_property,
                                      props,
                                      device->get_sensor_size(),
                                      device->active_video_format.get_size());
        }
        else
        {
            tcam_log(TCAM_LOG_ERROR, "Emulated property not implemented \"%s\"", new_property.get_name().c_str());
            return false;
        }
    }
    else if (desc->mapped)
    {
        for (auto& m : mappings)
        {
            auto p = m.std_prop.lock();
            if (p == desc->prop)
            {
                if (p->get_type() == TCAM_PROPERTY_TYPE_BOOLEAN)
                {
                    auto value = new_property.get_struct().value.b.value;
                    p->set_value(value, false);
                    auto internal_p = m.internal_prop.lock();

                    internal_p->set_value(m.bool_map.at(value));
                }
                else
                {
                    tcam_error("mapping type not implemented");
                }
                break;
            }
        }
        desc->prop->set_struct(new_property.get_struct());

        if (device->changeV4L2Control(*desc))
        {
            return true;
        }
    }
    else
    {
        desc->prop->set_struct(new_property.get_struct());

        if (device->changeV4L2Control(*desc))
        {
            return true;
        }
    }
    return false;
}
Ejemplo n.º 13
0
 void PropertyHolder::setPropertyAsString(const Ogre::String& key, const CeGuiString& value)
 {
     Property prop = getProperty(key);
     prop.getFromString(value);
     setProperty(key, prop);
 }
Ejemplo n.º 14
0
// Call back Declaration
ReturnType JoystickComp::onInitialize()
{
	//	XML에 저장된 프라퍼티를 parameter에 저장
	Property parameter;
	std::map<std::string, std::string> temp = getPropertyMap();
	parameter.SetProperty(temp);
	
	//	dll 파일이름을 확인하여 없으면 에러 리턴
	if(parameter.FindName("APIName") == false) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't find the APIName in property\n");
		return OPROS_FIND_PROPERTY_ERROR;
	}

#if defined(WIN32)
	//	DLL 로드
	hOprosAPI = LoadLibrary((LPCSTR)parameter.GetValue("APIName").c_str());
	if(hOprosAPI == NULL) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("APIName").c_str());
		return OPROS_FIND_DLL_ERROR;
	}
	
	//	API 로드
	GET_OPROS_API getOprosAPI;
	getOprosAPI = (GET_OPROS_API)GetProcAddress(hOprosAPI, "GetAPI");
	if(getOprosAPI == NULL) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n");
		FreeLibrary(hOprosAPI);
		hOprosAPI = NULL;
		return OPROS_LOAD_DLL_ERROR;
	}
#else
	hOprosAPI = dlopen(parameter.GetValue("APIName").c_str(), RTLD_LAZY);
	if(hOprosAPI == NULL) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("APIName").c_str());
		return OPROS_FIND_DLL_ERROR;
	}

	GET_OPROS_API getOprosAPI;
	getOprosAPI = (GET_OPROS_API)dlsym(hOprosAPI, "GetAPI");
	char *lastError = dlerror();
	if(lastError != NULL) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n");
		dlclose(hOprosAPI);
		hOprosAPI = NULL;
		return OPROS_LOAD_DLL_ERROR;
	}
#endif
	
	joystick = static_cast<Joystick *>(getOprosAPI());
	if(joystick == NULL) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't get a handle of Joystick API\n");
#if defined(WIN32)
		FreeLibrary(hOprosAPI);
#else
		dlclose(hOprosAPI);
#endif
		hOprosAPI = NULL;
		return OPROS_LOAD_DLL_ERROR;
	}

	//	API 초기화
	if(joystick->Initialize(parameter) != API_SUCCESS) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't intilaize a Joystick API\n");
		
		delete joystick;
		joystick = NULL;

#if defined(WIN32)
		FreeLibrary(hOprosAPI);
#else
		dlclose(hOprosAPI);
#endif
		hOprosAPI = NULL;
		return OPROS_INITIALIZE_API_ERROR;
	}

	lastError = OPROS_SUCCESS;

	PrintMessage("SUCCESS : JoystickComp::onInitialize()\n");
	return OPROS_SUCCESS;
}
Ejemplo n.º 15
0
 yarp::os::Bottle findPaths(Property& config, const char *name) {
     ConstString fname = config.check(name,Value(name)).asString();
     Bottle paths;
     findFileBase(config,fname,true,paths,false);
     return paths;
 }
Ejemplo n.º 16
0
void BaseEntity::BaseEntity_Impl::Initialize(BaseEntity* ent, const EngineContext* engineContext)
{
    //	Id Property
    PropertyDescriptor idPropertyDesc;
    idPropertyDesc.Name = "Id";
    idPropertyDesc.CanSerialize = true;
    idPropertyDesc.Description = "Id of the Entity";
    idPropertyDesc.DisplayName = "Id";
    idPropertyDesc.IsBrowsable = true;
    idPropertyDesc.IsReadOnly = true;
    idPropertyDesc.Type = PropertyType::UINT32;

    Property* idProperty = AddProperty(ent, idPropertyDesc);

    uint32_t id = GetId();
    idProperty->Set((void*)&id);

    // Name Property
    PropertyDescriptor namePropertyDesc;
    namePropertyDesc.Name = "Name";
    namePropertyDesc.CanSerialize = true;
    namePropertyDesc.Description = "Name of the Entity";
    namePropertyDesc.DisplayName = "Name";
    namePropertyDesc.IsBrowsable = true;
    namePropertyDesc.IsReadOnly = true;
    namePropertyDesc.Type = PropertyType::STRING;

    Property* nameProperty = AddProperty(ent, namePropertyDesc);
    nameProperty->Set("");

    //	Position Property
    PropertyDescriptor positionPropertyDesc;
    positionPropertyDesc.Name = "Position";
    positionPropertyDesc.CanSerialize = true;
    positionPropertyDesc.Description = "Position of the Entity in World Space";
    positionPropertyDesc.DisplayName = "Starting Position";
    positionPropertyDesc.IsBrowsable = true;
    positionPropertyDesc.IsReadOnly = false;
    positionPropertyDesc.Type = PropertyType::VEC3F;

    vec3f pos = GetPosition();
    Property* positionProperty = AddProperty(ent, positionPropertyDesc);
    positionProperty->Set((void*)&pos);

    //	Direction Property
    PropertyDescriptor directionPropertyDesc;
    directionPropertyDesc.Name = "Direction";
    directionPropertyDesc.CanSerialize = true;
    directionPropertyDesc.Description = "Direction of the Entity in World Space";
    directionPropertyDesc.DisplayName = "Starting Direction";
    directionPropertyDesc.IsBrowsable = true;
    directionPropertyDesc.IsReadOnly = false;
    directionPropertyDesc.Type = PropertyType::VEC4F;

    vec4f direction = GetDirection();
    Property* directionProperty = AddProperty(ent, directionPropertyDesc);
    directionProperty->Set((void*)&direction);

    for (auto component : _components)
    {
        component->Initialize(engineContext);
    }

    ent->OnInitialize(engineContext);
};
Ejemplo n.º 17
0
 yarp::os::ConstString findFile(Property& config, const char *name) {
     ConstString fname = config.check(name,Value(name)).asString();
     ConstString result = findFileBase(config,fname,false);
     return result;
 }
Ejemplo n.º 18
0
void BaseEntity::Deserialize(SerializableNodeObject* parentNode, EngineContext* engineContext)
{
    if (!parentNode)
    {
        LOG("Cannot deserialize Entity: Node is null.");
        return;
    }

    // Position.
    /*SerializableProperty* positionProp = (SerializableProperty*)parentNode->FindNodeByName("position");
    if (positionProp)
    	this->SetPosition(positionProp->Value.toVec3f());

    // Pose.
    SerializableProperty* poseProp = (SerializableProperty*)parentNode->FindNodeByName("pose");
    if (poseProp)
    	this->SetPose(poseProp->Value.toMat4f());

    // Direction.
    SerializableProperty* directionProp = (SerializableProperty*)parentNode->FindNodeByName("direction");
    if (directionProp)
    	this->SetDirection(directionProp->Value.toVec3f());

    // Scale.
    SerializableProperty* scaleProp = (SerializableProperty*)parentNode->FindNodeByName("scale");
    if (scaleProp)
    	this->SetScale(scaleProp->Value.toVec3f());*/

    auto nbNodes = parentNode->GetChildNodesCount();
    auto nodes = parentNode->GetChildNodes();

    for (size_t i = 0; i < nbNodes; ++i)
    {
        auto node = nodes[i];

        if (node->GetType() == SerializableNodeType::ARRAY && node->Name.toLower() == "properties")
        {
            auto nbProperties = node->GetChildNodesCount();
            auto properties = node->GetChildNodes();

            for (size_t p = 0; p < nbProperties; ++p)
            {
                if (properties[p]->GetType() != SerializableNodeType::OBJECT)
                    continue;

                PropertyDescriptor pDesc;
                pDesc.Deserialize((SerializableNodeObject*)properties[p], engineContext);

                Property* prop = this->AddProperty(pDesc);

                // Look for the value node.
                SerializableProperty* valueNode = (SerializableProperty*)properties[p]->FindNodeByName("value");

                if (valueNode)
                    prop->Set(valueNode->Value);
            }
        }
        else if (node->GetType() == SerializableNodeType::ARRAY && node->Name.toLower() == "components")
        {
            auto nbComponents = node->GetChildNodesCount();
            auto components = node->GetChildNodes();

            for (size_t c = 0; c < nbComponents; ++c)
            {
                if (components[c]->GetType() != SerializableNodeType::OBJECT)
                    continue;

                SerializableNodeObject* nodeInfo = (SerializableNodeObject*)components[c];

                BaseComponent* component = BaseComponent::DeserializeComponent(nodeInfo, engineContext, this);

                if (!component)
                {
                    LOG("Unable to deserialize component. Skipping.");
                    continue;
                }

                this->AddComponent(component);

                //component->Deserialize(nodeInfo);
            }
        }
        else if (node->GetType() == SerializableNodeType::PROPERTY)
        {
            if (node->Name.toLower() == "class")
            {
                this->SetClass(node->Value.c_str());
            }
        }
    }
}
Ejemplo n.º 19
0
bool doubleTouchThread::threadInit()
{
    cntctRdr      -> open(("/"+name+"/contacts:i").c_str());

    Property OptGaze;
    OptGaze.put("device","gazecontrollerclient");
    OptGaze.put("remote","/iKinGazeCtrl");
    OptGaze.put("local",("/"+name+"/gaze").c_str());

    Property OptR;
    OptR.put("robot",  robot.c_str());
    OptR.put("part",   "right_arm");
    OptR.put("device", "remote_controlboard");
    OptR.put("remote",("/"+robot+"/right_arm").c_str());
    OptR.put("local", ("/"+name+"/posCtrl/right_arm").c_str());

    Property OptL;
    OptL.put("robot",  robot.c_str());
    OptL.put("part",   "left_arm");
    OptL.put("device", "remote_controlboard");
    OptL.put("remote",("/"+robot+"/left_arm").c_str());
    OptL.put("local", ("/"+name+"/posCtrl/left_arm").c_str());

    if ((!ddG.open(OptGaze)) || (!ddG.view(igaze))){
        printMessage(0,"Error: could not open the Gaze Controller!\n");
        return false;
    }

    igaze -> storeContext(&contextGaze);
    igaze -> setNeckTrajTime(1.5);
    igaze -> setEyesTrajTime(0.5);
    igaze -> setSaccadesStatus(false);

    if (!ddR.open(OptR))
    {
        printMessage(0,"ERROR: could not open right_arm PolyDriver!\n");
        return false;
    }

    // open the view
    bool ok = 1;
    if (ddR.isValid())
    {
        ok = ok && ddR.view(iencsR);
        ok = ok && ddR.view(iposR);
        ok = ok && ddR.view(ictrlR);
        ok = ok && ddR.view(ilimR);
    }

    if (!ok)
    {
        printMessage(0,"\nERROR: Problems acquiring right_arm interfaces!!!!\n");
        return false;
    }

    iencsR->getAxes(&jntsR);
    encsR = new Vector(jntsR,0.0);

    if (!ddL.open(OptL))
    {
        printMessage(0,"ERROR: could not open left_arm PolyDriver!\n");
        return false;
    }

    // open the view
    ok = 1;
    if (ddL.isValid())
    {
        ok = ok && ddL.view(iencsL);
        ok = ok && ddL.view(iposL);
        ok = ok && ddL.view(ictrlL);
        ok = ok && ddL.view(ilimL);
    }

    if (!ok)
    {
        printMessage(0,"\nERROR: Problems acquiring left_arm interfaces!!!!\n");
        return false;
    }

    iencsL->getAxes(&jntsL);
    encsL = new Vector(jntsL,0.0);

    alignJointsBounds();

    Vector joints;
    iencsR->getEncoders(encsR->data());
    probl->index.getChainJoints(*encsR,joints);
    Matrix indexH=probl->index.getH(joints*CTRL_DEG2RAD);
    printf("indexH:\n%s\n", indexH.toString().c_str());

    probl->limb.setHN(indexH);
    testLimb.setHN(indexH);

    return true;
}
Ejemplo n.º 20
0
    virtual bool configure(yarp::os::ResourceFinder &rf)
    {
        Property options;
        options.fromString(rf.toString());
        char robotName[255];
        Time::turboBoost();    
        options.put("device", "remote_controlboard");
        if(options.check("robot"))
            strncpy(robotName, options.find("robot").asString().c_str(),sizeof(robotName));
        else
            strncpy(robotName, "icub", sizeof(robotName));
    
        if(options.check("part"))
            {
                char tmp[255];
                sprintf(tmp, "/%s/vc/%s/client",
                        robotName,
                        options.find("part").asString().c_str());
                options.put("local",tmp);
        
                sprintf(tmp, "/%s/%s", 
                        robotName,
                        options.find("part").asString().c_str());
                options.put("remote", tmp);
        
                sprintf(tmp,"/%s/vc/%s/input",
                        robotName,
                        options.find("part").asString().c_str());
                input_port.open(tmp);
            
                options.put("carrier", "mcast");
            
                attach(input_port);
            }
        else
            {
                yError("Please specify part (e.g. --part head)\n");
                return false;
            }
        ////end of the modif////////////
    
        if (!driver.open(options))
            {
                yError("Error opening device, check parameters\n");
                return false;
            }

        ///we start the thread
        int period = CONTROL_RATE;
        if(options.check("period"))
            period = options.find("period").asInt();
        
        yInfo("control rate is %d ms",period);

        if (!options.check("part"))
            return false;
        
        sprintf(partName, "%s", options.find("part").asString().c_str());

        vc=new velControlThread(period);
        vc->init(&driver, partName,
                 robotName);

        vc->start();
        return true;
    }
Ejemplo n.º 21
0
bool Compensator::init(string name, string robotName, string outputPortName, string inputPortName){
    skinPart = SKIN_PART_UNKNOWN;
    bodyPart = BODY_PART_UNKNOWN;

    if (!compensatedTactileDataPort.open(outputPortName.c_str())) {
	    stringstream msg; msg<< "Unable to open output port "<< outputPortName;
        sendInfoMsg(msg.str());
	    return false;  // unable to open
    }

    Property options;
    stringstream localPortName;
    localPortName<< "/"<< name<< "/input";
    options.put("robot",  robotName.c_str());
    options.put("local",  localPortName.str().c_str());
    options.put("remote",  inputPortName.c_str());
    options.put("device", "analogsensorclient");
     
    // create a new device driver
    tactileSensorDevice = new PolyDriver(options);
    if (!tactileSensorDevice->isValid()){
	    sendInfoMsg("Device not available.\n");
	    //printf("%s", Drivers::factory().toString().c_str());
	    return false;
    }
    // open the sensor interface	
    bool ok = tactileSensorDevice->view(tactileSensor);
    if (!ok) {
	    sendInfoMsg("Problems acquiring interfaces");
	    return false;
    }

    // (temp) open port to read skin data with timestamp (because device driver doesn't provide timestamps)
    localPortName<< "_temp";
    if(!inputPort.open(localPortName.str().c_str()))
    {
        stringstream msg; msg<< "Unable to open input data port "<< localPortName.str();
        sendInfoMsg(msg.str());
	    return false;
    }
    if( !Network::connect(inputPortName.c_str(), localPortName.str().c_str()))
    {
        stringstream msg;
        msg<< "Problems trying to connect ports %s and %s."<< inputPortName.c_str()<< localPortName.str().c_str();
        sendInfoMsg(msg.str());
        return false;
    }
    
    int getChannelsCounter = 0;
    skinDim = tactileSensor->getChannels();
    while(skinDim<=0){
        // getChannels() returns 0 if it hasn't performed the first reading yet
        // so wait for 1/50 sec, then try again        
        if(++getChannelsCounter==50){
            // after 50 failed trials give up and use the default value
            skinDim = 192;
            sendInfoMsg("Error reading the number of channels of the port. Using 192 as default value.");
            break;
        }
        Time::delay(0.02);
        skinDim = tactileSensor->getChannels();
	}
    readErrorCounter = 0;
    rawData.resize(skinDim);
    baselines.resize(skinDim);
    touchThresholds.resize(skinDim);
    touchDetected.resize(skinDim);
    subTouchDetected.resize(skinDim);
    touchDetectedFilt.resize(skinDim);
    compensatedData.resize(skinDim);
    compensatedDataOld.resize(skinDim);
    compensatedDataFilt.resize(skinDim);
    taxelPos.resize(skinDim, zeros(3));
    taxelOri.resize(skinDim, zeros(3));
	taxelPoseConfidence.resize(skinDim,0.0);
    maxNeighDist = MAX_NEIGHBOR_DISTANCE;
    // by default every taxel is neighbor with all the other taxels
    list<int> defaultNeighbors(skinDim);
    int i=0;
    for(list<int>::iterator it=defaultNeighbors.begin();it!=defaultNeighbors.end();it++, i++) 
        *it = i;
    neighborsXtaxel.resize(skinDim, defaultNeighbors);

    // test read to check if the skin is broken (all taxel output is 0)
    if(robotName!="icubSim" && readInputData(compensatedData)){
        bool skinBroken = true;
        for(unsigned int i=0; i<skinDim; i++){
            if(compensatedData[i]!=0.0){
                skinBroken = false;
                break;
            }
        }
        if(skinBroken)
            sendInfoMsg("The output of all the taxels is 0. Probably there is a hardware problem.");
        return !skinBroken;
    }

    return true;
}
Ejemplo n.º 22
0
QString TabletHandler::getProperty(const QString &tabletId, const DeviceType& deviceType, const Property& property) const
{
    Q_D( const TabletHandler );

    if( !d->tabletBackendList.contains(tabletId) || d->tabletBackendList.value(tabletId) == NULL) {
        kError() << QString::fromLatin1("Unable to get property '%1' from device '%2' as no device is currently available!").arg(property.key()).arg(deviceType.key());
        return QString();
    }

    return d->tabletBackendList.value(tabletId)->getProperty( deviceType, property );
}
Ejemplo n.º 23
0
void CONFIG::Run(void) {
	static const char* const params[] = {
		"-r", "-wcp", "-wcd", "-wc", "-writeconf", "-l", "-rmconf",
		"-h", "-help", "-?", "-axclear", "-axadd", "-axtype", "-get", "-set",
		"-writelang", "-wl", "-securemode", "" };
	enum prs {
		P_NOMATCH, P_NOPARAMS, // fixed return values for GetParameterFromList
		P_RESTART,
		P_WRITECONF_PORTABLE, P_WRITECONF_DEFAULT, P_WRITECONF, P_WRITECONF2,
		P_LISTCONF,	P_KILLCONF,
		P_HELP, P_HELP2, P_HELP3,
		P_AUTOEXEC_CLEAR, P_AUTOEXEC_ADD, P_AUTOEXEC_TYPE,
		P_GETPROP, P_SETPROP,
		P_WRITELANG, P_WRITELANG2,
		P_SECURE
	} presult = P_NOMATCH;
	
	bool first = true;
	std::vector<std::string> pvars;
	// Loop through the passed parameters
	while(presult != P_NOPARAMS) {
		presult = (enum prs)cmd->GetParameterFromList(params, pvars);
		switch(presult) {
		
		case P_RESTART:
			if (securemode_check()) return;
			if (pvars.size() == 0) restart_program(control->startup_params);
			else {
				std::vector<std::string> restart_params;
				restart_params.push_back(control->cmdline->GetFileName());
				for(size_t i = 0; i < pvars.size(); i++) {
					restart_params.push_back(pvars[i]);
					if (pvars[i].find(' ') != std::string::npos) {
						pvars[i] = "\""+pvars[i]+"\""; // add back spaces
					}
				}
				// the rest on the commandline, too
				cmd->FillVector(restart_params);
				restart_program(restart_params);
			}
			return;
		
		case P_LISTCONF: {
			Bitu size = control->configfiles.size();
			std::string config_path;
			Cross::GetPlatformConfigDir(config_path);
			WriteOut(MSG_Get("PROGRAM_CONFIG_CONFDIR"), VERSION,config_path.c_str());
			if (size==0) WriteOut(MSG_Get("PROGRAM_CONFIG_NOCONFIGFILE"));
			else {
				WriteOut(MSG_Get("PROGRAM_CONFIG_PRIMARY_CONF"),control->configfiles.front().c_str());
				if (size > 1) {
					WriteOut(MSG_Get("PROGRAM_CONFIG_ADDITIONAL_CONF"));
					for(Bitu i = 1; i < size; i++)
						WriteOut("%s\n",control->configfiles[i].c_str());
				}
			}
			if (control->startup_params.size() > 0) {
				std::string test;
				for(size_t k = 0; k < control->startup_params.size(); k++)
					test += control->startup_params[k] + " ";
				WriteOut(MSG_Get("PROGRAM_CONFIG_PRINT_STARTUP"), test.c_str());
			}
			break;
		}
		case P_WRITECONF: case P_WRITECONF2:
			if (securemode_check()) return;
			if (pvars.size() > 1) return;
			else if (pvars.size() == 1) {
				// write config to specific file, except if it is an absolute path
				writeconf(pvars[0], !Cross::IsPathAbsolute(pvars[0]));
			} else {
				// -wc without parameter: write primary config file
				if (control->configfiles.size()) writeconf(control->configfiles[0], false);
				else WriteOut(MSG_Get("PROGRAM_CONFIG_NOCONFIGFILE"));
			}
			break;
		case P_WRITECONF_DEFAULT: {
			// write to /userdir/dosbox0.xx.conf
			if (securemode_check()) return;
			if (pvars.size() > 0) return;
			std::string confname;
			Cross::GetPlatformConfigName(confname);
			writeconf(confname, true);
			break;
		}
		case P_WRITECONF_PORTABLE:
			if (securemode_check()) return;
			if (pvars.size() > 1) return;
			else if (pvars.size() == 1) {
				// write config to startup directory
				writeconf(pvars[0], false);
			} else {
				// -wcp without parameter: write dosbox.conf to startup directory
				if (control->configfiles.size()) writeconf(std::string("dosbox.conf"), false);
				else WriteOut(MSG_Get("PROGRAM_CONFIG_NOCONFIGFILE"));
			}
			break;

		case P_NOPARAMS:
			if (!first) break;

		case P_NOMATCH:
			WriteOut(MSG_Get("PROGRAM_CONFIG_USAGE"));
			return;

		case P_HELP: case P_HELP2: case P_HELP3: {
			switch(pvars.size()) {
			case 0:
				WriteOut(MSG_Get("PROGRAM_CONFIG_USAGE"));
				return;
			case 1: {
				if (!strcasecmp("sections",pvars[0].c_str())) {
					// list the sections
					WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_SECTLIST"));
					Bitu i = 0;
					while(true) {
						Section* sec = control->GetSection(i++);
						if (!sec) break;
						WriteOut("%s\n",sec->GetName());
					}
					return;
				}
				// if it's a section, leave it as one-param
				Section* sec = control->GetSection(pvars[0].c_str());
				if (!sec) {
					// could be a property
					sec = control->GetSectionFromProperty(pvars[0].c_str());
					if (!sec) {
						WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR"));
						return;
					}
					pvars.insert(pvars.begin(),std::string(sec->GetName()));
				}
				break;
			}
			case 2: {
				// sanity check
				Section* sec = control->GetSection(pvars[0].c_str());
				Section* sec2 = control->GetSectionFromProperty(pvars[1].c_str());
				if (sec != sec2) {
					WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR"));
				}
				break;
			}
			default:
				WriteOut(MSG_Get("PROGRAM_CONFIG_USAGE"));
				return;
			}	
			// if we have one value in pvars, it's a section
			// two values are section + property
			Section* sec = control->GetSection(pvars[0].c_str());
			if (sec==NULL) {
				WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR"));
				return;
			}
			Section_prop* psec = dynamic_cast <Section_prop*>(sec);
			if (psec==NULL) {
				// failed; maybe it's the autoexec section?
				Section_line* pline = dynamic_cast <Section_line*>(sec);
				if (pline==NULL) E_Exit("Section dynamic cast failed.");

				WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_LINEHLP"),
					pline->GetName(),
					// this is 'unclean' but the autoexec section has no help associated
					MSG_Get("AUTOEXEC_CONFIGFILE_HELP"),
					pline->data.c_str() );
				return;
			} 
			if (pvars.size()==1) {
				size_t i = 0;
				WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_SECTHLP"),pvars[0].c_str());
				while(true) {
					// list the properties
					Property* p = psec->Get_prop(i++);
					if (p==NULL) break;
					WriteOut("%s\n", p->propname.c_str());
				}
			} else {
				// find the property by it's name
				size_t i = 0;
				while (true) {
					Property *p = psec->Get_prop(i++);
					if (p==NULL) break;
					if (!strcasecmp(p->propname.c_str(),pvars[1].c_str())) {
						// found it; make the list of possible values
						std::string propvalues;
						std::vector<Value> pv = p->GetValues();
						
						if (p->Get_type()==Value::V_BOOL) {
							// possible values for boolean are true, false
							propvalues += "true, false";
						} else if (p->Get_type()==Value::V_INT) {
							// print min, max for integer values if used
							Prop_int* pint = dynamic_cast <Prop_int*>(p);
							if (pint==NULL) E_Exit("Int property dynamic cast failed.");
							if (pint->getMin() != pint->getMax()) {
								std::ostringstream oss;
								oss << pint->getMin();
								oss << "..";
								oss << pint->getMax();
								propvalues += oss.str();
							}
						}
						for(Bitu k = 0; k < pv.size(); k++) {
							if (pv[k].ToString() =="%u")
								propvalues += MSG_Get("PROGRAM_CONFIG_HLP_POSINT");
							else propvalues += pv[k].ToString();
							if ((k+1) < pv.size()) propvalues += ", ";
						}

						WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_PROPHLP"),
							p->propname.c_str(),
							sec->GetName(),
							p->Get_help(),propvalues.c_str(),
							p->Get_Default_Value().ToString().c_str(),
							p->GetValue().ToString().c_str());
						// print 'changability'
						if (p->getChange()==Property::Changeable::OnlyAtStart) {
							WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_NOCHANGE"));
						}
						return;
					}
				}
				break;
			}
			return;
		}
		case P_AUTOEXEC_CLEAR: {
			Section_line* sec = dynamic_cast <Section_line*>
				(control->GetSection(std::string("autoexec")));
			sec->data.clear();
			break;
		}
		case P_AUTOEXEC_ADD: {
			if (pvars.size() == 0) {
				WriteOut(MSG_Get("PROGRAM_CONFIG_MISSINGPARAM"));
				return;
			}
			Section_line* sec = dynamic_cast <Section_line*>
				(control->GetSection(std::string("autoexec")));

			for(Bitu i = 0; i < pvars.size(); i++) sec->HandleInputline(pvars[i]);
			break;
		}
		case P_AUTOEXEC_TYPE: {
			Section_line* sec = dynamic_cast <Section_line*>
				(control->GetSection(std::string("autoexec")));
			WriteOut("\n%s",sec->data.c_str());
			break;
		}
		case P_GETPROP: {
			// "section property"
			// "property"
			// "section"
			// "section" "property"
			if (pvars.size()==0) {
				WriteOut(MSG_Get("PROGRAM_CONFIG_GET_SYNTAX"));
				return;
			}
			std::string::size_type spcpos = pvars[0].find_first_of(' ');
			// split on the ' '
			if (spcpos != std::string::npos) {
				pvars.insert(++pvars.begin(),pvars[0].substr(spcpos+1));
				pvars[0].erase(spcpos);
			}
			switch(pvars.size()) {
			case 1: {
				// property/section only
				// is it a section?
				Section* sec = control->GetSection(pvars[0].c_str());
				if (sec) {
					// list properties in section
					Bitu i = 0;
					Section_prop* psec = dynamic_cast <Section_prop*>(sec);
					if (psec==NULL) {
						// autoexec section
						Section_line* pline = dynamic_cast <Section_line*>(sec);
						if (pline==NULL) E_Exit("Section dynamic cast failed.");

						WriteOut("%s",pline->data.c_str());
						break;
					}
					while(true) {
						// list the properties
						Property* p = psec->Get_prop(i++);
						if (p==NULL) break;
						WriteOut("%s=%s\n", p->propname.c_str(),
							p->GetValue().ToString().c_str());
					}
				} else {
					// no: maybe it's a property?
					sec = control->GetSectionFromProperty(pvars[0].c_str());
					if (!sec) {
						WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR"));
						return;
					}
					// it's a property name
					std::string val = sec->GetPropValue(pvars[0].c_str());
					WriteOut("%s",val.c_str());
				}
				break;
			}
			case 2: {
				// section + property
				Section* sec = control->GetSection(pvars[0].c_str());
				if (!sec) {
					WriteOut(MSG_Get("PROGRAM_CONFIG_SECTION_ERROR"));
					return;
				}
				std::string val = sec->GetPropValue(pvars[1].c_str());
				if (val == NO_SUCH_PROPERTY) {
					WriteOut(MSG_Get("PROGRAM_CONFIG_NO_PROPERTY"),
						pvars[1].c_str(),pvars[0].c_str());   
					return;
				}
				WriteOut("%s",val.c_str());
				break;
			}
			default:
				WriteOut(MSG_Get("PROGRAM_CONFIG_GET_SYNTAX"));
				return;
			}
			return;
		}
		case P_SETPROP:	{
			// Code for the configuration changes
			// Official format: config -set "section property=value"
			// Accepted: with or without -set, 
			// "section property value"
			// "section property=value"
			// "property" "value"
			// "section" "property=value"
			// "section" "property=value" "value" "value" ...
			// "section" "property" "value" "value" ...
			// "section property" "value" "value" ...
			// "property" "value" "value" ...
			// "property=value" "value" "value" ...

			if (pvars.size()==0) {
				WriteOut(MSG_Get("PROGRAM_CONFIG_SET_SYNTAX"));
				return;
			}

			// add rest of command
			std::string rest;
			if (cmd->GetStringRemain(rest)) pvars.push_back(rest);

			// attempt to split off the first word
			std::string::size_type spcpos = pvars[0].find_first_of(' ');
			std::string::size_type equpos = pvars[0].find_first_of('=');

			if ((equpos != std::string::npos) && 
				((spcpos == std::string::npos) || (equpos < spcpos))) {
				// If we have a '=' possibly before a ' ' split on the =
				pvars.insert(++pvars.begin(),pvars[0].substr(equpos+1));
				pvars[0].erase(equpos);
				// As we had a = the first thing must be a property now
				Section* sec=control->GetSectionFromProperty(pvars[0].c_str());
				if (sec) pvars.insert(pvars.begin(),std::string(sec->GetName()));
				else {
					WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR"));
					return;
				}
				// order in the vector should be ok now
			} else {
				if ((spcpos != std::string::npos) &&
					((equpos == std::string::npos) || (spcpos < equpos))) {
					// ' ' before a possible '=', split on the ' '
					pvars.insert(++pvars.begin(),pvars[0].substr(spcpos+1));
					pvars[0].erase(spcpos);
				}
				// check if the first parameter is a section or property
				Section* sec = control->GetSection(pvars[0].c_str());
				if (!sec) {
					// not a section: little duplicate from above
					Section* sec=control->GetSectionFromProperty(pvars[0].c_str());
					if (sec) pvars.insert(pvars.begin(),std::string(sec->GetName()));
					else {
						WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR"));
						return;
					}
				} else {
					// first of pvars is most likely a section, but could still be gus
					// have a look at the second parameter
					if (pvars.size() < 2) {
						WriteOut(MSG_Get("PROGRAM_CONFIG_SET_SYNTAX"));
						return;
					}
					std::string::size_type spcpos2 = pvars[1].find_first_of(' ');
					std::string::size_type equpos2 = pvars[1].find_first_of('=');
					if ((equpos2 != std::string::npos) && 
						((spcpos2 == std::string::npos) || (equpos2 < spcpos2))) {
						// split on the =
						pvars.insert(pvars.begin()+2,pvars[1].substr(equpos2+1));
						pvars[1].erase(equpos2);
					} else if ((spcpos2 != std::string::npos) &&
						((equpos2 == std::string::npos) || (spcpos2 < equpos2))) {
						// split on the ' '
						pvars.insert(pvars.begin()+2,pvars[1].substr(spcpos2+1));
						pvars[1].erase(spcpos2);
					}
					// is this a property?
					Section* sec2 = control->GetSectionFromProperty(pvars[1].c_str());
					if (!sec2) {
						// not a property, 
						Section* sec3 = control->GetSectionFromProperty(pvars[0].c_str());
						if (sec3) {
							// section and property name are identical
							pvars.insert(pvars.begin(),pvars[0]);
						} // else has been checked above already
					}
				}
			}
			if(pvars.size() < 3) {
				WriteOut(MSG_Get("PROGRAM_CONFIG_SET_SYNTAX"));
				return;
			}
			// check if the property actually exists in the section
			Section* sec2 = control->GetSectionFromProperty(pvars[1].c_str());
			if (!sec2) {
				WriteOut(MSG_Get("PROGRAM_CONFIG_NO_PROPERTY"),
					pvars[1].c_str(),pvars[0].c_str());
				return;
			}
			// Input has been parsed (pvar[0]=section, [1]=property, [2]=value)
			// now execute
			Section* tsec = control->GetSection(pvars[0]);
			std::string value;
			value += pvars[2];
			for(Bitu i = 3; i < pvars.size(); i++) value += (std::string(" ") + pvars[i]);
			std::string inputline = pvars[1] + "=" + value;
			
			tsec->ExecuteDestroy(false);
			bool change_success = tsec->HandleInputline(inputline.c_str());
			if (!change_success) WriteOut(MSG_Get("PROGRAM_CONFIG_VALUE_ERROR"),
				value.c_str(),pvars[1].c_str());
			tsec->ExecuteInit(false);
			return;
		}
		case P_WRITELANG: case P_WRITELANG2:
			// In secure mode don't allow a new languagefile to be created
			// Who knows which kind of file we would overwrite.
			if (securemode_check()) return;
			if (pvars.size() < 1) {
				WriteOut(MSG_Get("PROGRAM_CONFIG_MISSINGPARAM"));
				return;
			}
			if (!MSG_Write(pvars[0].c_str())) {
				WriteOut(MSG_Get("PROGRAM_CONFIG_FILE_ERROR"),pvars[0].c_str());
				return;
			}
			break;

		case P_SECURE:
			// Code for switching to secure mode
			control->SwitchToSecureMode();
			WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_ON"));
			return;

		default:
			E_Exit("bug");
			break;
		}
		first = false;
	}
	return;
}
Ejemplo n.º 24
0
    bool configureFromPolicy(Property& config, const char *policyName) {
        this->policyName = policyName;
        if (verbose) {
            fprintf(RTARGET,"||| policy set to %s\n", policyName);
        }
        String rootVar = policyName;
        const char *result =
            yarp::os::getenv(rootVar.c_str());
        bool needEnv = false;
#ifdef YARP2_WINDOWS
        needEnv = true;
#endif
        if (result==NULL) {
            root = "";
        } else {
            root = result;
        }
        root = config.check(policyName,Value(root)).asString().c_str();
        if (root == "") {
            if (verbose||needEnv) {
                fprintf(RTARGET,"||| environment variable %s not set\n",
                        rootVar.c_str());
            }
            if (needEnv) {
                return false;
            }
        } else {
            if (verbose) {
                fprintf(RTARGET,"||| %s: %s\n",
                        rootVar.c_str(),root.c_str());
            }
        }
        String checked = "";
        String userConfig = expandUserFileName(ConstString(policyName) + ".ini").c_str();
        String rootConfig = String(root.c_str()) + "/" + policyName + ".ini";
        String altConfig = String("/etc/yarp/policies/") + policyName + ".ini";
#ifndef YARP_NO_DEPRECATED
        String deprecatedConfig = String("/etc/") + policyName + ".ini"; // FIXME Deprecated
#endif // YARP_NO_DEPRECATED
        bool ok = false;
        if (!ok) {
            if (root!="") {
                if (verbose) {
                    fprintf(RTARGET,"||| loading policy from %s\n",
                            rootConfig.c_str());
                }
                checked += " " + rootConfig;
                ok = config.fromConfigFile(rootConfig.c_str(),false);
            }
        }
        if (!needEnv) {
            if (!ok) {
                if (verbose) {
                    fprintf(RTARGET,"||| loading policy from %s\n",
                            userConfig.c_str());
                }
                checked += " " + userConfig;
                ok = config.fromConfigFile(userConfig.c_str(),false);
            }
            if (!ok) {
                if (verbose) {
                    fprintf(RTARGET,"||| loading policy from %s\n",
                            altConfig.c_str());
                }
                checked += " " + altConfig;
                ok = config.fromConfigFile(altConfig.c_str(),false);
            }
#ifndef YARP_NO_DEPRECATED
            if (!ok) {
                if (verbose) {
                    fprintf(RTARGET,"||| loading policy from %s\n",
                            deprecatedConfig.c_str());
                }
                checked += " " + deprecatedConfig;
                ok = config.fromConfigFile(deprecatedConfig.c_str(),false);
                if (ok) {
                    fprintf(RTARGET, "||| WARNING: Loading policies from /etc/ is deprecated,\n"
                                     "|||          you should move them in /etc/yarp/policies/ .\n");
                }
            }
#endif // YARP_NO_DEPRECATED
            if (!ok) {
                altConfig = String("/usr/local/etc/") + policyName + ".ini";
                if (verbose) {
                    fprintf(RTARGET,"||| loading policy from %s\n",
                            altConfig.c_str());
                }
                checked += " " + altConfig;
                ok = config.fromConfigFile(altConfig.c_str(),false);
            }
        }
        /*
          // this would violate the spec
        if (!ok) {
            if (verbose) {
                fprintf(RTARGET,"||| in desperation, loading policy from %s\n",
                        policyName);
            }
            checked += " ";
            checked += policyName;
            ok = config.fromConfigFile(policyName);
        }
        */
        if (!ok) {
            if (!quiet) {
                fprintf(RTARGET,"||| failed to load policy from%s\n",
                        checked.c_str());
            }
            return false;
        }

        // currently only support "capability" style configuration
        if (config.check("style",Value("")).asString()!="capability") {
            if (!quiet) {
                fprintf(RTARGET,"||| policy \"style\" can currently only be \"capability\"\n");
            }
            return false;
        }

        return true;
    }
    void SkeletonAnimationManager::_animationsHaveLoaded(void* params)
    {
		FileManager::ReadFileCallbackParameters* rcp = (FileManager::ReadFileCallbackParameters*)params;
		
        if(rcp->result == ResultCode_OK)
        {
            // check to see if there is an animation load list
            std::set< std::string >* animationsToLoad = 0;
            
            if( rcp->userData.keyExists( ANIMATION_LIST_POINTER_KEY ) )
            {
                const Property* prop = rcp->userData.getValueForKey( ANIMATION_LIST_POINTER_KEY );
                animationsToLoad = prop->asPointer< std::set< std::string> >();
            }
            
            XMLDocument xmlDoc(rcp->buffer, rcp->length, "Animations");
            
            if(xmlDoc)
            {
                Property property;                
                if(xmlDoc.getRootIterator().getAttribute( "curveCollection", property ) )
                {
                    setCurveCollectionName( property.asString() );
                    if( animationsToLoad )
                    {
                        CurveManager::getManager().loadCurveCollection( getCurveCollectionName(),
                                                                        CallbackPtr(),
                                                                        *animationsToLoad );
                    }
                    else
                    {
                        CurveManager::getManager().loadCurveCollection(getCurveCollectionName());
                    }
                }
                
                XMLDocument::NamedIterator animationIt = xmlDoc.getNamedIteratorTo( "Animation" );
                
                while( animationIt )
                {
                    // we need to compare the animation name to the list of animations we want to
                    // export to see if we should export it...
                    bool shouldAddAnimation = true;
                    if( animationsToLoad )
                    {
                        Property aniNameProp;
                        animationIt.getAttribute( "name", aniNameProp );
                        std::string animationName = aniNameProp.asString();
                        
                        if( animationsToLoad->find( animationName ) == animationsToLoad->end() )
                        {
                            // this animation isn't in the load list, skip it
                            shouldAddAnimation = false;
                        }
                    }
                    
                    if( shouldAddAnimation )
                    {
                        Animation* ani =
                            Animation::createAnimationFromXmlNode( XMLDocument::Iterator(
                                                                    animationIt.getCurrentNode() ),
                                                                   mSkeleton );
                        
                        addAnimation(ani);
                    }
                    
                    ++animationIt;
                }
            }
            
            // we created a dynamic copy of the set because we need it to last through functions,
            // so we pass it through by pointer and delete it on this end
            if( animationsToLoad )
            {
                delete animationsToLoad;
            }
            
            delete [] rcp->buffer;
        }
    }
Ejemplo n.º 26
0
    bool configure(Property& config, const char *policyName, int argc,
                   char *argv[], bool skip) {
        Property p;
        p.fromCommand(argc,argv,skip);

        //printf("SETTINGS: %s\n", p.toString().c_str());

        if (p.check("verbose")) {
            setVerbose(p.check("verbose",Value(1)).asInt());
        }

        ConstString name = "";
        if (policyName!=NULL) {
            name = policyName;
        }
        name = p.check("policy",Value(name.c_str())).asString();
        if (name=="") {
            const char *result =
                yarp::os::getenv("YARP_POLICY");
            if (result!=NULL) {
                if (verbose) {
                    fprintf(RTARGET,"||| Read policy from YARP_POLICY\n");
                }
                name = result;
            }
        }
        bool skip_policy = false;
        if (name=="") {
            if (verbose) {
                fprintf(RTARGET,"||| no policy found\n");
            }
            skip_policy = true;
        }
        if (name=="none") {
            skip_policy = true;
        }

        if (!skip_policy) {
            config.fromString(p.toString().c_str(),false);
            bool result = configureFromPolicy(config,name.c_str());
            if (!result) return result;
        }

        if (p.check("context")) {
            clearAppNames();
            ConstString c = p.check("context",Value("default")).asString();
            addAppName(c.c_str());
            if (verbose) {
                fprintf(RTARGET,"||| added context %s\n",
                        c.c_str());
            }
        }

        config.fromCommand(argc,argv,skip,false);
        if (config.check("from")) {
            ConstString from = config.check("from",
                                            Value("config.ini")).toString();
            if (verbose) {
                fprintf(RTARGET,"||| default config file specified as %s\n",
                        from.c_str());
            }
            ConstString corrected = findFile(config,from.c_str());
            if (corrected!="") {
                from = corrected;
            }
            ConstString fromPath = extractPath(from.c_str());
            configFilePath = fromPath;
            config.fromConfigFile(from,false);
            config.fromCommand(argc,argv,skip,false);
        }
        return true;
    }
Ejemplo n.º 27
0
void UPnpCDSVideo::PopulateArtworkURIS(CDSObject* pItem, int nVidID,
                                       const QUrl& URIBase)
{
    QUrl artURI = URIBase;
    artURI.setPath("Content/GetVideoArtwork");
    artURI.addQueryItem("Id", QString::number(nVidID));

    // Prefer JPEG over PNG here, although PNG is allowed JPEG probably
    // has wider device support and crucially the filesizes are smaller
    // which speeds up loading times over the network

    // We MUST include the thumbnail size, but since some clients may use the
    // first image they see and the thumbnail is tiny, instead return the
    // medium first. The large could be very large, which is no good if the
    // client is pulling images for an entire list at once!

    // Thumbnail
    // At least one albumArtURI must be a ThumbNail (TN) no larger
    // than 160x160, and it must also be a jpeg
    QUrl thumbURI = artURI;
    if (pItem->m_sClass == "object.item.videoItem") // Show screenshot for TV, coverart for movies
        thumbURI.addQueryItem("Type", "screenshot");
    else
        thumbURI.addQueryItem("Type", "coverart");
    thumbURI.addQueryItem("Width", "160");
    thumbURI.addQueryItem("Height", "160");

    // Small
    // Must be no more than 640x480
    QUrl smallURI = artURI;
    smallURI.addQueryItem("Type", "coverart");
    smallURI.addQueryItem("Width", "640");
    smallURI.addQueryItem("Height", "480");

    // Medium
    // Must be no more than 1024x768
    QUrl mediumURI = artURI;
    mediumURI.addQueryItem("Type", "coverart");
    mediumURI.addQueryItem("Width", "1024");
    mediumURI.addQueryItem("Height", "768");

    // Large
    // Must be no more than 4096x4096 - for our purposes, just return
    // a fullsize image
    QUrl largeURI = artURI;
    largeURI.addQueryItem("Type", "fanart");

    QList<Property*> propList = pItem->GetProperties("albumArtURI");
    if (propList.size() >= 4)
    {
        Property *pProp = propList.at(0);
        if (pProp)
        {
            pProp->SetValue(mediumURI.toEncoded());
            pProp->AddAttribute("dlna:profileID", "JPEG_MED");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        pProp = propList.at(1);
        if (pProp)
        {

            pProp->SetValue(thumbURI.toEncoded());
            pProp->AddAttribute("dlna:profileID", "JPEG_TN");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        pProp = propList.at(2);
        if (pProp)
        {
            pProp->SetValue(smallURI.toEncoded());
            pProp->AddAttribute("dlna:profileID", "JPEG_SM");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        pProp = propList.at(3);
        if (pProp)
        {
            pProp->SetValue(largeURI.toEncoded());
            pProp->AddAttribute("dlna:profileID", "JPEG_LRG");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }
    }

    if (pItem->m_sClass.startsWith("object.item.videoItem"))
    {
        QString sProtocol;

        sProtocol = DLNA::ProtocolInfoString(UPNPProtocol::kHTTP,
                                             "image/jpeg", QSize(1024, 768));
        pItem->AddResource( sProtocol, mediumURI.toEncoded());

        sProtocol = DLNA::ProtocolInfoString(UPNPProtocol::kHTTP,
                                             "image/jpeg", QSize(160, 160));
        pItem->AddResource( sProtocol, thumbURI.toEncoded());

        sProtocol = DLNA::ProtocolInfoString(UPNPProtocol::kHTTP,
                                             "image/jpeg", QSize(640, 480));
        pItem->AddResource( sProtocol, smallURI.toEncoded());

        sProtocol = DLNA::ProtocolInfoString(UPNPProtocol::kHTTP,
                                             "image/jpeg", QSize(1920, 1080)); // Not the actual res, we don't know that
        pItem->AddResource( sProtocol, largeURI.toEncoded());
    }
}
Ejemplo n.º 28
0
 bool setDefault(Property& config, const char *key, const char *val) {
     if (!config.check(key)) {
         config.put(key,val);
     }
     return true;
 }
void ItemLibraryEntry::addProperty(QString &name, QString &type, QString &value)
{
    Property property;
    property.set(name, type, value);
    addProperty(property);
}
Ejemplo n.º 30
0
int main(int argc, char **argv)
{
    Network yarp;

    printf("Going to stress rpc connections to the robot\n");
    printf("Run as --id unique-id\n");
    printf("Optionally:\n");
    printf("--part robot-part\n");
    printf("--prot protocol\n");
    printf("--time dt (seconds)\n");
    printf("--robot name \n");

    Property parameters;
    parameters.fromCommand(argc, argv);

    ConstString part=parameters.find("part").asString();
    int id=parameters.find("id").asInt();
    double time=0;
    if (parameters.check("time"))
        {
            time=parameters.find("time").asDouble();
        }
    else
        time=-1;

    ConstString protocol;
    if (parameters.check("prot"))
    {
        protocol=parameters.find("prot").asString();
    }
    else
        protocol="tcp";

    ConstString rname;
    if (parameters.check("robot"))
    {
        rname=parameters.find("robot").asString();
    }
    else
        rname="controlboard";

    PolyDriver dd;
    Property p;

    Random::seed((unsigned int)Time::now());
     
    string remote=string("/")+rname.c_str();
    if (part!="")
        {
            remote+=string("/");
            remote+=part;
        }
    string local=string("/")+string(rname.c_str());
    if (part!="")
        {
            local+=string("/");
            local+=part;
        }
    local+=string("/stress");

    stringstream lStream; 
    lStream << id;
    local += lStream.str();

    p.put("device", "remote_controlboard");
    p.put("local", local.c_str());
    p.put("remote", remote.c_str());
    p.put("carrier", protocol.c_str());
    dd.open(p);
    
    if (!dd.isValid())
    {
        fprintf(stderr, "Error, could not open controlboard\n");
        return -1;
    }

    IEncoders *ienc;
    IPositionControl *ipos;
    IAmplifierControl *iamp;
    IPidControl *ipid;
    IControlLimits *ilim;
    IControlCalibration2 *ical;

    dd.view(ienc);
    dd.view(ipos);
    dd.view(iamp);
    dd.view(ipid);
    dd.view(ilim);
    dd.view(ical);
    
    int c=100;
    int nj;
    Vector encoders;
    ienc->getAxes(&nj);
    encoders.resize(nj);

    int count=0;
    bool done=false;
    double startT=Time::now();
    double now=0;
    while((!done) || (time==-1))
        {
            count++;
            double v;
            int jj=0;
            
            for(jj=0; jj<nj; jj++)
                {
                    //    ienc->getEncoder(jj, encoders.data()+jj);
                    //    iamp->enableAmp(jj);
                    //    ilim->setLimits(jj, 0, 0);
                    //    double max;
                    //    double min;
                    //    ilim->getLimits(jj, &min, &max);
                    fprintf(stderr, ".");
                    // Pid pid;
                    // ipid->getPid(jj, &pid);
                    bool done;
                    ipos->checkMotionDone(jj, &done);
                    fprintf(stderr, "#\n");
                }

            fprintf(stderr, "%u\n", count);

            Time::delay(0.1);

            now=Time::now();
            if ((now-startT)>time)
                done=true;
        }

    printf("bye bye from %d\n", id);
    
    return 0;
}