Example #1
0
File: test.cpp Project: acat/emule
bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename)
{
	FileSource pubFile(pubFilename, true, new HexDecoder);
	RSASSA_PKCS1v15_SHA_Verifier pub(pubFile);

	FileSource signatureFile(signatureFilename, true, new HexDecoder);
	if (signatureFile.MaxRetrievable() != pub.SignatureLength())
		return false;
	SecByteBlock signature(pub.SignatureLength());
	signatureFile.Get(signature, signature.size());

	VerifierFilter *verifierFilter = new VerifierFilter(pub);
	verifierFilter->Put(signature, pub.SignatureLength());
	FileSource f(messageFilename, true, verifierFilter);

	return verifierFilter->GetLastResult();
}
Example #2
0
int
main(int argc, char** argv)
{
  qm::init("test_pub");
  
  qm::Publisher pub("chatter", true);
  
  for (int i = 0; i < 20; ++i) {
    if (!qm::ok()) break;
    std::stringstream ss;  
    ss << "Hello world: " << i << std::endl;
    pub.publish(ss.str());    
    std::cout << ss.str();
    std::this_thread::sleep_for(std::chrono::seconds(1));
  }
  return 0;
}
Example #3
0
void BenchMarkKeyGen(const char *name, AuthenticatedKeyAgreementDomain &d, double timeTotal, bool pc=false)
{
	SecByteBlock priv(d.EphemeralPrivateKeyLength()), pub(d.EphemeralPublicKeyLength());

	const clock_t start = clock();
	unsigned int i;
	double timeTaken;
	for (timeTaken=(double)0, i=0; timeTaken < timeTotal; timeTaken = double(clock() - start) / CLOCK_TICKS_PER_SECOND, i++)
		d.GenerateEphemeralKeyPair(GlobalRNG(), priv, pub);

	OutputResultOperations(name, "Key-Pair Generation", pc, i, timeTaken);

	if (!pc && d.GetMaterial().SupportsPrecomputation())
	{
		d.AccessMaterial().Precompute(16);
		BenchMarkKeyGen(name, d, timeTotal, true);
	}
}
Example #4
0
/*!
 * Внутренняя функция для инициирования публикации изменений на основе состояния сервера.
 */
void Net::pub(ChatChannel channel, const QString &path)
{
  if (!channel)
    return;

  DataCreator *creator = m_creators.get(path);
  if (!creator)
    return;

  NetRecord record;
  if (!creator->create(channel, path, record))
    return;

  if (!record.date)
    record.date = DateTime::utc();

  pub(channel, path, record);
}
  virtual CallResult call()
  {
    VoidConstPtr tracker;
    if (use_tracked_object_)
    {
      tracker = tracked_object_.lock();

      if (!tracker)
      {
        return Invalid;
      }
    }

    SingleSubscriberPublisher pub(sub_link_);
    callback_(pub);

    return Success;
  }
// validate signature signed by someone else
bool CertDecoder::ValidateSignature(SignerList* signers)
{
    assert(signers);

    SignerList::iterator first = signers->begin();
    SignerList::iterator last  = signers->end();

    while (first != last) {
        if ( memcmp(issuerHash_, (*first)->GetHash(), SHA::DIGEST_SIZE) == 0) {
      
            const PublicKey& iKey = (*first)->GetPublicKey();
            Source pub(iKey.GetKey(), iKey.size());
            return ConfirmSignature(pub);
        }   
        ++first;
    }
    return false;
}
/**
 * logic for initializing equipment and PID in the constructors
 * @param thermPins list with formatting of: [ temp busPin ; onewire index ; heating controlPin ; heating powerPin ]
 * NOTE: if a Pin value is not enabled pass -1 as the value for that pin.
 */
void Ohmbrewer::Thermostat::initThermostat(std::list<int>* thermPins){

    // Initialize equipment components
    int size = thermPins->size();
    if (size == 4) {

        thermPins->pop_front();//remove busPIN - unused for now.
        int index = thermPins->front();
        _tempSensor = new TemperatureSensor(new Onewire(index));
        thermPins->pop_front();
        _heatingElm = new HeatingElement(thermPins);
    } else {//not correct number on PINS
        // Publish error
        Ohmbrewer::Publisher::publish_map_t pMap;
        Ohmbrewer::Publisher pub(new String("error_log"), &pMap);
        pMap[String("list_check_thermostat")] = String("improperly formed input - Thermostat(int id, int<list>)");
        pub.publish();

        // Disable and GTFO
        setState(false);
        return;
    }
    _targetTemp = new Temperature();

    // PID set up
    _thermPID = new PID(&input, &output, &setPoint,
                        cons.kP(), cons.kI(), cons.kD(),
                        PID::DIRECT);

    // Initialize the variables we're linked to
    windowStartTime = millis();
    setPoint = _targetTemp->c();
    input = _tempSensor->getTemp()->c();

    // Tell the PID to range between 0 and the full window size
    _thermPID->SetOutputLimits(0, windowSize);

    // Turn the PID on
    _thermPID->SetMode(PID::AUTOMATIC);

    //Timer timer(5000, doPID);
    //_timer = &timer;

}
/**
 * Runs a small global trigger test chain with the different configuration as specified
 * in TriggerConfig.C.
 * \param config  The configuration version to pass to TriggerConfig.C
 * \param usecint  If true then the global trigger component uses CINT to interpret
 *     the code rather than compiling it.
 * \param debug  If true then the global trigger component generates extra debug
 *     statements in the on the fly AliHLTGlobalTriggerImp_*.cxx file.
 * \param numOfEvents  The number of events to run the chain for.
 * \param customClass  Names the custom class that should be loaded from the file
 *     <i>\<customClass\>.cxx</i>. This is useful for debugging only. i.e. you can
 *     edit a generated logic file and test it by hand.
 */
void RunTrigger(int config = 0, bool usecint = false, bool debug = false, int numOfEvents = 8, const char* customClass = NULL)
{
	AliHLTSystem sys;
	sys.ScanOptions("ECS=CTP_TRIGGER_CLASS=00:TRIGGER-ALL:00-01-02-03-04-05-06-07-08-09-10-11-12-13-14-15-16-17");
	sys.LoadComponentLibraries("libAliHLTUtil.so");
	sys.LoadComponentLibraries("libAliHLTTRD.so");
	sys.LoadComponentLibraries("libAliHLTMUON.so");
	sys.LoadComponentLibraries("libAliHLTTrigger.so");
	if (debug)
	{
		AliLog::SetGlobalLogLevel(AliLog::kMaxType);
		sys.SetGlobalLoggingLevel(kHLTLogAll);
	}
	
	TString cmdline = "-datatype ROOTTOBJ 'HLT ' ";
	for (int i = 1; i <= 8; i++)
	{
		if (i > 1) cmdline += " -nextevent";
		cmdline += Form(" -datafile testInputFile%d.root", i);
	}
	AliHLTConfiguration pub("pub", "ROOTFilePublisher", NULL, cmdline.Data());
	
	cmdline = Form("-config $ALICE_ROOT/HLT/trigger/test/TriggerConfig.C(%d)"
		" -includepath $ALICE_ROOT/include -includepath $ALICE_ROOT/HLT/BASE"
		" -includepath $ALICE_ROOT/HLT/trigger -include AliHLTScalars.h",
		config
		);
	if (customClass != NULL) cmdline += Form(" -usecode %s.cxx %s", customClass, customClass);
	if (usecint) cmdline += " -cint";
	if (debug) cmdline += " -debug";
	AliHLTConfiguration proc("proc", "HLTGlobalTrigger", "pub", cmdline.Data());
	
	AliHLTConfiguration sink("sink", "ROOTFileWriter", "proc", "-datafile testOutputFile.root -concatenate-events");
	
	sys.BuildTaskList("sink");
	sys.Run(
		numOfEvents,
		1,   // Stop chain at end of run.
		0x1, // Active CTP trigger mask.
		0,   // Time stamp.
		0    // Event type.
	);
}
Example #9
0
void
O2Profile::
SetRSAKey(const byte *priv, size_t privlen, const byte *pub, size_t publen)
{
	bool valid = false;

	if (priv && privlen && pub && publen) {
		if (privlen == RSA_PRIVKEY_SIZE && publen == RSA_PUBKEY_SIZE) {
			PrivKey.assign(priv, privlen);
			PubKey.assign(pub, publen);
			valid = true;
		}
	}

	if (!valid) {

		CryptoPP::RandomPool randpool;

#ifdef _WIN32   /** windows */
		GUID guid;
		CoCreateGuid(&guid);
		randpool.Put((byte*)&guid, sizeof(GUID));
#else           /** unix */
		boost::uuids::random_generator gen;
		boost::uuids::uuid uuid = gen();
		randpool.Put((byte*)&uuid, sizeof(boost::uuids::uuid));
#endif

		byte tmpPriv[RSA_PRIVKEY_SIZE];
		CryptoPP::RSAES_OAEP_SHA_Decryptor priv(randpool, RSA_KEYLENGTH);
		CryptoPP::ArraySink privArray(tmpPriv, RSA_PRIVKEY_SIZE);
		priv.DEREncode(privArray);
		privArray.MessageEnd();
		PrivKey.assign(tmpPriv, RSA_PRIVKEY_SIZE);

		byte tmpPub[RSA_PUBKEY_SIZE];
		CryptoPP::RSAES_OAEP_SHA_Encryptor pub(priv);
		CryptoPP::ArraySink pubArray(tmpPub, RSA_PUBKEY_SIZE);
		pub.DEREncode(pubArray);
		pubArray.MessageEnd();
		PubKey.assign(tmpPub, RSA_PUBKEY_SIZE);
	}
}
/*
 * ROS rosserial publisher thread.
 */
msg_t rosserial_pub_thread(void * arg) {
	std_msgs::String str_msg;
	ros::Publisher pub("chatter", &str_msg);

	(void) arg;
	chRegSetThreadName("rosserial_pub");

	nh.initNode();
	nh.advertise(pub);

	for (;;) {
		char hello[] = "Hello world!";
		str_msg.data = hello;
		pub.publish(&str_msg);
		nh.spinOnce();
		chThdSleepMilliseconds(500);
	}

	return CH_SUCCESS;
}
/*
 * Publisher threads.
 */
static msg_t PublisherRawThread(void *arg) {
	Middleware & mw = Middleware::instance();
	Node n("pubRaw");
	Publisher<tIMURaw9> pub("IMURaw");
	tIMURaw9 *msg;
	systime_t time;
	static const int period = 10;

	(void) arg;
	chRegSetThreadName("tIMURaw9 pub thread");

	mw.newNode(&n);

	if (! n.advertise(&pub)) {
		mw.delNode(&n);
		return 0;
	}

	time = chTimeNow();
	while (TRUE) {
		msg = pub.alloc();
		if (msg != NULL) {
			rtcanGetTime(&RTCAND1, (rtcan_time_t *)&(msg->timestamp));
			msg->gyro_x = gyro_data.x;
			msg->gyro_y = gyro_data.y;
			msg->gyro_z = gyro_data.z;
			msg->acc_x = acc_data.x;
			msg->acc_y = acc_data.y;
			msg->acc_z = acc_data.z;
			msg->mag_x = mag_data.x;
			msg->mag_y = mag_data.y;
			msg->mag_z = mag_data.z;
			pub.broadcast(msg);
		}

		time += MS2ST(period);
		chThdSleepUntil(time);
	}

	return 0;
}
Example #12
0
void RTPPublisher::removed(const SubscriberStub& sub, const NodeStub& node) {
	RScopeLock lock(_mutex);
	int status;
	std::string ip = sub.getIP();
	uint16_t port = sub.getPort();
	if (!ip.length())		//only use separate subscriber ip (for multicast support etc.), if specified
		ip = node.getIP();

	// do we now about this sub via this node?
	bool subscriptionFound = false;
	std::pair<_domainSubs_t::iterator, _domainSubs_t::iterator> subIter = _domainSubs.equal_range(sub.getUUID());
	while(subIter.first !=  subIter.second) {
		if (subIter.first->second.first.getUUID() ==  node.getUUID()) {
			subscriptionFound = true;
			break;
		}
		subIter.first++;
	}
	if (!subscriptionFound)
		return;

	UM_LOG_INFO("%s: lost a %s subscriber (%s:%u) for channel %s", SHORT_UUID(_uuid).c_str(), sub.isMulticast() ? "multicast" : "unicast", ip.c_str(), port, _channelName.c_str());

	struct libre::sa addr;
	libre::sa_init(&addr, AF_INET);
	if ((status = libre::sa_set_str(&addr, ip.c_str(), port)))
		UM_LOG_WARN("%s: error %d in libre::sa_set_str(%s:%u): %s", SHORT_UUID(_uuid).c_str(), status, ip.c_str(), port, strerror(status));
	else
		_destinations.erase(ip+":"+toStr(port));

	if (_domainSubs.count(sub.getUUID()) ==  1) { // about to vanish
		if (_greeter !=  NULL) {
			Publisher pub(Publisher(StaticPtrCast<PublisherImpl>(shared_from_this())));
			_greeter->farewell(pub, sub);
		}
		_subs.erase(sub.getUUID());
	}

	_domainSubs.erase(subIter.first);
	UMUNDO_SIGNAL(_pubLock);
}
Example #13
0
void RTPPublisher::added(const SubscriberStub& sub, const NodeStub& node) {
	RScopeLock lock(_mutex);
	int status;

	std::string ip = sub.getIP();
	uint16_t port = sub.getPort();
	if (!ip.length())		//only use separate subscriber ip (for multicast support etc.), if specified
		ip = node.getIP();

	// do we already now about this sub via this node?
	std::pair<_domainSubs_t::iterator, _domainSubs_t::iterator> subIter = _domainSubs.equal_range(sub.getUUID());
	while(subIter.first !=  subIter.second) {
		if (subIter.first->second.first.getUUID() ==  node.getUUID())
			return; // we already know about this sub from this node
		subIter.first++;
	}

	UM_LOG_INFO("%s: received a new %s subscriber (%s:%u) for channel %s", SHORT_UUID(_uuid).c_str(), sub.isMulticast() ? "multicast" : "unicast", ip.c_str(), port, _channelName.c_str());

	struct libre::sa addr;
	libre::sa_init(&addr, AF_INET);
	status = libre::sa_set_str(&addr, ip.c_str(), port);

	if (status) {
		UM_LOG_WARN("%s: error %d in libre::sa_set_str(%s:%u): %s", SHORT_UUID(_uuid).c_str(), status, ip.c_str(), port, strerror(status));
	} else {
		_destinations[ip + ":" + toStr(port)] = addr;
	}

	_subs[sub.getUUID()] = sub;
	_domainSubs.insert(std::make_pair(sub.getUUID(), std::make_pair(node, sub)));

	if (_greeter !=  NULL && _domainSubs.count(sub.getUUID()) ==  1) {
		// only perform greeting for first occurence of subscriber
		Publisher pub(StaticPtrCast<PublisherImpl>(shared_from_this()));
		_greeter->welcome(pub, sub);
	}

	UMUNDO_SIGNAL(_pubLock);
}
Example #14
0
void FenetreZoom::TracerZoom(wxPoint p)
{
    if (zoomInactif)
    {
        if (!IsShown())

            return;
        zoomInactif =false;
    }
    ImageInfoCV*	imAcq=fMere->ImAcq();
    wxImage *d=fMere->ImageAffichee();
    wxClientDC hdc(this);

    hdc.SetBrush(*wxBLACK_BRUSH);
    if (facteurZoom!=0)
    {
        if (imAcq && imAcq->cols>0)
        {
            wxRect		src(0,0,imAcq->cols,imAcq->rows);
            wxRect		dst=CalculPosRectDst(src,&p),r=GetClientSize();
            hdc.DrawRectangle(r.GetRight(),r.GetTop(),r.GetRight(),r.GetBottom());
            wxRect		rSrc(src.GetLeft(),src.GetTop(),src.GetRight()-src.GetLeft()+1,src.GetBottom()-src.GetTop()+1);
            wxImage		sousImage=d->GetSubImage(rSrc);
            //	sousImage.SetMask(0);
            wxImage		imageZoom=sousImage.Scale(dst.GetRight()-dst.GetLeft()+1,dst.GetBottom()-dst.GetTop()+1);
            //	imageZoom.SetMask(0);

            wxBitmap	b(imageZoom);
            hdc.DrawBitmap(b,0,0);
            hdc.SetPen(*wxBLACK);
            hdc.DrawRectangle(dst.GetRight(),r.GetTop(),r.GetRight(),r.GetBottom());
            hdc.DrawRectangle(r.GetLeft(),dst.GetBottom(),r.GetRight(),r.GetBottom());
        }
    }
    else
    {
        wxBitmap pub(*d);
        hdc.DrawBitmap(pub,-p.x,-p.y);
    }
}
Example #15
0
int
main(int argc, char* argv[])
{
  if (argc < 2) {
    std::cout << "USAGE:\n\t tspub <sensor-id>" << std::endl;
    return -1;
  }
  int sid = atoi(argv[1]);
  const int N = 100;

  dds::domain::DomainParticipant dp(0);
  dds::topic::Topic<tutorial::TempSensorType> topic(dp, "TTempSensor");
  dds::pub::Publisher pub(dp);
  dds::pub::DataWriter<tutorial::TempSensorType> dw(pub, topic);
    
  const float avgT = 25;
  const float avgH = 0.6;
  const float deltaT = 5;
  const float deltaH = 0.15;
  // Initialize random number generation with a seed
  srandom(clock());
    
  // Write some temperature randomly changing around a set point
  float temp = avgT + ((random()*deltaT)/RAND_MAX);
  float hum  = avgH + ((random()*deltaH)/RAND_MAX);

  tutorial::TempSensorType sensor( sid, temp, hum, tutorial::CELSIUS );

  for (unsigned int i = 0; i < N; ++i) {
    dw.write(sensor);
    std::cout << "DW << " << sensor << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
    temp = avgT + ((random()*deltaT)/RAND_MAX);
    sensor.temp(temp); 
    hum = avgH + ((random()*deltaH)/RAND_MAX);
    sensor.hum(hum);
  }
  return 0;
}
bool ValidateECDSA(const byte *input, const size_t inputLength, const int secLevelIndex)
{
	string description = generateDetailedDescription("ECDSA", securityLevels[secLevelIndex], 1, inputLength);

	// from Sample Test Vectors for P1363
	GF2NT gf2n(191, 9, 0);
	byte a[]="\x28\x66\x53\x7B\x67\x67\x52\x63\x6A\x68\xF5\x65\x54\xE1\x26\x40\x27\x6B\x64\x9E\xF7\x52\x62\x67";
	byte b[]="\x2E\x45\xEF\x57\x1F\x00\x78\x6F\x67\xB0\x08\x1B\x94\x95\xA3\xD9\x54\x62\xF5\xDE\x0A\xA1\x85\xEC";
	EC2N ec(gf2n, PolynomialMod2(a,24), PolynomialMod2(b,24));

	EC2N::Point P;
	ec.DecodePoint(P, (byte *)"\x04\x36\xB3\xDA\xF8\xA2\x32\x06\xF9\xC4\xF2\x99\xD7\xB2\x1A\x9C\x36\x91\x37\xF2\xC8\x4A\xE1\xAA\x0D"
		"\x76\x5B\xE7\x34\x33\xB3\xF9\x5E\x33\x29\x32\xE7\x0E\xA2\x45\xCA\x24\x18\xEA\x0E\xF9\x80\x18\xFB", ec.EncodedPointSize());
	Integer n("40000000000000000000000004a20e90c39067c893bbb9a5H");
	Integer d("340562e1dda332f9d2aec168249b5696ee39d0ed4d03760fH");
	EC2N::Point Q(ec.Multiply(d, P));
	ECDSA<EC2N, SHA>::Signer priv(ec, P, n, d);
	ECDSA<EC2N, SHA>::Verifier pub(priv);

	bool pass = ProfileSignatureValidate(priv, pub, input, inputLength, description);
	assert(pass);

	return pass;
}
Example #17
0
int main(int argc, char* argv[]) {
  try {
    DomainParticipant dp(0);
    Topic<ShapeType> topic(dp, "Circle");
    Publisher pub(dp);
    DataWriter<ShapeType> dw(pub, topic);

    const uint32_t N = 1000;
    uint32_t sleep_time = 300000;
    for (int i = 0; i < N; ++i) {
      ShapeType bc = {"RED", i, i, 60};
      ShapeType rc = {"BLUE", N-i, N-i, 60};
      dw.write(bc);
      // You can also write with streaming operators!
      dw << rc;
      std::cout << "." << std::flush;
      usleep(sleep_time);
    }

  } catch (const dds::core::Exception& e) {
    std::cout << e.what() << std::endl;
  }
  return 0;
}
Example #18
0
void
O2Profile::
SetRSAKey(const byte *priv, size_t privlen, const byte *pub, size_t publen)
{
	bool valid = false;

	if (priv && privlen && pub && publen) {
		if (privlen == RSA_PRIVKEY_SIZE && publen == RSA_PUBKEY_SIZE) {
			PrivKey.assign(priv, privlen);
			PubKey.assign(pub, publen);
			valid = true;
		}
	}

	if (!valid) {
		GUID guid;
		CoCreateGuid(&guid);

		CryptoPP::RandomPool randpool;
		randpool.Put((byte*)&guid, sizeof(GUID));

		byte tmpPriv[RSA_PRIVKEY_SIZE];
		CryptoPP::RSAES_OAEP_SHA_Decryptor priv(randpool, RSA_KEYLENGTH);
		CryptoPP::ArraySink privArray(tmpPriv, RSA_PRIVKEY_SIZE);
		priv.DEREncode(privArray);
		privArray.MessageEnd();
		PrivKey.assign(tmpPriv, RSA_PRIVKEY_SIZE);

		byte tmpPub[RSA_PUBKEY_SIZE];
		CryptoPP::RSAES_OAEP_SHA_Encryptor pub(priv);
		CryptoPP::ArraySink pubArray(tmpPub, RSA_PUBKEY_SIZE);
		pub.DEREncode(pubArray);
		pubArray.MessageEnd();
		PubKey.assign(tmpPub, RSA_PUBKEY_SIZE);
	}
}
void UBYouTubePublisher::uploadVideo(const QString& videoFilePath)
{
    mVideoFilePath = videoFilePath;

    UBYouTubePublishingDialog pub(videoFilePath, UBApplication::mainWindow);

    pub.title->setText(QFileInfo(mVideoFilePath).completeBaseName());
    pub.keywords->setText("Uniboard");

    QString defaultEMail = UBSettings::settings()->youTubeUserEMail->get().toString();
    pub.email->setText(defaultEMail);

    QString defaultPassword = UBSettings::settings()->password(defaultEMail);
    pub.password->setText(defaultPassword);

    if (pub.exec() == QDialog::Accepted)
    {
        mTitle = pub.title->text();
        mDescription = pub.description->toPlainText();
        mCategories << pub.category->itemData(pub.category->currentIndex()).toString();
        mKeywords = pub.keywords->text();

        QString email = pub.email->text();
        UBSettings::settings()->youTubeUserEMail->set(email);

        QString password = pub.password->text();

        UBSettings::settings()->setPassword(email, password);

        postClientLoginRequest(email, password);
    }
    else
    {
        deleteLater();
    }
}
 void foo() { pub(); }
Example #21
0
PGPPublicKey revoke_with_cert(const PGPSecretKey & pri, PGPPublicKey & revoke){
    PGPPublicKey pub(pri);
    return revoke_with_cert(pub, revoke);
}
int main(int argc, char** argv)
{
    ros::init(argc, argv, "urdf2graspit", ros::init_options::AnonymousName);
    ros::NodeHandle priv("~");
    ros::NodeHandle pub("");

    if (argc < 6)
    {
        ROS_ERROR("Not enough arguments!");
        ROS_INFO_STREAM("Usage: " << argv[0] <<
                        " <urdf-file> <output-directory> <palm link name>" <<
                        " <finger joint name 0> ... <finger joint name n>");
        return 0;
    }

    // set parameters

    std::string urdf_filename = std::string(argv[1]);
    ROS_INFO("URDF file: %s", urdf_filename.c_str());

    std::string outputDir = std::string(argv[2]);
    ROS_INFO("Output dir: %s", outputDir.c_str());

    std::string palmLinkName = std::string(argv[3]);
    ROS_INFO("Hand root: %s", palmLinkName.c_str());

    std::vector<std::string> roots;
    for (unsigned int i = 4; i < argc; ++i)
    {
        std::string fingerJoint = std::string(argv[i]);
        ROS_INFO("Joint: %s", fingerJoint.c_str());
        roots.push_back(fingerJoint);
    }

    std::string outputMaterial = "plastic";
    priv.param<std::string>("output_material", outputMaterial, outputMaterial);
    ROS_INFO("output_material: <%s>", outputMaterial.c_str());

    double scaleFactor = 1000;
    priv.param<double>("scale_factor", scaleFactor, scaleFactor);
    ROS_INFO("scale_factor: <%f>", scaleFactor);
    
    bool negateJointMoves = false;
    priv.param<bool>("negate_joint_movement", negateJointMoves, negateJointMoves);
    ROS_INFO("negate_joint_movement: <%d>", negateJointMoves);


    // An axis and angle (degrees) can be specified which will transform *all*
    // visuals (not links, but their visuals!) within their local coordinate system.
    // This can be used to correct transformation errors which may have been 
    // introduced in converting meshes from one format to the other, losing orientation information
    // For example, .dae has an "up vector" definition which may have been ignored.
    float visCorrAxX=0;
    priv.param<float>("visual_corr_axis_x", visCorrAxX, visCorrAxX);
    float visCorrAxY=0;
    priv.param<float>("visual_corr_axis_y", visCorrAxY, visCorrAxY);
    float visCorrAxZ=0;
    priv.param<float>("visual_corr_axis_z", visCorrAxZ, visCorrAxZ);
    float visCorrAxAngle=0;
    priv.param<float>("visual_corr_axis_angle", visCorrAxAngle, visCorrAxAngle);
    urdf2graspit::Urdf2GraspIt::EigenTransform addVisualTrans(Eigen::AngleAxisd(visCorrAxAngle*M_PI/180, Eigen::Vector3d(visCorrAxX,visCorrAxY,visCorrAxZ)));

    urdf2inventor::Urdf2Inventor::UrdfTraverserPtr traverser(new urdf_traverser::UrdfTraverser());
    urdf2graspit::Urdf2GraspIt converter(traverser, scaleFactor, negateJointMoves);

    ROS_INFO("Starting model conversion...");

    urdf2graspit::Urdf2GraspIt::ConversionResultPtr cResult =
        converter.processAll(urdf_filename,
                             palmLinkName,
                             roots, outputMaterial, addVisualTrans);
    if (!cResult || !cResult->success)
    {
        ROS_ERROR("Failed to process.");
        return 0;
    }

    ROS_INFO("Conversion done.");

    urdf2graspit::FileIO fileIO(outputDir, converter.getOutStructure());

    if (!fileIO.write(cResult))
    {
        ROS_ERROR("Could not write files");
        return 0;
    }
    
    ROS_INFO("Cleaning up...");
    converter.cleanup();

    ROS_INFO("Done.");
    return 0;
}
bool CertDecoder::ValidateSelfSignature()
{
    Source pub(key_.GetKey(), key_.size());
    return ConfirmSignature(pub);
}
int main(int argc, char **argv)
{

  if (argc != 1)
  {
    if (argc == 3)
    {
      // Change the NUM_SAMPLES by reading the argument
      NUM_SAMPLES = atoll(argv[1]);
      SIZE_SAMPLES = atoll(argv[2]);
    }
    else
    {
      std::cout << "Accept TWO argument: NUM_SAMPLES & SIZE_SAMPLES\n"
                << "  - NUM_SAMPLES: The number of round trip times to measure.\n"
                << "  - SIZE_SAMPLES: The number of Float64 values to transmit." 
                << std::endl;
      return 1;
    }
  }
  else
  {
    std::cout<<"Use default value: NUM_SAMPLES: "<<NUM_SAMPLES<<"; SIZE_SAMPLES: "<<SIZE_SAMPLES<<std::endl;
  }

  data = new double[NUM_SAMPLES];

  std_msgs::Float64MultiArray msg;
  std_msgs::MultiArrayDimension dim;
  dim.size = SIZE_SAMPLES;
  dim.stride = SIZE_SAMPLES;
  msg.layout.data_offset = 0;
  msg.layout.dim.push_back(dim);
  msg.data.resize(SIZE_SAMPLES);

  ros::init(argc, argv, "master", ros::init_options::AnonymousName);
  ros::NodeHandle n;

  shared_memory_interface::Publisher<std_msgs::Float64MultiArray> pub(WRITE_TO_ROS_TOPIC);
  pub.advertise("/rtt_tx");

  shared_memory_interface::Subscriber<std_msgs::Float64MultiArray> sub(LISTEN_TO_ROS_TOPIC, USE_POLLING);
  sub.subscribe("/rtt_rx", boost::bind(&rttRxCallback, _1));

  ros::Rate loop_rate(1000);
  while (ros::ok())
  {
    if (roundDone)
    {
      roundDone = false;
      sendTime = ros::Time::now();
      if (!pub.publish(msg))
      {
        ROS_ERROR("Master: Failed to publish message. Aborting.");
        break;
      }
    }
    loop_rate.sleep();
  }
  ros::spin();
  return 0;
}
Example #25
0
void
ShapesDialog::onPublishButtonClicked()
{
    dds::topic::qos::TopicQos topicQos = dp_.default_topic_qos()
                                         << dds::core::policy::Durability::Persistent()
                                         << dds::core::policy::DurabilityService(dds::core::Duration(3600,0),
                                                    dds::core::policy::HistoryKind::KEEP_LAST,
                                                    100,
                                                    8192,
                                                    4196,
                                                    8192);

    dds::pub::qos::PublisherQos PQos = dp_.default_publisher_qos()
                                        << gQos_;
    dds::pub::Publisher pub(dp_, PQos);


    int d = mainWidget.sizeSlider->value();
    float speed = ((float)mainWidget.speedSlider->value()) / 9;
    QRect rect(0, 0, d, d);
    // TODO: This should be retrieved from the canvas...


    QRect constr(0, 0, IS_WIDTH, IS_HEIGHT);
    // QRect constr = this->geometry();
    int x = constr.width() * ((float)rand() / RAND_MAX);
    int y = constr.height() * ((float)rand() / RAND_MAX);
    int cIdx = mainWidget.colorList->currentIndex();
    int sIdx = mainWidget.wShapeList->currentIndex();

    QBrush brush(color_[cIdx], Qt::SolidPattern);
    QPen pen(QColor(0xff, 0xff, 0xff), 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);

    ShapeType shape;
    shape.color = DDS::string_dup(colorString_[cIdx]);
    shape.shapesize = rect.width();
    shape.x = x;
    shape.y = y;

    switch (sIdx)
    {

        case CIRCLE:
        {
            dds::topic::Topic<ShapeType> circle_(dp_, circleTopicName, topicQos);
            dds::pub::qos::DataWriterQos dwqos = circle_.qos();
            dds::pub::DataWriter<ShapeType> dw(pub, circle_, writerQos_.get_qos());


            BouncingShapeDynamics::ref_type dynamics(new BouncingShapeDynamics(x, y, rect, constr, PI/6, speed, shape, dw));
            Shape::ref_type  circle(new Circle(rect, dynamics, pen, brush));
            shapesWidget->addShape(circle);

            break;
        }

        case SQUARE:
        {
            dds::topic::Topic<ShapeType> square_(dp_, squareTopicName, topicQos);
            dds::pub::qos::DataWriterQos dwqos = square_.qos();
            dds::pub::DataWriter<ShapeType> dw(pub, square_, writerQos_.get_qos());


            BouncingShapeDynamics::ref_type dynamics(new BouncingShapeDynamics(x, y, rect, constr, PI/6, speed, shape, dw));
            Shape::ref_type  square(new Square(rect, dynamics, pen, brush));
            shapesWidget->addShape(square);
            break;
        }
        case TRIANGLE:
        {
            dds::topic::Topic<ShapeType> triangle_(dp_, triangleTopicName, topicQos);
            dds::pub::qos::DataWriterQos dwqos = triangle_.qos();
            dds::pub::DataWriter<ShapeType> dw(pub, triangle_, writerQos_.get_qos());


            BouncingShapeDynamics::ref_type dynamics(new BouncingShapeDynamics(x, y, rect, constr, PI/6, speed, shape, dw));
            Shape::ref_type  triangle(new Triangle(rect, dynamics, pen, brush));
            shapesWidget->addShape(triangle);
            break;
        }
        default:
            break;
    };
}
Example #26
0
/**
 * This function performs the publisher role in this example.
 * @return 0 if a sample is successfully written, 1 otherwise.
 */
int publisher(int argc, char *argv[])
{
    int result = 0;
    try
    {
        /** A dds::domain::DomainParticipant is created for the default domain. */
        dds::domain::DomainParticipant dp(org::opensplice::domain::default_id());

        /** The Durability::Transient policy is specified as a dds::topic::qos::TopicQos
         * so that even if the subscriber does not join until after the sample is written
         * then the DDS will still retain the sample for it. The Reliability::Reliable
         * policy is also specified to guarantee delivery and a policy::Deadline() of 1 second is
         * used to trigger the ExampleDataReaderListener::on_request_deadline_missed method
         * after no message  has been received for that duration. */
        dds::topic::qos::TopicQos topicQos
             = dp.default_topic_qos()
                << dds::core::policy::Durability::Transient()
                << dds::core::policy::Reliability::Reliable()
                << dds::core::policy::Deadline(dds::core::Duration(1, 0));

        /** These tailored QoS are made the new participant default */
        dp.default_topic_qos(topicQos);

        /** A dds::topic::Topic is created for our sample type on the domain participant. */
        dds::topic::Topic<ListenerData::Msg> topic(dp, "ListenerData_Msg", topicQos);

        /** A dds::pub::Publisher is created on the domain participant. */
        std::string name = "Listener example";
        dds::pub::qos::PublisherQos pubQos
            = dp.default_publisher_qos()
                << dds::core::policy::Partition(name);
        dds::pub::Publisher pub(dp, pubQos);

        /** The dds::pub::qos::DataWriterQos is derived from the topic qos and the
         * WriterDataLifecycle::ManuallyDisposeUnregisteredInstances policy is
         * specified as an addition. This is so the publisher can optionally be run (and
         * exit) before the subscriber. It prevents the middleware default 'clean up' of
         * the topic instance after the writer deletion, this deletion implicitly performs
         * DataWriter::unregister_instance */
        dds::pub::qos::DataWriterQos dwqos = topic.qos();
        dwqos << dds::core::policy::WriterDataLifecycle::ManuallyDisposeUnregisteredInstances();

        /** A dds::pub::DataWriter is created on the Publisher & Topic with the modififed Qos. */
        dds::pub::DataWriter<ListenerData::Msg> dw(pub, topic, dwqos);

        /** A sample is created on the stack and then written. */
        ListenerData::Msg msgInstance(1, "Hello World");
        dw << msgInstance;

        std::cout << "=== [Publisher] written a message containing :" << std::endl;
        std::cout << "    userID  : " << msgInstance.userID() << std::endl;
        std::cout << "    Message : \"" << msgInstance.message() << "\"" << std::endl;

        /* A short sleep ensures time is allowed for the sample to be written to the network.
        If the example is running in *Single Process Mode* exiting immediately might
        otherwise shutdown the domain services before this could occur */
        exampleSleepMilliseconds(1500);
    }
    catch (const dds::core::Exception& e)
    {
        std::cerr << "ERROR: Exception: " << e.what() << std::endl;
        result = 1;
    }

    return result;
}