Exemple #1
0
bool SOAPClient::SendSOAPRequest( const QString    &sMethod, 
                                        QStringMap &list, 
                                        int        &nErrCode, 
                                        QString    &sErrDesc,
                                        bool        bInQtThread )
{
    QUrl url( m_url );

    url.setPath( m_sControlPath );

    // --------------------------------------------------------------
    // Add appropriate headers
    // --------------------------------------------------------------

    QHttpRequestHeader header;

    header.setValue("CONTENT-TYPE", "text/xml; charset=\"utf-8\"" );
    header.setValue("SOAPACTION"  , QString( "\"%1#GetConnectionInfo\"" )
                                       .arg( m_sNamespace ));

    // --------------------------------------------------------------
    // Build request payload
    // --------------------------------------------------------------

    QByteArray  aBuffer;
    QTextStream os( &aBuffer );

    os << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"; 
    os << "<s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
    os << " <s:Body>\r\n";
    os << "  <u:" << sMethod << " xmlns:u=\"" << m_sNamespace << "\">\r\n";

    // --------------------------------------------------------------
    // Add parameters from list
    // --------------------------------------------------------------

    for ( QStringMap::iterator it  = list.begin(); 
                               it != list.end(); 
                             ++it ) 
    {                                                               
        os << "   <" << it.key() << ">";
        os << HTTPRequest::Encode( *it );
        os << "</"   << it.key() << ">\r\n";
    }

    os << "  </u:" << sMethod << ">\r\n";
    os << " </s:Body>\r\n";
    os << "</s:Envelope>\r\n";

    os.flush();

    // --------------------------------------------------------------
    // Perform Request
    // --------------------------------------------------------------

    QBuffer     buff( &aBuffer );

    QString sXml = HttpComms::postHttp( url, 
                                        &header,
                                        (QIODevice *)&buff,
                                        10000, // ms
                                        3,     // retries
                                        0,     // redirects
                                        false, // allow gzip
                                        NULL,  // login
                                        bInQtThread );

    // --------------------------------------------------------------
    // Parse response
    // --------------------------------------------------------------

    list.clear();

    QDomDocument doc;

    if ( !doc.setContent( sXml, true, &sErrDesc, &nErrCode ))
    {
        VERBOSE( VB_UPNP, QString( "MythXMLClient::SendSOAPRequest( %1 ) - Invalid response from %2" )
                             .arg( sMethod   )
                             .arg( url.toString() ));
        return false;
    }

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QString      sResponseName = sMethod + "Response";
    QDomNodeList oNodeList     = doc.elementsByTagNameNS( m_sNamespace, sResponseName );

    if (oNodeList.count() > 0)
    {
        QDomNode oMethod = oNodeList.item(0);

        if (!oMethod.isNull())
        {

            for ( QDomNode oNode = oMethod.firstChild(); !oNode.isNull(); 
                           oNode = oNode.nextSibling() )
            {
                QDomElement e = oNode.toElement();

                if (!e.isNull())
                {
                    QString sName  = e.tagName();
                    QString sValue = "";
    
                    QDomText  oText = oNode.firstChild().toText();
    
                    if (!oText.isNull())
                        sValue = oText.nodeValue();

                    list.insert(QUrl::fromPercentEncoding(sName.toUtf8()),
                                QUrl::fromPercentEncoding(sValue.toUtf8()));
                }
            }
        }

        return true;
    }

    // --------------------------------------------------------------
    // Must be a fault... parse it to return reason
    // --------------------------------------------------------------

    nErrCode = GetNodeValue( doc, "Envelope/Body/Fault/detail/UPnPResult/errorCode"       , 500 );
    sErrDesc = GetNodeValue( doc, "Envelope/Body/Fault/detail/UPnPResult/errorDescription", QString( "Unknown" ));

    return false;
}
Exemple #2
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args;
    std::string wire;
    double seconds_in_future;
    size_t total_num_samps;
    double rate;
    std::string channel_list;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "single uhd device address args")
        ("wire", po::value<std::string>(&wire)->default_value(""), "the over the wire type, sc16, sc8, etc")
        ("secs", po::value<double>(&seconds_in_future)->default_value(1.5), "number of seconds in the future to receive")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(10000), "total number of samples to receive")
        ("rate", po::value<double>(&rate)->default_value(100e6/16), "rate of incoming samples")
        ("dilv", "specify to disable inner-loop verbose")
        ("channels", po::value<std::string>(&channel_list)->default_value("0"), "which channel(s) to use (specify \"0\", \"1\", \"0,1\", etc)")
    
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD RX Timed Samples %s") % desc << std::endl;
        return ~0;
    }

    bool verbose = vm.count("dilv") == 0;

    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

   //detect which channels to use
    std::vector<std::string> channel_strings;
    std::vector<size_t> channel_nums;
    boost::split(channel_strings, channel_list, boost::is_any_of("\"',"));
    for(size_t ch = 0; ch < channel_strings.size(); ch++){
        size_t chan = boost::lexical_cast<int>(channel_strings[ch]);
        if(chan >= usrp->get_tx_num_channels() or chan >= usrp->get_rx_num_channels()){
            throw std::runtime_error("Invalid channel(s) specified.");
        }
        else channel_nums.push_back(boost::lexical_cast<int>(channel_strings[ch]));
    }

    //set the rx sample rate
    std::cout << boost::format("Setting RX Rate: %f Msps...") % (rate/1e6) << std::endl;
    usrp->set_rx_rate(rate);
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate()/1e6) << std::endl << std::endl;

    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;
    usrp->set_time_now(uhd::time_spec_t(0.0));

    //create a receive streamer
    uhd::stream_args_t stream_args("fc32", wire); //complex floats
    stream_args.channels = channel_nums;
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    //setup streaming
    std::cout << std::endl;
    std::cout << boost::format(
        "Begin streaming %u samples, %f seconds in the future..."
    ) % total_num_samps % seconds_in_future << std::endl;
    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
    stream_cmd.num_samps = total_num_samps;
    stream_cmd.stream_now = false;
    stream_cmd.time_spec = uhd::time_spec_t(seconds_in_future);
    rx_stream->issue_stream_cmd(stream_cmd);

    //meta-data will be filled in by recv()
    uhd::rx_metadata_t md;

    //allocate buffer to receive with samples
    std::vector<std::complex<float> > buff(rx_stream->get_max_num_samps());
    std::vector<void *> buffs;
    for (size_t ch = 0; ch < rx_stream->get_num_channels(); ch++)
        buffs.push_back(&buff.front()); //same buffer for each channel

    //the first call to recv() will block this many seconds before receiving
    double timeout = seconds_in_future + 0.1; //timeout (delay before receive + padding)

    size_t num_acc_samps = 0; //number of accumulated samples
    while(num_acc_samps < total_num_samps){
        //receive a single packet
        size_t num_rx_samps = rx_stream->recv(
            buffs, buff.size(), md, timeout, true
        );

        //use a small timeout for subsequent packets
        timeout = 0.1;

        //handle the error code
        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) break;
        if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE){
            throw std::runtime_error(str(boost::format(
                "Receiver error %s"
            ) % md.strerror()));
        }

        if(verbose) std::cout << boost::format(
            "Received packet: %u samples, %u full secs, %f frac secs"
        ) % num_rx_samps % md.time_spec.get_full_secs() % md.time_spec.get_frac_secs() << std::endl;

        num_acc_samps += num_rx_samps;
    }

    if (num_acc_samps < total_num_samps) std::cerr << "Receive timeout before all samples received..." << std::endl;

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return EXIT_SUCCESS;
}
Exemple #3
0
JNIEXPORT jlong JNICALL
Java_gurux_io_NativeCode_openSerialPort (JNIEnv* env, jclass clazz,
        jstring port, jlongArray closing)
{
    jboolean isCopy;
#if defined(_WIN32) || defined(_WIN64)
    const char* pPort = env->GetStringUTFChars(port, &isCopy);
    std::string port2(pPort);
    std::string buff("\\\\.\\");
    buff.append(pPort);
    env->ReleaseStringUTFChars(port, pPort);
    //Open serial port for read / write. Port can't share.
    HANDLE hComPort = CreateFileA(buff.c_str(),
                                  GENERIC_READ | GENERIC_WRITE, 0, NULL,
                                  OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
    if (hComPort == INVALID_HANDLE_VALUE)
    {
        ReportError(env, GetLastError());
    }
    DCB dcb =
    {	0};
    dcb.DCBlength = sizeof(DCB);
    dcb.BaudRate = 9600;
    dcb.fBinary = 1;
    dcb.fDtrControl = DTR_CONTROL_ENABLE;
    dcb.fRtsControl = DTR_CONTROL_ENABLE;
    dcb.fOutX = dcb.fInX = 0;
    //CTS handshaking on output.
    dcb.fOutxCtsFlow = DTR_CONTROL_DISABLE;
    //DSR handshaking on output
    dcb.fOutxDsrFlow = DTR_CONTROL_DISABLE;
    //Abort all reads and writes on Error.
    dcb.fAbortOnError = 1;
    dcb.ByteSize = 8;
    //Parity = None.
    dcb.Parity = 0;
    //StopBits = 1;
    dcb.StopBits = 0;
    int ret;
    if ((ret = GXSetCommState(hComPort, &dcb)) != 0)
    {
        ReportError(env, ret);
    }
    jlong hClosing = (jlong) ::CreateEvent(NULL, TRUE, FALSE, NULL);
    env->SetLongArrayRegion(closing, 0, 1, &hClosing);
    return (long) hComPort;
#else //#if defined(__LINUX__)
    const char* pPort = env->GetStringUTFChars (port, &isCopy);
    std::string buff (pPort);
    env->ReleaseStringUTFChars (port, pPort);

    // file description for the serial port
    int hComPort;
    // read/write | not controlling term | don't wait for DCD line signal.
    hComPort = open (buff.c_str (), O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (hComPort == -1)// if open is unsuccessful.
    {
        buff.insert (0, "Failed to Open port: ");
        ReportError (env, buff.c_str ());
    }
    else
    {
        if (!isatty (hComPort))
        {
            ReportError (env, "Failed to Open port. This is not a serial port.");
        }

        if ((ioctl (hComPort, TIOCEXCL) == -1))
        {
            ReportError (env, "Failed to Open port. Exclusive access denied.");
        }

        struct termios options;
        memset (&options, 0, sizeof(options));
        options.c_iflag = 0;
        options.c_oflag = 0;
        options.c_cflag = CS8 | CREAD | CLOCAL; // 8n1, see termios.h for more information
        options.c_lflag = 0;
        options.c_cc[VMIN] = 1;
        options.c_cc[VTIME] = 5;
        //Set Baud Rates
        cfsetospeed (&options, B9600);
        cfsetispeed (&options, B9600);

        //hardware flow control is used as default.
        //options.c_cflag |= CRTSCTS;
        if (tcsetattr (hComPort, TCSAFLUSH, &options) != 0)
        {
            ReportError (env, "Failed to Open port. tcsetattr failed.");
            //errno
        }
    }
    return hComPort;
#endif
}
void transceive(
    uhd::usrp::multi_usrp::sptr usrp,
    uhd::tx_streamer::sptr tx_stream,
    uhd::rx_streamer::sptr rx_stream,
    unsigned int npulses,
    float pulse_time,
    //std::complex<int16_t>* txbuff,
    std::vector<std::complex<int16_t> >* txbuff0,
    std::vector<std::complex<int16_t> >* txbuff1,
    float tx_ontime,
    std::complex<int16_t>** outdata,
    size_t samps_per_pulse
){
    int debug = 0;
    if (debug){
        std::cout << "samps_per_pulse: " << samps_per_pulse << std::endl;
    }
    //create metadeta tags for transmit streams
    uhd::time_spec_t start_time = usrp->get_time_now() + 0.05;
    uhd::tx_metadata_t md;
    md.start_of_burst = true;
    md.end_of_burst = false;
    md.has_time_spec = true;
    md.time_spec = start_time;
    std::vector<std::complex<int16_t> *> vec_ptr;
    vec_ptr.resize(1);
    //vec_ptr[0] = &txbuff->front();
    
    usrp->set_gpio_attr("RXA","CTRL",0x0, TR_BIT); //GPIO mode
    usrp->set_gpio_attr("RXA","DDR",TR_BIT, TR_BIT); //Direction out
    
    //create metadata tags for receive stream
    uhd::rx_metadata_t rxmd;
    std::vector<std::complex<int16_t> > buff(samps_per_pulse,0);
    if (verbose) std::cout << "rx buff size: " << buff.size() << std::endl;
    if (verbose) std::cout << "tx buff size: " << txbuff0->size() << std::endl;
    uhd::stream_cmd_t stream_cmd = uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE;
    stream_cmd.num_samps = npulses*samps_per_pulse;
    stream_cmd.stream_now = false;
    stream_cmd.time_spec = start_time + 22 / usrp->get_rx_rate(); //Digital hardware delay is 22 samples long.  Found by experiment.
    if (verbose) std::cout << "time spec: " << stream_cmd.time_spec.get_real_secs() << std::endl;
    
    //loop for every pulse in the sequence
    size_t spb;
    std::vector<std::complex<int16_t>* > rx_dptr;
    rx_dptr.resize(usrp->get_rx_num_channels());
    spb = tx_stream->get_max_num_samps();
    if (verbose) std::cout << "npulses: " << npulses << std::endl;
    boost::thread_group rx_threads;
    boost::thread_group tx_threads;
    for (int ipulse=0; ipulse<npulses; ipulse++){
        if (debug) std::cout << "pulse number: " << ipulse << std::endl;
        for (size_t ichan=0; ichan<usrp->get_rx_num_channels(); ichan++){
         rx_dptr[ichan] = ipulse*samps_per_pulse + outdata[ichan];
        }
        
        float timeout = 1.1;
        
        //usrp->set_command_time(start_time-50e-6,0);
        //usrp->set_gpio_attr("RXA","OUT",TR_BIT, TR_BIT);
        
        if (ipulse==0){
            if (verbose) std::cout << "time spec: " << stream_cmd.time_spec.get_real_secs() << std::endl;
            if (verbose) std::cout << "Issuing stream command to start collecting samples\n";
            usrp->issue_stream_cmd(stream_cmd);
        }
        
        //usrp->set_command_time(start_time+tx_ontime,0);
        //usrp->set_gpio_attr("RXA","OUT",0x0, TR_BIT);
        
        size_t acc_samps=0;
        if (ipulse%2 == 0) {
            vec_ptr[0] = &txbuff0->front();
        }
        if (ipulse%2 == 1) {
            vec_ptr[0] = &txbuff1->front();
        }
        
        if (ipulse != npulses-1) {
             tx_threads.create_thread(boost::bind(tx_worker,
                 txbuff0->size(), tx_stream, start_time, vec_ptr[0], 0));
        }
        if (ipulse == npulses-1) {
             tx_threads.create_thread(boost::bind(tx_worker,
                 txbuff0->size(), tx_stream, start_time, vec_ptr[0], 1));
        }
        
        rx_threads.join_all();
        rx_threads.create_thread(boost::bind(rx_worker,
         rx_stream, samps_per_pulse, rx_dptr));
        
        //for (int k=0; k<10; k++){
        // //std::cout << "raw data: " << outdata[0][i][k] << "\t" << outdata[1][i][k] << std::endl;
        // std::cout << "raw data: " << rx_dptr[0][k] << " " << rx_dptr[1][k] << std::endl;
        //}
        //for (int k=0; k<samps_per_pulse; k++)
        //    outdata[i][k] += buff[k];
        
        
        start_time += float(pulse_time);
    }
    tx_threads.join_all();
    rx_threads.join_all();
}
/// @fn D3D9DeviceThread
/// @brief デフォルトコンストラクタ
D3D9DeviceThread::D3D9DeviceThread(LPDIRECT3DDEVICE9 device)
 : device_(device),
   thread_life_(true),
	 clear_flag_(D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL),
	 clear_color_(D3DCOLOR_RGBA(50, 0, 50, 0)),
	 clear_z_(1),
	 clear_stencil_(0) {
	auto function = [&] {

		while (thread_life_) {
			std::unique_lock<std::mutex> lock(condition_mutex_);
			condition_.wait(lock);

			if (!thread_life_) return;

			device_task_mutex_.lock();
			while (!device_task_.empty()) {
				if (!*device_task_.front().task_mutex) {
					device_task_.pop();
					continue;
				}

				(*device_task_.front().task_mutex)->lock();
				device_task_.front().task(device_);
				(*device_task_.front().task_mutex)->unlock();
				device_task_.pop();
			}
			device_task_mutex_.unlock();

			device_->Clear(0, nullptr,
				clear_flag_,
				clear_color_,
				clear_z_,
				clear_stencil_);
			if (FAILED(device_->BeginScene())) {
				continue;
			}

			draw_task_mutex_.lock();
			while (!draw_task_.empty()) {
				if (!*draw_task_.front().task_mutex) {
					draw_task_.pop();
					continue;
				}

				(*draw_task_.front().task_mutex)->lock();
				draw_task_.front().task(device_);
				(*draw_task_.front().task_mutex)->unlock();

				draw_task_.pop();
			}
			draw_task_mutex_.unlock();

			device_->EndScene();
			device_->Present(nullptr, nullptr, nullptr, nullptr);
		}
	};

	std::thread buff(function);
	device_thread_.swap(buff);
}
void recv_to_file(uhd::rx_streamer::sptr rx_stream,
    const std::string& file,
    const size_t samps_per_buff,
    const double rx_rate,
    const unsigned long long num_requested_samples,
    double time_requested       = 0.0,
    bool bw_summary             = false,
    bool stats                  = false,
    bool enable_size_map        = false,
    bool continue_on_bad_packet = false)
{
    unsigned long long num_total_samps = 0;

    uhd::rx_metadata_t md;
    std::vector<samp_type> buff(samps_per_buff);
    std::ofstream outfile;
    if (not file.empty()) {
        outfile.open(file.c_str(), std::ofstream::binary);
    }
    bool overflow_message = true;

    // setup streaming
    uhd::stream_cmd_t stream_cmd((num_requested_samples == 0)
                                     ? uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS
                                     : uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
    stream_cmd.num_samps  = size_t(num_requested_samples);
    stream_cmd.stream_now = true;
    stream_cmd.time_spec  = uhd::time_spec_t();
    std::cout << "Issuing stream cmd" << std::endl;
    rx_stream->issue_stream_cmd(stream_cmd);

    const auto start_time = std::chrono::steady_clock::now();
    const auto stop_time =
        start_time + std::chrono::milliseconds(int64_t(1000 * time_requested));
    // Track time and samps between updating the BW summary
    auto last_update                     = start_time;
    unsigned long long last_update_samps = 0;

    typedef std::map<size_t, size_t> SizeMap;
    SizeMap mapSizes;

    // Run this loop until either time expired (if a duration was given), until
    // the requested number of samples were collected (if such a number was
    // given), or until Ctrl-C was pressed.
    while (not stop_signal_called
           and (num_requested_samples != num_total_samps or num_requested_samples == 0)
           and (time_requested == 0.0 or std::chrono::steady_clock::now() <= stop_time)) {
        const auto now = std::chrono::steady_clock::now();

        size_t num_rx_samps =
            rx_stream->recv(&buff.front(), buff.size(), md, 3.0, enable_size_map);

        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) {
            std::cout << boost::format("Timeout while streaming") << std::endl;
            break;
        }
        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW) {
            if (overflow_message) {
                overflow_message = false;
                std::cerr
                    << boost::format(
                           "Got an overflow indication. Please consider the following:\n"
                           "  Your write medium must sustain a rate of %fMB/s.\n"
                           "  Dropped samples will not be written to the file.\n"
                           "  Please modify this example for your purposes.\n"
                           "  This message will not appear again.\n")
                           % (rx_rate * sizeof(samp_type) / 1e6);
            }
            continue;
        }
        if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE) {
            std::string error = str(boost::format("Receiver error: %s") % md.strerror());
            if (continue_on_bad_packet) {
                std::cerr << error << std::endl;
                continue;
            } else
                throw std::runtime_error(error);
        }

        if (enable_size_map) {
            SizeMap::iterator it = mapSizes.find(num_rx_samps);
            if (it == mapSizes.end())
                mapSizes[num_rx_samps] = 0;
            mapSizes[num_rx_samps] += 1;
        }

        num_total_samps += num_rx_samps;

        if (outfile.is_open()) {
            outfile.write((const char*)&buff.front(), num_rx_samps * sizeof(samp_type));
        }

        if (bw_summary) {
            last_update_samps += num_rx_samps;
            const auto time_since_last_update = now - last_update;
            if (time_since_last_update > std::chrono::seconds(UPDATE_INTERVAL)) {
                const double time_since_last_update_s =
                    std::chrono::duration<double>(time_since_last_update).count();
                const double rate = double(last_update_samps) / time_since_last_update_s;
                std::cout << "\t" << (rate / 1e6) << " MSps" << std::endl;
                last_update_samps = 0;
                last_update       = now;
            }
        }
    }
    const auto actual_stop_time = std::chrono::steady_clock::now();

    stream_cmd.stream_mode = uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;
    std::cout << "Issuing stop stream cmd" << std::endl;
    rx_stream->issue_stream_cmd(stream_cmd);

    // Run recv until nothing is left
    int num_post_samps = 0;
    do {
        num_post_samps = rx_stream->recv(&buff.front(), buff.size(), md, 3.0);
    } while (num_post_samps and md.error_code == uhd::rx_metadata_t::ERROR_CODE_NONE);

    if (outfile.is_open())
        outfile.close();

    if (stats) {
        std::cout << std::endl;

        const double actual_duration_seconds =
            std::chrono::duration<float>(actual_stop_time - start_time).count();

        std::cout << boost::format("Received %d samples in %f seconds") % num_total_samps
                         % actual_duration_seconds
                  << std::endl;
        const double rate = (double)num_total_samps / actual_duration_seconds;
        std::cout << (rate / 1e6) << " MSps" << std::endl;

        if (enable_size_map) {
            std::cout << std::endl;
            std::cout << "Packet size map (bytes: count)" << std::endl;
            for (SizeMap::iterator it = mapSizes.begin(); it != mapSizes.end(); it++)
                std::cout << it->first << ":\t" << it->second << std::endl;
        }
    }
}
/***********************************************************************
 * recv_to_file function
 **********************************************************************/
template<typename samp_type> void recv_to_file(
    uhd::usrp::multi_usrp::sptr usrp,
    const std::string &cpu_format,
    const std::string &wire_format,
    const std::string &file,
    size_t samps_per_buff,
    int num_requested_samples,
    float settling_time,
    std::vector<size_t> rx_channel_nums
) {
    int num_total_samps = 0;
    //create a receive streamer
    uhd::stream_args_t stream_args(cpu_format,wire_format);
    stream_args.channels = rx_channel_nums;
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    uhd::rx_metadata_t md;
    std::vector<samp_type> buff(samps_per_buff);
    std::ofstream outfile(file.c_str(), std::ofstream::binary);
    bool overflow_message = true;
    float timeout = settling_time + 0.1; //expected settling time + padding for first recv

    //setup streaming
    uhd::stream_cmd_t stream_cmd((num_requested_samples == 0)?
                                 uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS:
                                 uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE
                                );
    stream_cmd.num_samps = num_requested_samples;
    stream_cmd.stream_now = false;
    stream_cmd.time_spec = uhd::time_spec_t(settling_time);
    rx_stream->issue_stream_cmd(stream_cmd);

    while(not stop_signal_called and (num_requested_samples != num_total_samps or num_requested_samples == 0)) {
        size_t num_rx_samps = rx_stream->recv(&buff.front(), buff.size(), md, timeout);
        timeout = 0.1; //small timeout for subsequent recv

        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) {
            std::cout << boost::format("Timeout while streaming") << std::endl;
            break;
        }
        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW) {
            if (overflow_message) {
                overflow_message = false;
                std::cerr << boost::format(
                              "Got an overflow indication. Please consider the following:\n"
                              "  Your write medium must sustain a rate of %fMB/s.\n"
                              "  Dropped samples will not be written to the file.\n"
                              "  Please modify this example for your purposes.\n"
                              "  This message will not appear again.\n"
                          ) % (usrp->get_rx_rate()*sizeof(samp_type)/1e6);
            }
            continue;
        }
        if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE) {
            throw std::runtime_error(str(boost::format(
                                             "Receiver error %s"
                                         ) % md.strerror()));
        }

        num_total_samps += num_rx_samps;

        outfile.write((const char*)&buff.front(), num_rx_samps*sizeof(samp_type));
    }

    outfile.close();
}
void CStateEvidences::ActivateL(const TDesC8& aData)
{
    iSignKey.Copy(aData);

    if (iState != EInitState)
    {
        // Log File has been sent.
        // Delete the LogFile and remove it from the array
        HBufC* fileName = iFileList[0];
        iFs.Delete(*fileName);
        delete fileName;
        iFileList.Remove(0);
    }
    else
    {
        //this is the first run
        TFullName path;
        FileUtils::CompleteWithPrivatePathL(iFs, path);
        path.Append(_L("*.log"));
        FileUtils::ListFilesInDirectoryL(iFs, path, iFileList);

        iState = ESendLogData;
    }
    // Check if there exists log files...
    if (iFileList.Count() == 0)
    {
        iObserver.ChangeStateL();
        return;
    }
    //send evidence
    //here we are sure we don't need anymore the answer
    delete iResponseData;
    iResponseData = NULL;

    CBufBase* buffer = CBufFlat::NewL(10);
    CleanupStack::PushL(buffer);
    //append command
    buffer->InsertL(buffer->Size(),(TUint8 *)KProto_Log().Ptr(),KProto_Log().Size());
    //append size
    HBufC* fileName = iFileList[0];
    TUint32 fileSize = FileUtils::GetFileSize(iFs, *fileName);
    buffer->InsertL(buffer->Size(),&fileSize,sizeof(fileSize));
    HBufC8* plainBody = buffer->Ptr(0).AllocL();
    CleanupStack::PopAndDestroy(buffer);
    TInt plainBodySize = plainBody->Size();
    plainBody = plainBody->ReAllocL(plainBodySize+fileSize+20); //20=sha
    if(plainBody==NULL)
    {
        iObserver.ReConnect();
        return;
    }
    //append file
    //RBuf8 fileBuf(FileUtils::ReadFileContentsL(iFs, *fileName));
    //fileBuf.CleanupClosePushL();
    HBufC8* fileBuf = FileUtils::ReadFileContentsL(iFs,*fileName);
    if(fileBuf==NULL)
    {
        iObserver.ReConnect();
        return;
    }
    plainBody->Des().Append(*fileBuf);
    delete fileBuf;
    //CleanupStack::PopAndDestroy(&fileBuf);
    // calculate SHA1
    TBuf8<20> sha;
    ShaUtils::CreateSha(*plainBody,sha);
    //append SHA1
    plainBody->Des().Append(sha);

    // encrypt an send
    RBuf8 buff(AES::EncryptPkcs5L(*plainBody, KIV, iSignKey));
    if(buff.Size()<=0)
    {
        delete plainBody;
        iObserver.ReConnect();
        return;
    }
    buff.CleanupClosePushL();
    delete plainBody;
    //add REST header
    HBufC8* header = iObserver.GetRequestHeaderL();
    TBuf8<32> contentLengthLine;
    contentLengthLine.Append(KContentLength);
    contentLengthLine.AppendNum(buff.Size());
    contentLengthLine.Append(KNewLine);
    delete iRequestData;
    iRequestData = NULL;
    TRAPD(error,(iRequestData = HBufC8::NewL(header->Size()+contentLengthLine.Size()+KNewLine().Size()+buff.Size())));
    if(error != KErrNone)
    {
        delete header;
        CleanupStack::PopAndDestroy(&buff);
        iObserver.ReConnect();
        return;
    }
    iRequestData->Des().Append(*header);
    delete header;
    iRequestData->Des().Append(contentLengthLine);
    iRequestData->Des().Append(KNewLine);
    iRequestData->Des().Append(buff);
    CleanupStack::PopAndDestroy(&buff);
    TRAPD(err,iObserver.SendStateDataL(*iRequestData));
    if(err != KErrNone)
    {
        iObserver.ReConnect();
    }
}
Exemple #9
0
// in interactive mode with second usrp sending bursts. calibrate trigger level
float
Responder::calibrate_usrp_for_test_run()
{
    bool calibration_finished = false;
    float threshold = 0.0f;
    double ave_high = 0, ave_low = 0;
    int ave_high_count = 0, ave_low_count = 0;
    bool level_calibration_stage_2 = false; // 1. stage = rough calibration ; 2. stage = fine calibration

    std::vector<std::complex<float> > buff(_opt.samps_per_buff);
    while (not s_stop_signal_called && !calibration_finished && _return_code == RETCODE_OK)
    {
        uhd::rx_metadata_t rx_md;
        size_t num_rx_samps = _rx_stream->recv(&buff.front(), buff.size(), rx_md, _opt.timeout);

        // handle errors
        if(handle_rx_errors(rx_md.error_code, num_rx_samps) )
        {
            break;
        }

        // Wait for USRP for DC offset calibration
        if (_dc_offset_countdown > 0)
        {
            _dc_offset_countdown -= (int64_t)num_rx_samps;
            if (_dc_offset_countdown > 0)
                continue;
            set_usrp_rx_dc_offset(_usrp, false);
            print_msg("DC offset calibration complete");
        }

        // Wait for certain time to minimize POWER UP effects
        if (_init_delay_count > 0)
        {
            _init_delay_count -= (int64_t)num_rx_samps;
            if (_init_delay_count > 0)
                continue;
            print_msg("Initial settling period elapsed");
        }

        ////////////////////////////////////////////////////////////
        // detect falling edges and calibrate detection values
        if (_level_calibration_countdown > 0)
        {
            if (level_calibration_stage_2 == false)
            {
                float average = 0.0f;
                for (size_t n = 0; n < num_rx_samps; n++)
                    average += buff[n].real() * _opt.invert;
                average /= (float)num_rx_samps;

                if (ave_low_count == 0)
                {
                    ave_low = average;
                    ++ave_low_count;
                }
                else if (average < ave_low)
                {
                    ave_low = average;
                    ++ave_low_count;
                }

                if (ave_high_count == 0)
                {
                    ave_high = average;
                    ++ave_high_count;
                }
                else if (average > ave_high)
                {
                    ave_high = average;
                    ++ave_high_count;
                }
            }
            else {
                for (size_t n = 0; n < num_rx_samps; n++)
                {
                    float f = buff[n].real() * _opt.invert;
                    if (f >= threshold)
                    {
                        ave_high += f;
                        ave_high_count++;
                    }
                    else
                    {
                        ave_low += f;
                        ave_low_count++;
                    }
                }
            }

            _level_calibration_countdown -= (int64_t)num_rx_samps;

            if (_level_calibration_countdown <= 0)
            {
                if (level_calibration_stage_2 == false)
                {
                    level_calibration_stage_2 = true;
                    _level_calibration_countdown = _opt.level_calibration_count();
                    threshold = ave_low + ((ave_high - ave_low) / 2.0);
                    print_msg( (boost::format("Phase #1: Ave low: %.3f (#%d), ave high: %.3f (#%d), threshold: %.3f") % ave_low % ave_low_count % ave_high % ave_high_count % threshold).str() );
                    ave_low_count = ave_high_count = 0;
                    ave_low = ave_high = 0.0f;
                    continue;
                }
                else
                {
                    ave_low /= (double)ave_low_count;
                    ave_high /= (double)ave_high_count;
                    threshold = ave_low + ((ave_high - ave_low) * _opt.trigger_level);
                    print_msg( (boost::format("Phase #2: Ave low: %.3f (#%d), ave high: %.3f (#%d), threshold: %.3f\n") % ave_low % ave_low_count % ave_high % ave_high_count % threshold).str() );

                    _stream_cmd.stream_mode = uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;
                    _stream_cmd.stream_now = true;
                    _usrp->issue_stream_cmd(_stream_cmd);

                    double diff = abs(ave_high - ave_low);
                    if (diff < _opt.pulse_detection_threshold)
                    {
                        _return_code = RETCODE_BAD_ARGS;
                        print_error_msg( (boost::format("Did not detect any pulses (difference %.6f < detection threshold %.6f)") % diff % _opt.pulse_detection_threshold).str() );
                        break;
                    }

                    _stream_cmd.stream_mode = uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS;
                    _stream_cmd.stream_now = true;
                    _usrp->issue_stream_cmd(_stream_cmd);
                }
            }
            else
                continue;
        } // calibration finished
        calibration_finished = true;
    }
    return threshold;
}
Exemple #10
0
inline bool string_convertible_to(const std::string& x){
  std::stringstream buff(x);
  T temp;
  buff >> temp;
  return buff.fail();
}
VError DB4DJournalParser::NextOperation( uLONG8 &outOperation, uLONG8 *outGlobalOperation, CDB4DJournalData **outJournalData )
{
	VError error = VE_OK;
	RecordHeader recHeader;
	
	if ( outJournalData )
		*outJournalData = NULL;

	outOperation = fCurrentOperation;
	sLONG8 globaloperation = 0;
	
	if ( fFileStream )
	{
		uLONG operationTag;
		error = fFileStream->GetLong(operationTag);
		if ( error == VE_OK )
		{
			if ( operationTag == kTagLogDB4D )
			{
				sLONG8 contextID;
				DB4D_LogAction logAction;
				sLONG len;
				sLONG8 curpos;
				error = fFileStream->GetLong8(globaloperation);

				if ( error == VE_OK )
				{
					error = fFileStream->GetLong(len);
				}

				if ( !outJournalData )
				{
					error = fFileStream->SetPosByOffset( len - 24 );//- 4 /*Tag*/ - 8 /*Operation#*/- 4 /*len*/ - 4 /*len at the end*/ - 4 /*tag at the end*/
				}
				else
				{

				if ( error == VE_OK )
					error = fFileStream->GetLong((uLONG&)logAction);

				if ( error == VE_OK )
					error = fFileStream->GetLong8(contextID);

				uLONG8 timeStamp;
				if (error == VE_OK)
					error = fFileStream->GetLong8(timeStamp);


				if (error == VE_OK)
				{
					switch (logAction)
					{
						case DB4D_Log_OpenData:
						case DB4D_Log_CloseData:
						case DB4D_Log_StartBackup:
						case DB4D_Log_StartTrans:
						case DB4D_Log_Commit:
						case DB4D_Log_RollBack:
							{
								*outJournalData = new VDB4DJournalData(globaloperation, logAction,contextID, GetContextExtraData( contextID),timeStamp);
							}
							break;

						case DB4D_Log_CloseContext:
							{
								*outJournalData = new VDB4DJournalData(globaloperation, logAction,contextID, GetContextExtraData( contextID),timeStamp);
								fContextExtraByID.erase(contextID);
							}
							break;

						case DB4D_Log_CreateRecord:
						case DB4D_Log_ModifyRecord:
							{
								VUUID xTableID;
								if ( error == VE_OK )
									error = recHeader.ReadFromStream(fFileStream);
								
								if ( error == VE_OK )
									if ( !recHeader.Match(DBOH_Record) )
										error = VE_DB4D_WRONGRECORDHEADER;
								
								if ( error == VE_OK )
									error = xTableID.ReadFromStream(fFileStream);

								curpos = fFileStream->GetPos();
								if ( error == VE_OK )
								{
									sLONG dataSize = recHeader.GetLen() + sizeof(ChampHeader)*(recHeader.GetNbFields());
									error = fFileStream->SetPosByOffset(dataSize);
								}
								if ( error == VE_OK )
									*outJournalData = new VDB4DJournalData(globaloperation, logAction,contextID, GetContextExtraData( contextID),&recHeader,timeStamp, curpos, fFileStream, xTableID);
							}
							break;

						case DB4D_Log_DeleteBlob:
							{
								VString path;
								sLONG blobnumber;
								if ( error == VE_OK )
									error = fFileStream->GetLong(blobnumber);

								if (blobnumber == -2)
								{
									sLONG lenpath = 0;
									error = fFileStream->GetLong(lenpath);
									if (lenpath > 0)
									{
										tempBuffer<256> buff(len);
										error = fFileStream->GetWords((sWORD*)buff.GetPtr(), &lenpath);
										path.FromBlock(buff.GetPtr(), lenpath * sizeof(UniChar), VTC_UTF_16);
									}
								}
								
								VUUID xTableID;
								if ( error == VE_OK )
									error = xTableID.ReadFromStream(fFileStream);

								if ( error == VE_OK )
								{
									VDB4DJournalData* jdata = new VDB4DJournalData(globaloperation, logAction,contextID, GetContextExtraData( contextID),timeStamp, blobnumber ,xTableID);
									*outJournalData = jdata;
									if (!path.IsEmpty())
									{
										jdata->SetPath(path);
									}
								}
							}
							break;

						case DB4D_Log_DeleteRecord:
						case DB4D_Log_TruncateTable:
							{
								sLONG recordNumber;
								if ( error == VE_OK )
									error = fFileStream->GetLong(recordNumber);
								/*
								sLONG tableIndex;
								if ( error == VE_OK )
									error = fFileStream->GetLong(tableIndex);
								*/
								VUUID xTableID;
								if ( error == VE_OK )
									error = xTableID.ReadFromStream(fFileStream);

								if ( error == VE_OK )
									*outJournalData = new VDB4DJournalData(globaloperation, logAction,contextID, GetContextExtraData( contextID),timeStamp,recordNumber,xTableID);
							}
							break;

						case DB4D_Log_CreateContextWithUserUUID:
							{
								VUUID userID;
								error = userID.ReadFromStream(fFileStream);
								if (error == VE_OK)
									*outJournalData = new VDB4DJournalData(globaloperation, logAction,contextID, GetContextExtraData( contextID),timeStamp,userID);
							}
							break;
						
						case DB4D_Log_CreateContextWithExtra:
							{
								VValueBag *bag = new VValueBag;
								if (bag != NULL)
								{
									// the extra data is always stored in little endian
									Boolean oldNeedSwap = fFileStream->NeedSwap();
									fFileStream->SetLittleEndian();
									error = bag->ReadFromStream(fFileStream);
									fFileStream->SetNeedSwap( oldNeedSwap);
									
									if (error == VE_OK)
									{
										try
										{
											fContextExtraByID[contextID] = bag;
										}
										catch(...)
										{
										}
										*outJournalData = new VDB4DJournalData(globaloperation, logAction,contextID, GetContextExtraData( contextID),timeStamp);
									}
								}
								else
								{
									error = memfull;
								}
								ReleaseRefCountable( &bag);
							}
							break;

						case DB4D_Log_CreateBlob:
						case DB4D_Log_ModifyBlob:
							{
								VString path;

								sLONG lenblob = 0;
								sLONG blobNumber;
								if ( error == VE_OK )
									error = fFileStream->GetLong(blobNumber);

								if (blobNumber == -2)
								{
									sLONG lenpath = 0;
									error = fFileStream->GetLong(lenpath);
									if (lenpath > 0)
									{
										tempBuffer<256> buff(len);
										error = fFileStream->GetWords((sWORD*)buff.GetPtr(), &lenpath);
										path.FromBlock(buff.GetPtr(), lenpath * sizeof(UniChar), VTC_UTF_16);
									}
								}


								VUUID xTableID;
								if ( error == VE_OK )
									error = xTableID.ReadFromStream(fFileStream);

								curpos = fFileStream->GetPos();
								if ( error == VE_OK )
								{
									error = fFileStream->GetLong(lenblob);
									error = fFileStream->SetPosByOffset(lenblob);
								}
								if ( error == VE_OK )
								{
									VDB4DJournalData* jdata = new VDB4DJournalData(globaloperation, logAction,contextID, GetContextExtraData( contextID),timeStamp, blobNumber, lenblob, xTableID, curpos, fFileStream);
									*outJournalData = jdata;
									if (!path.IsEmpty())
									{
										jdata->SetPath(path);
									}
								}
							}
							break;

						case DB4D_Log_SaveSeqNum:
							{
								sLONG8 seqnum;
								if ( error == VE_OK )
									error = fFileStream->GetLong8(seqnum);
								/*
								sLONG tableIndex;
								if ( error == VE_OK )
								error = fFileStream->GetLong(tableIndex);
								*/
								VUUID xTableID;
								if ( error == VE_OK )
									error = xTableID.ReadFromStream(fFileStream);

								if ( error == VE_OK )
									*outJournalData = new VDB4DJournalData(globaloperation, logAction,contextID, GetContextExtraData( contextID), timeStamp, seqnum, xTableID, true);
							}
							break;

						default:
							assert(false);
							break;
					}
				}
				}
				sLONG lenEnd;
				if ( error == VE_OK )
				{
					error = fFileStream->GetLong(lenEnd);
					if (len != lenEnd)
						error = VE_UNIMPLEMENTED;
				}

				uLONG operationTagEnd;
				if (error == VE_OK)
				{
					error = fFileStream->GetLong((uLONG&)operationTagEnd);
					if (operationTagEnd != kTagLogDB4DEnd)
						error = VE_UNIMPLEMENTED;
				}
			}
			else
			{
				error = VE_UNIMPLEMENTED; // bad file
			}

			if ( error != VE_OK )
			{
				if ( outJournalData && *outJournalData )
				{
					(*outJournalData)->Release();
					*outJournalData = NULL;
				}
			}
			else
			{
				outOperation = ++fCurrentOperation;
				if ( outJournalData && *outJournalData )
				{
					if ( fCurrentData )
						fCurrentData->Release();
					fCurrentData = *outJournalData;
					fCurrentData->Retain();
				}
			}
		}
	}
	else
	{
		error = VE_UNIMPLEMENTED; // not initialized
	}

	if (outGlobalOperation != NULL)
		*outGlobalOperation = globaloperation;
	
	return error;
}
Exemple #12
0
inline T from_str(std::string x){
  std::stringstream buff(x);
  T temp;
  buff >> temp;
  return temp;
}
Exemple #13
0
QByteArray GraphExport::generateBin()
{
    GraphCurve *c = m_curves->at(ui->curveBox->itemData(ui->curveBox->currentIndex()).toInt())->curve;
    Q_ASSERT(c);

    QByteArray bin;
    QBuffer buff(&bin);
    buff.open(QIODevice::WriteOnly);

    bool big = !ui->endianBox->currentIndex();
    int idxW = (1 << ui->idxWidthBox->currentIndex());

    for(quint32 i = 0; i < c->getSize(); ++i)
    {
        emit updateProgress(i*100/c->getSize());

        if(ui->indexBox->isChecked())
        {
            quint64 idx = i;
            Utils::swapEndian(idx);
            if(!big)
                Utils::swapEndian(((char*)&idx)+(sizeof(idx)-idxW), idxW);
            buff.write(((char*)&idx)+(sizeof(idx)-idxW), idxW);
        }

        qreal s = c->sample(i).y();
        switch(c->getDataType())
        {
            case NUM_FLOAT:
            {
                float f = s;
                buff.write((char*)&f, sizeof(f));
                break;
            }
            case NUM_DOUBLE:
                buff.write((char*)&s, sizeof(s));
                break;
            default:
            {
                QVariant var(s);
                switch(c->getDataType())
                {
                    case NUM_UINT8:
                    case NUM_INT8:
                    {
                        quint8 y = var.toInt();
                        if(big) Utils::swapEndian((char*)&y, sizeof(y));
                        buff.write((char*)&y, sizeof(y));
                        break;
                    }
                    case NUM_UINT16:
                    case NUM_INT16:
                    {
                        quint16 y = var.toInt();
                        if(big) Utils::swapEndian((char*)&y, sizeof(y));
                        buff.write((char*)&y, sizeof(y));
                        break;
                    }
                    case NUM_UINT32:
                    case NUM_INT32:
                    {
                        quint32 y = var.toInt();
                        if(big) Utils::swapEndian((char*)&y, sizeof(y));
                        buff.write((char*)&y, sizeof(y));
                        break;
                    }
                    case NUM_UINT64:
                    case NUM_INT64:
                    {
                        quint64 y = var.toLongLong();
                        if(big) Utils::swapEndian((char*)&y, sizeof(y));
                        buff.write((char*)&y, sizeof(y));
                        break;
                    }
                }
                break;
            }
        }
    }
    buff.close();
    return bin;
}
Exemple #14
0
bool CTGitPath::HasStashDir() const
{
	CString topdir;
	if(!GitAdminDir::HasAdminDir(GetWinPathString(),&topdir))
	{
		return false;
	}

	CString dotGitPath;
	GitAdminDir::GetAdminDirPath(topdir, dotGitPath);

	if (!!PathFileExists(dotGitPath + _T("refs\\stash")))
		return true;

	CAutoFile hfile = CreateFile(dotGitPath + _T("packed-refs"), GENERIC_READ, 
		FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
	if (!hfile)
		return false;

	DWORD filesize = ::GetFileSize(hfile, nullptr);
	if (filesize == 0)
		return false;

	DWORD size = 0;
	std::unique_ptr<char[]> buff(new char[filesize + 1]);
	ReadFile(hfile, buff.get(), filesize, &size, nullptr);
	buff.get()[filesize] = '\0';

	if (size != filesize)
		return false;

	for (DWORD i = 0; i < filesize;)
	{
		if (buff[i] == '#' || buff[i] == '^')
		{
			while (buff[i] != '\n')
			{
				++i;
				if (i == filesize)
					break;
			}
			++i;
		}

		if (i >= filesize)
			break;

		while (buff[i] != ' ')
		{
			++i;
			if (i == filesize)
				break;
		}

		++i;
		if (i >= filesize)
			break;

		if (i <= filesize - 10 && (buff[i + 10] == '\n' || buff[i + 10] == '\0') && !strncmp("refs/stash", buff.get() + i, 10))
			return true;
		while (buff[i] != '\n')
		{
			++i;
			if (i == filesize)
				break;
		}

		while (buff[i] == '\n')
		{
			++i;
			if (i == filesize)
				break;
		}
	}
	return false;
}
Exemple #15
0
Handle process_env_dispatch_c(TaskData *mdTaskData, Handle args, Handle code)
{
    unsigned c = get_C_unsigned(mdTaskData, DEREFWORDHANDLE(code));
    switch (c)
    {
    case 0: /* Return the program name. */
        return SAVE(C_string_to_Poly(mdTaskData, userOptions.programName));

    case 1: /* Return the argument list. */
        return convert_string_list(mdTaskData, userOptions.user_arg_count, userOptions.user_arg_strings);

    case 14: /* Return a string from the environment. */
        {
            TempString buff(args->Word());
            if (buff == 0) raise_syscall(mdTaskData, "Insufficient memory", ENOMEM);
            TCHAR *res = _tgetenv(buff);
            if (res == NULL) raise_syscall(mdTaskData, "Not Found", 0);
            else return SAVE(C_string_to_Poly(mdTaskData, res));
        }

    case 21: // Return the whole environment.  Only available in Posix.ProcEnv.
        {
            /* Count the environment strings */
            int env_count = 0;
            while (environ[env_count] != NULL) env_count++;
            return convert_string_list(mdTaskData, env_count, environ);
        }

    case 15: /* Return the success value. */
        return Make_arbitrary_precision(mdTaskData, EXIT_SUCCESS);

    case 16: /* Return a failure value. */
        return Make_arbitrary_precision(mdTaskData, EXIT_FAILURE);

    case 17: /* Run command. */
        {
            TempString buff(args->Word());
            if (buff == 0) raise_syscall(mdTaskData, "Insufficient memory", ENOMEM);
            int res = -1;
#if (defined(_WIN32) && ! defined(__CYGWIN__))
            // Windows.
            TCHAR *argv[4];
            argv[0] = _tgetenv(_T("COMSPEC")); // Default CLI.
            if (argv[0] == 0) argv[0] = (TCHAR*)_T("cmd.exe"); // Win NT etc.
            argv[1] = (TCHAR*)_T("/c");
            argv[2] = buff;
            argv[3] = NULL;
            // If _P_NOWAIT is given the result is the process handle.
            // spawnvp does any necessary path searching if argv[0]
            // does not contain a full path.
            intptr_t pid = _tspawnvp(_P_NOWAIT, argv[0], argv);
            if (pid == -1)
                raise_syscall(mdTaskData, "Function system failed", errno);
#else
            // Cygwin and Unix
            char *argv[4];
            argv[0] = (char*)"sh";
            argv[1] = (char*)"-c";
            argv[2] = buff;
            argv[3] = NULL;
#if (defined(__CYGWIN__))
            CygwinSpawnRequest request(argv);
            processes->MakeRootRequest(mdTaskData, &request);
            int pid = request.pid;
            if (pid < 0)
                raise_syscall(mdTaskData, "Function system failed", errno);
#else
            // We need to break this down so that we can unblock signals in the
            // child process.
            // The Unix "system" function seems to set SIGINT and SIGQUIT to
            // SIG_IGN in the parent so that the wait will not be interrupted.
            // That may make sense in a single-threaded application but is
            // that right here?
            int pid = vfork();
            if (pid == -1)
                raise_syscall(mdTaskData, "Function system failed", errno);
            else if (pid == 0)
            { // In child
                sigset_t sigset;
                sigemptyset(&sigset);
                sigprocmask(SIG_SETMASK, &sigset, 0);
                // Reset other signals?
                execve("/bin/sh", argv, environ);
                _exit(1);
            }
#endif
#endif
            while (true)
            {
                try
                {
                // Test to see if the child has returned.
#if (defined(_WIN32) && ! defined(__CYGWIN__))
                    switch (WaitForSingleObject((HANDLE)pid, 0))
                    {
                    case WAIT_OBJECT_0:
                        {
                            DWORD result;
                            BOOL fResult = GetExitCodeProcess((HANDLE)pid, &result);
                            if (! fResult)
                                raise_syscall(mdTaskData, "Function system failed", -(int)GetLastError());
                            CloseHandle((HANDLE)pid);
                            return Make_arbitrary_precision(mdTaskData, result);
                        }
                    case WAIT_FAILED:
                        raise_syscall(mdTaskData, "Function system failed", -(int)GetLastError());
                    }
                    // Wait for the process to exit or for the timeout
                    WaitHandle waiter((HANDLE)pid);
                    processes->ThreadPauseForIO(mdTaskData, &waiter);
#else
                    int wRes = waitpid(pid, &res, WNOHANG);
                    if (wRes > 0)
                        break;
                    else if (wRes < 0)
                    {
                        raise_syscall(mdTaskData, "Function system failed", errno);
                    }
                    // In Unix the best we can do is wait.  This may be interrupted
                    // by SIGCHLD depending on where signals are processed.
                    // One possibility is for the main thread to somehow wake-up
                    // the thread when it processes a SIGCHLD.
                    processes->ThreadPause(mdTaskData);
#endif
                }
                catch (...)
                {
                    // Either IOException or KillException.
                    // We're abandoning the wait.  This will leave
                    // a zombie in Unix.
#if (defined(_WIN32) && ! defined(__CYGWIN__))
                    CloseHandle((HANDLE)pid);
#endif
                    throw;
                }
            }
            return Make_arbitrary_precision(mdTaskData, res);
        }

    case 18: /* Register function to run at exit. */
        {
            PLocker locker(&atExitLock);
            if (! exiting)
            {
                PolyObject *cell = alloc(mdTaskData, 2);
                cell->Set(0, at_exit_list);
                cell->Set(1, DEREFWORD(args));
                at_exit_list = cell;
            }
            return Make_arbitrary_precision(mdTaskData, 0);
        }

    case 19: /* Return the next function in the atExit list and set the
                "exiting" flag to true. */
        {
            PLocker locker(&atExitLock);
            Handle res;
            exiting = true; /* Ignore further calls to atExit. */
            if (at_exit_list == TAGGED(0))
                raise_syscall(mdTaskData, "List is empty", 0);
            PolyObject *cell = at_exit_list.AsObjPtr();
            res = SAVE(cell->Get(1));
            at_exit_list = cell->Get(0);
            return res;
        }

    case 20: /* Terminate without running the atExit list or flushing buffers. */
        {
            /* I don't like terminating without some sort of clean up
               but we'll do it this way for the moment. */
            int i = get_C_int(mdTaskData, DEREFWORDHANDLE(args));
            _exit(i);
        }

        /************ Error codes **************/

    case 2: /* Get the name of a numeric error message. */
        {
            char buff[40];
            int e = get_C_int(mdTaskData, DEREFWORDHANDLE(args));
            Handle  res;
            /* First look to see if we have the name in
               the error table. They should generally all be
               there. */
            const char *errorMsg = stringFromErrorCode(e);
            if (errorMsg != NULL)
                return SAVE(C_string_to_Poly(mdTaskData, errorMsg));
            /* We get here if there's an error which isn't in the table. */
#if (defined(_WIN32) && ! defined(__CYGWIN__))
            /* In the Windows version we may have both errno values
               and also GetLastError values.  We convert the latter into
               negative values before returning them. */
            if (e < 0)
            {
                sprintf(buff, "WINERROR%0d", -e);
                res = SAVE(C_string_to_Poly(mdTaskData, buff));
                return res;
            }
            else
#endif
            {
                sprintf(buff, "ERROR%0d", e);
                res = SAVE(C_string_to_Poly(mdTaskData, buff));
            }
            return res;
        }

    case 3: /* Get the explanatory message for an error. */
        {
            return errorMsg(mdTaskData, get_C_int(mdTaskData, DEREFWORDHANDLE(args)));
        }

    case 4: /* Try to convert an error string to an error number. */
        {
            char buff[40];
            /* Get the string. */
            Poly_string_to_C(DEREFWORD(args), buff, sizeof(buff));
            /* Look the string up in the table. */
            int err = 0;
            if (errorCodeFromString(buff, &err))
                return Make_arbitrary_precision(mdTaskData, err);
            /* If we don't find it then it may have been a constructed
               error name. */
            if (strncmp(buff, "ERROR", 5) == 0)
            {
                int i = atoi(buff+5);
                if (i > 0) return Make_arbitrary_precision(mdTaskData, i);
            }
#if (defined(_WIN32) && ! defined(__CYGWIN__))
            if (strncmp(buff, "WINERROR", 8) == 0)
            {
                int i = atoi(buff+8);
                if (i > 0) return Make_arbitrary_precision(mdTaskData, -i);
            }
#endif
            return Make_arbitrary_precision(mdTaskData, 0);
        }

        /************ Directory/file paths **************/

    case 5: /* Return the string representing the current arc. */
        return SAVE(C_string_to_Poly(mdTaskData, "."));

    case 6: /* Return the string representing the parent arc. */
        /* I don't know that this exists in MacOS. */
        return SAVE(C_string_to_Poly(mdTaskData, ".."));

    case 7: /* Return the string representing the directory separator. */
        return SAVE(C_string_to_Poly(mdTaskData, DEFAULTSEPARATOR));

    case 8: /* Test the character to see if it matches a separator. */
        {
            int e = get_C_int(mdTaskData, DEREFWORDHANDLE(args));
            if (ISPATHSEPARATOR(e))
                return Make_arbitrary_precision(mdTaskData, 1);
            else return Make_arbitrary_precision(mdTaskData, 0);
        }

    case 9: /* Are names case-sensitive? */
#if (defined(_WIN32) && ! defined(__CYGWIN__))
        /* Windows - no. */
        return Make_arbitrary_precision(mdTaskData, 0);
#else
        /* Unix - yes. */
        return Make_arbitrary_precision(mdTaskData, 1);
#endif

        // These are no longer used.  The code is handled entirely in ML.
    case 10: /* Are empty arcs redundant? */
        /* Unix and Windows - yes. */
        return Make_arbitrary_precision(mdTaskData, 1);

    case 11: /* Match the volume name part of a path. */
        {
            const TCHAR *volName = NULL;
            int  isAbs = 0;
            int  toRemove = 0;
            PolyWord path = DEREFHANDLE(args);
            /* This examines the start of a string and determines
               how much of it represents the volume name and returns
               the number of characters to remove, the volume name
               and whether it is absolute.
               One would assume that if there is a volume name then it
               is absolute but there is a peculiar form in Windows/DOS
               (e.g. A:b\c) which means the file b\c relative to the
               currently selected directory on the volume A.
            */
#if (defined(_WIN32) && ! defined(__CYGWIN__))
            TempString buff(path);
            if (buff == 0) raise_syscall(mdTaskData, "Insufficient memory", ENOMEM);
            size_t length = _tcslen(buff);
            if (length >= 2 && buff[1] == ':')
            { /* Volume name? */
                if (length >= 3 && ISPATHSEPARATOR(buff[2]))
                {
                    /* Absolute path. */
                    toRemove = 3; isAbs = 1;
                }
                else { toRemove = 2; isAbs = 0; }
                volName = buff; buff[2] = '\0';
            }
            else if (length > 3 &&
                     ISPATHSEPARATOR(buff[0]) &&
                     ISPATHSEPARATOR(buff[1]) &&
                     ! ISPATHSEPARATOR(buff[2]))
            { /* UNC name? */
                int i;
                /* Skip the server name. */
                for (i = 3; buff[i] != 0 && !ISPATHSEPARATOR(buff[i]); i++);
                if (ISPATHSEPARATOR(buff[i]))
                {
                    i++;
                    /* Skip the share name. */
                    for (; buff[i] != 0 && !ISPATHSEPARATOR(buff[i]); i++);
                    toRemove = i;
                    if (buff[i] != 0) toRemove++;
                    isAbs = 1;
                    volName = buff;
                    buff[i] = '\0';
                }
            }
            else if (ISPATHSEPARATOR(buff[0]))
                /* \a\b strictly speaking is relative to the
                   current drive.  It's much easier to treat it
                   as absolute. */
                { toRemove = 1; isAbs = 1; volName = _T(""); }
#else
            /* Unix - much simpler. */
            char toTest = 0;
            if (IS_INT(path)) toTest = UNTAGGED(path);
            else {
                PolyStringObject * ps = (PolyStringObject *)path.AsObjPtr();
                if (ps->length > 1) toTest = ps->chars[0];
            }
            if (ISPATHSEPARATOR(toTest))
                { toRemove = 1; isAbs = 1; volName = ""; }
#endif
            /* Construct the result. */
            {
                Handle sVol = SAVE(C_string_to_Poly(mdTaskData, volName));
                Handle sRes = ALLOC(3);
                DEREFWORDHANDLE(sRes)->Set(0, TAGGED(toRemove));
                DEREFHANDLE(sRes)->Set(1, DEREFWORDHANDLE(sVol));
                DEREFWORDHANDLE(sRes)->Set(2, TAGGED(isAbs));
                return sRes;
            }
        }

    case 12: /* Construct a name from a volume and whether it is
                absolute. */
        {
            unsigned isAbs = get_C_unsigned(mdTaskData, DEREFHANDLE(args)->Get(1));
            PolyWord volName = DEREFHANDLE(args)->Get(0);
            /* In Unix the volume name will always be empty. */
            if (isAbs == 0)
                return SAVE(volName);
            /* N.B. The arguments to strconcatc are in reverse. */
            else return strconcatc(mdTaskData,
                                   SAVE(C_string_to_Poly(mdTaskData, DEFAULTSEPARATOR)),
                                   SAVE(volName));
        }

    case 13: /* Is the string a valid file name? */
        {
            PolyWord volName = DEREFWORD(args);
            // First check for NULL.  This is not allowed in either Unix or Windows.
            if (IS_INT(volName))
            {
                if (volName == TAGGED(0))
                    return Make_arbitrary_precision(mdTaskData, 0);
            }
            else
            {
                PolyStringObject * volume = (PolyStringObject *)(volName.AsObjPtr());
                for (POLYUNSIGNED i = 0; i < volume->length; i++)
                {
                    if (volume->chars[i] == '\0')
                        return Make_arbitrary_precision(mdTaskData, 0);
                }
            }
#if (defined(_WIN32) && ! defined(__CYGWIN__))
            // We need to look for certain invalid characters but only after
            // we've converted it to Unicode if necessary.
            TempString name(volName);
            for (const TCHAR *p = name; *p != 0; p++)
            {
                switch (*p)
                {
                case '<': case '>': case ':': case '"': 
                case '\\': case '|': case '?': case '*': case '\0':
#if (0)
                // This currently breaks the build.
                case '/':
#endif
                    return Make_arbitrary_precision(mdTaskData, 0);
                }
                if (*p >= 0 && *p <= 31) return Make_arbitrary_precision(mdTaskData, 0);
            }
            // Should we check for special names such as aux, con, prn ??
            return Make_arbitrary_precision(mdTaskData, 1);
#else
            // That's all we need for Unix.
            // TODO: Check for /.  It's invalid in a file name arc.
            return Make_arbitrary_precision(mdTaskData, 1);
#endif
        }

        // A group of calls have now been moved to poly_specific.
        // This entry is returned for backwards compatibility.
    case 100: case 101: case 102: case 103: case 104: case 105:
        return poly_dispatch_c(mdTaskData, args, code);

    default:
        {
            char msg[100];
            sprintf(msg, "Unknown environment function: %d", c);
            raise_exception_string(mdTaskData, EXC_Fail, msg);
            return 0;
        }
    }
}
Exemple #16
0
// this is the actual "work" function. All the fun happens here
void
Responder::run_test(float threshold)
{
    STATS statsCurrent; //, statsPrev;
    memset(&statsCurrent, 0x00, sizeof(STATS));
    if (_opt.test_iterations > 0)
    {
        update_and_print_parameters(statsCurrent, _delay);
        statsCurrent.delay = _opt.delay_min;
    }
    ///////////////////////////////////////////////////////////////////////////
    uint64_t trigger_count = 0;
    size_t success_count = 0;
    uint64_t num_total_samps_test = 0;

    std::vector<std::complex<float> > buff(_opt.samps_per_buff);
    while (not s_stop_signal_called && _return_code == RETCODE_OK)
    {
        // get samples from rx stream.
        uhd::rx_metadata_t rx_md;
        size_t num_rx_samps = _rx_stream->recv(&buff.front(), buff.size(), rx_md, _opt.timeout);
        // handle errors
        if(handle_rx_errors(rx_md.error_code, num_rx_samps) )
        {
            break;
        }
        // detect falling edges, send respond pulse and check if response could be sent in time
        trigger_count = detect_respond_pulse_count(statsCurrent, buff, trigger_count, num_rx_samps, threshold, rx_md.time_spec);

        // increase counters for single test and overall test samples count.
        _num_total_samps += num_rx_samps;
        num_total_samps_test += num_rx_samps;

        // control section for interactive mode
        if (_opt.test_iterations == 0) // == "interactive'
        {
            if(handle_interactive_control() )
                break;
        }

        // control section for test mode
        if (_opt.test_iterations > 0) // == test mode / batch-mode
        {
            int step_return = test_step_finished(trigger_count, num_total_samps_test, statsCurrent, success_count);
            if(step_return == -2) // == test is finished with all desired delay steps
                break;
            else if(step_return == -1) // just continue test
                continue;
            else // test with one delay is finished
            {
                success_count = (size_t) step_return;
                trigger_count = 0;
                num_total_samps_test = 0;
                memset(&statsCurrent, 0x00, sizeof(STATS)); // reset current stats for next test iteration
                statsCurrent.delay = _delay;
            }
        } // end test mode control section
    }// exit outer loop after stop signal is called, test is finished or other break condition is met

    if (s_stop_signal_called)
        _return_code = RETCODE_MANUAL_ABORT;
}
Exemple #17
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args;
    std::string wire;
    double seconds_in_future;
    size_t total_num_samps;
    double rate;
    float ampl;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "single uhd device address args")
        ("wire", po::value<std::string>(&wire)->default_value(""), "the over the wire type, sc16, sc8, etc")
        ("secs", po::value<double>(&seconds_in_future)->default_value(1.5), "number of seconds in the future to transmit")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(10000), "total number of samples to transmit")
        ("rate", po::value<double>(&rate)->default_value(100e6/16), "rate of outgoing samples")
        ("ampl", po::value<float>(&ampl)->default_value(float(0.3)), "amplitude of each sample")
        ("dilv", "specify to disable inner-loop verbose")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD TX Timed Samples %s") % desc << std::endl;
        return ~0;
    }

    bool verbose = vm.count("dilv") == 0;

    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

    //set the tx sample rate
    std::cout << boost::format("Setting TX Rate: %f Msps...") % (rate/1e6) << std::endl;
    usrp->set_tx_rate(rate);
    std::cout << boost::format("Actual TX Rate: %f Msps...") % (usrp->get_tx_rate()/1e6) << std::endl << std::endl;

    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;
    usrp->set_time_now(uhd::time_spec_t(0.0));

    //create a transmit streamer
    uhd::stream_args_t stream_args("fc32", wire); //complex floats
    uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args);

    //allocate buffer with data to send
    std::vector<std::complex<float> > buff(tx_stream->get_max_num_samps(), std::complex<float>(ampl, ampl));

    //setup metadata for the first packet
    uhd::tx_metadata_t md;
    md.start_of_burst = false;
    md.end_of_burst = false;
    md.has_time_spec = true;
    md.time_spec = uhd::time_spec_t(seconds_in_future);

    //the first call to send() will block this many seconds before sending:
    const double timeout = seconds_in_future + 0.1; //timeout (delay before transmit + padding)

    size_t num_acc_samps = 0; //number of accumulated samples
    while(num_acc_samps < total_num_samps){
        size_t samps_to_send = std::min(total_num_samps - num_acc_samps, buff.size());

        //send a single packet
        size_t num_tx_samps = tx_stream->send(
            &buff.front(), samps_to_send, md, timeout
        );

        //do not use time spec for subsequent packets
        md.has_time_spec = false;

        if (num_tx_samps < samps_to_send) std::cerr << "Send timeout..." << std::endl;
        if(verbose) std::cout << boost::format("Sent packet: %u samples") % num_tx_samps << std::endl;

        num_acc_samps += num_tx_samps;
    }

    //send a mini EOB packet
    md.end_of_burst   = true;
    tx_stream->send("", 0, md);

    std::cout << std::endl << "Waiting for async burst ACK... " << std::flush;
    uhd::async_metadata_t async_md;
    bool got_async_burst_ack = false;
    //loop through all messages for the ACK packet (may have underflow messages in queue)
    while (not got_async_burst_ack and tx_stream->recv_async_msg(async_md, timeout)){
        got_async_burst_ack = (async_md.event_code == uhd::async_metadata_t::EVENT_CODE_BURST_ACK);
    }
    std::cout << (got_async_burst_ack? "success" : "fail") << std::endl;

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return EXIT_SUCCESS;
}
  virtual HandleRequestReply process(const RequestInfo& requestInfo, RequestOutput& requestOutput) {
    std::string buff("Stats and status\n\n");

    WebHandlerInternal* const webHandlerInternal = WebHandlerInternal::bindIfExists();
    if (webHandlerInternal) {
      buff << webHandlerInternal->getHandlerStats() << "\n";
    }

    MotionInfo motionInfo;
    motionSensor.getMotionValue(&motionInfo);
    buff << "motion: " << (motionInfo.currMotionDetected ? "y" : "n") << "\n";
    buff << "motion_last_change: ";
    INT2BUFF(motionInfo.lastChangedHour); buff << ":";
    INT2BUFF(motionInfo.lastChangedMin); buff << ":";
    INT2BUFF(motionInfo.lastChangedSec); buff << "\n";
    
    buff << "light_sensor: "; INT2BUFF(lightSensor.getLightValue()); buff << "\n";
    buff << "display_mode: " << display.getInternalDisplayMode() << "\n";
    buff << "led_strip_mode: " << ledStrip.getInternalLedStripMode() << "\n";

    MqttClientInfo mqttClientInfo;
    mqttClient.getMqttClientInfo(&mqttClientInfo);
    buff << "\n";
    buff << "mqttBrokerConnected: " << (mqttClientInfo.mqttBrokerConnected ? "yes" : "no") << "\n";
    buff << "mqttLastLoopRc: "; INT2BUFF(mqttClientInfo.last_loop_rc);
    buff << " (" << mqttClient.getStrError(mqttClientInfo.last_loop_rc) << ")" << "\n";
    buff << "mqttBrokerIp: " << mqttClientInfo.mqttBrokerIp << "\n";
    buff << "mqttBrokerPort: "; INT2BUFF(mqttClientInfo.mqttBrokerPort); buff << "\n";
    buff << "mqttKeepAlive (secs): "; INT2BUFF(mqttClientInfo.mqttKeepAlive); buff << "\n";
    buff << "mqttConnectAttempts: "; INT2BUFF(mqttClientInfo.connectAttempts); buff << "\n";
    buff << "mqttConnects: "; INT2BUFF(mqttClientInfo.connects); buff << "\n";
    buff << "mqttDisconnects: "; INT2BUFF(mqttClientInfo.disconnects); buff << "\n";
    buff << "mqttPublishes: "; INT2BUFF(mqttClientInfo.publishes); buff << "\n";
    buff << "mqttPublishedMotions: "; INT2BUFF(mqttClientInfo.publishedMotions); buff << "\n";
    buff << "mqttPublishesDropped: "; INT2BUFF(mqttClientInfo.publishesDropped); buff << "\n";
    buff << "mqttPublishCallbacks: "; INT2BUFF(mqttClientInfo.publishCallbacks); buff << "\n";
    buff << "mqttMessages: "; INT2BUFF(mqttClientInfo.messages); buff << "\n";
    buff << "mqttTicks: "; INT2BUFF(mqttClientInfo.ticks); buff << "\n";

    DictionaryStatus dictionaryStatus;
    dictionary.getDictionaryStatus(dictionaryStatus);
    buff << "\n";
    buff << "dictSize: "; INT2BUFF(dictionary.size()); buff << "\n";
    buff << "dictTicks: "; INT2BUFF(dictionaryStatus.ticks); buff << "\n";
    buff << "dictAdds: "; INT2BUFF(dictionaryStatus.entriesAdded); buff << "\n";
    buff << "dictRemoves: "; INT2BUFF(dictionaryStatus.entriesRemoved); buff << "\n";
    buff << "dictExpires: "; INT2BUFF(dictionaryStatus.entriesExpired); buff << "\n";

    if (!dictionary.empty()) {
      buff << "\n";
      bool found;
      std::string currKey;
      std::string currData = dictionary.getFirst(currKey, &found);
      while (found) {
	buff << "dict: " << currKey << " => " << currData << "\n";
	currData = dictionary.getNext(currKey, &found);
      }
    }
    
    setHeaderContentTypeText(requestOutput);
    ADD_BODY(buff);
    return replyOk;
  }
Exemple #19
0
// ÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑ
//		¥ ParseAndLink												/*e*/ Static
// ÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑ
// Prepares the tnt basic code text handle passed as a runnable program.
// if it throws the semi complete parse is held in sParsingProgram
CProgram *CProgram::ParseAndLink(
	Handle			inCode,
	bool			&outContainsErrors,
	const StringPtr	inProgramName)
{
	Handle			adoptedHandle=inCode;
	
	ThrowIfOSErr_(::HandToHand(&adoptedHandle));
	
	// Append a CR to the handle. This is done as every statement has to be followed by a cr in the same way that every
	// statement in c has be followed by a ;. A lot of people miss out the trailing cr so add one now.
    // also append double null, as is required by parser
    Size            sz=::GetHandleSize(adoptedHandle);
	ThrowIfOSErr_(::BetterSetHandleSize(adoptedHandle,sz+4,'\r'));
    (*adoptedHandle)[sz+2]=0;
    (*adoptedHandle)[sz+3]=0;

	// Convert mac line endings to unix line endings for full on parsing using flex buffer class
	CFlexBuffer::MacToUnixCR(*adoptedHandle,::GetHandleSize(adoptedHandle));
	
	delete sParsingProgram;			// semi complete program - probably from a failed parse
	sParsingProgram=0;

	// Preparse the code now to get a list of procedures
	CProcNode		*procs=ExtractProcedures(adoptedHandle);
	
	sParsingProgram=new CProgram(adoptedHandle,procs);
	ThrowIfMemFull_(sParsingProgram);
	
	gLineno=1;

	{
		UHandleLocker	locked(adoptedHandle,true);

		CFlexBuffer		buff(*adoptedHandle,::GetHandleSize(adoptedHandle),&TBParser::AllocAndSwitchToBuffer,&TBParser::DeallocBuffer,&TBParser::GetCurrentLexOffset);
		
		if (basicparse())
			;//Throw_(-1);	// misc error - if this happens find out why and reclassify the error code but it shouldn't happen
		
		// check for parsing scopes that have been left open, such as when an 'end proc' is missing
		STextRange		loc(GetCurrentTokenLoc());

		loc.line-=2;	// drop the two added crs so that the line number for any generated msgs is correct		
		sParsingProgram->CheckParsingScope(loc,1);		// should only be the root scope left
	}

	outContainsErrors=sParsingProgram->GetErrors().CountElements() || sParsingProgram->mMiscErrorFlag;
	
	if (!outContainsErrors)			// no errors, continue to link stage...
		sParsingProgram->Link();

	// check for errors again
	outContainsErrors=sParsingProgram->GetErrors().CountElements() || sParsingProgram->mMiscErrorFlag;

	CProgram		*result=0;
	result=sParsingProgram;

	sParsingProgram=0;
	basicin=0;
	
	// Finally store the name of the resource as the program name
	if (inProgramName[0])
		LString::CopyPStr(inProgramName,result->mProgramName);
	
	return result;
}
Exemple #20
0
/***********************************************************************
 * Main function
 **********************************************************************/
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args, wave_type, ant, subdev, ref, otw;
    size_t spb;
    double rate, freq, gain, wave_freq, bw;
    float ampl;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "single uhd device address args")
        ("spb", po::value<size_t>(&spb)->default_value(0), "samples per buffer, 0 for default")
        ("rate", po::value<double>(&rate), "rate of outgoing samples")
        ("freq", po::value<double>(&freq), "RF center frequency in Hz")
        ("ampl", po::value<float>(&ampl)->default_value(float(0.3)), "amplitude of the waveform [0 to 0.7]")
        ("gain", po::value<double>(&gain), "gain for the RF chain")
        ("ant", po::value<std::string>(&ant), "daughterboard antenna selection")
        ("subdev", po::value<std::string>(&subdev), "daughterboard subdevice specification")
        ("bw", po::value<double>(&bw), "daughterboard IF filter bandwidth in Hz")
        ("wave-type", po::value<std::string>(&wave_type)->default_value("CONST"), "waveform type (CONST, SQUARE, RAMP, SINE)")
        ("wave-freq", po::value<double>(&wave_freq)->default_value(0), "waveform frequency in Hz")
        ("ref", po::value<std::string>(&ref)->default_value("internal"), "clock reference (internal, external, mimo)")
        ("otw", po::value<std::string>(&otw)->default_value("sc16"), "specify the over-the-wire sample mode")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD TX Waveforms %s") % desc << std::endl;
        return ~0;
    }

    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);

    //Lock mboard clocks
    usrp->set_clock_source(ref);

    //always select the subdevice first, the channel mapping affects the other settings
    if (vm.count("subdev")) usrp->set_tx_subdev_spec(subdev);

    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

    //set the sample rate
    if (not vm.count("rate")){
        std::cerr << "Please specify the sample rate with --rate" << std::endl;
        return ~0;
    }
    std::cout << boost::format("Setting TX Rate: %f Msps...") % (rate/1e6) << std::endl;
    usrp->set_tx_rate(rate);
    std::cout << boost::format("Actual TX Rate: %f Msps...") % (usrp->get_tx_rate()/1e6) << std::endl << std::endl;

    //set the center frequency
    if (not vm.count("freq")){
        std::cerr << "Please specify the center frequency with --freq" << std::endl;
        return ~0;
    }

    for(size_t chan = 0; chan < usrp->get_tx_num_channels(); chan++) {
        std::cout << boost::format("Setting TX Freq: %f MHz...") % (freq/1e6) << std::endl;
        usrp->set_tx_freq(freq, chan);
        std::cout << boost::format("Actual TX Freq: %f MHz...") % (usrp->get_tx_freq(chan)/1e6) << std::endl << std::endl;

        //set the rf gain
        if (vm.count("gain")){
            std::cout << boost::format("Setting TX Gain: %f dB...") % gain << std::endl;
            usrp->set_tx_gain(gain, chan);
            std::cout << boost::format("Actual TX Gain: %f dB...") % usrp->get_tx_gain(chan) << std::endl << std::endl;
        }

        //set the IF filter bandwidth
        if (vm.count("bw")){
            std::cout << boost::format("Setting TX Bandwidth: %f MHz...") % bw << std::endl;
            usrp->set_tx_bandwidth(bw, chan);
            std::cout << boost::format("Actual TX Bandwidth: %f MHz...") % usrp->get_tx_bandwidth(chan) << std::endl << std::endl;
        }

        //set the antenna
        if (vm.count("ant")) usrp->set_tx_antenna(ant, chan);
    }

    //for the const wave, set the wave freq for small samples per period
    if (wave_freq == 0 and wave_type == "CONST"){
        wave_freq = usrp->get_tx_rate()/2;
    }

    //error when the waveform is not possible to generate
    if (std::abs(wave_freq) > usrp->get_tx_rate()/2){
        throw std::runtime_error("wave freq out of Nyquist zone");
    }
    if (usrp->get_tx_rate()/std::abs(wave_freq) > wave_table_len/2){
        throw std::runtime_error("wave freq too small for table");
    }

    //pre-compute the waveform values
    const wave_table_class wave_table(wave_type, ampl);
    const size_t step = boost::math::iround(wave_freq/usrp->get_tx_rate() * wave_table_len);
    size_t index = 0;

    //create a transmit streamer
    //linearly map channels (index0 = channel0, index1 = channel1, ...)
    uhd::stream_args_t stream_args("fc32", otw);
    for (size_t chan = 0; chan < usrp->get_tx_num_channels(); chan++)
        stream_args.channels.push_back(chan); //linear mapping
    uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args);

    //allocate a buffer which we re-use for each channel
    if (spb == 0) spb = tx_stream->get_max_num_samps()*10;
    std::vector<std::complex<float> > buff(spb);
    std::vector<std::complex<float> *> buffs(usrp->get_tx_num_channels(), &buff.front());

    //setup the metadata flags
    uhd::tx_metadata_t md;
    md.start_of_burst = true;
    md.end_of_burst   = false;
    md.has_time_spec  = true;
    md.time_spec = uhd::time_spec_t(0.1);

    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;
    usrp->set_time_now(uhd::time_spec_t(0.0));

    //Check Ref and LO Lock detect
    std::vector<std::string> sensor_names;
    sensor_names = usrp->get_tx_sensor_names(0);
    if (std::find(sensor_names.begin(), sensor_names.end(), "lo_locked") != sensor_names.end()) {
        uhd::sensor_value_t lo_locked = usrp->get_tx_sensor("lo_locked",0);
        std::cout << boost::format("Checking TX: %s ...") % lo_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(lo_locked.to_bool());
    }
    sensor_names = usrp->get_mboard_sensor_names(0);
    if ((ref == "mimo") and (std::find(sensor_names.begin(), sensor_names.end(), "mimo_locked") != sensor_names.end())) {
        uhd::sensor_value_t mimo_locked = usrp->get_mboard_sensor("mimo_locked",0);
        std::cout << boost::format("Checking TX: %s ...") % mimo_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(mimo_locked.to_bool());
    }
    if ((ref == "external") and (std::find(sensor_names.begin(), sensor_names.end(), "ref_locked") != sensor_names.end())) {
        uhd::sensor_value_t ref_locked = usrp->get_mboard_sensor("ref_locked",0);
        std::cout << boost::format("Checking TX: %s ...") % ref_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(ref_locked.to_bool());
    }

    std::signal(SIGINT, &sig_int_handler);
    std::cout << "Press Ctrl + C to stop streaming..." << std::endl;

    //send data until the signal handler gets called
    while(not stop_signal_called){
        //fill the buffer with the waveform
        for (size_t n = 0; n < buff.size(); n++){
            buff[n] = wave_table(index += step);
        }

        //send the entire contents of the buffer
        tx_stream->send(buffs, buff.size(), md);

        md.start_of_burst = false;
        md.has_time_spec = false;
    }

    //send a mini EOB packet
    md.end_of_burst = true;
    tx_stream->send("", 0, md);

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;
    return 0;
}
Exemple #21
0
/***********************************************************************
 * Main function
 **********************************************************************/
int UHD_SAFE_MAIN(int argc, char *argv[]) {
    uhd::set_thread_priority_safe();

    //transmit variables to be set by po
    std::string tx_args, wave_type, tx_ant, tx_subdev, ref, otw, tx_channels;
    double tx_rate, tx_freq, tx_gain, wave_freq, tx_bw;
    float ampl;

    //receive variables to be set by po
    std::string rx_args, file, type, rx_ant, rx_subdev, rx_channels;
    size_t total_num_samps, spb;
    double rx_rate, rx_freq, rx_gain, rx_bw;
    float settling;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
    ("help", "help message")
    ("tx-args", po::value<std::string>(&tx_args)->default_value(""), "uhd transmit device address args")
    ("rx-args", po::value<std::string>(&rx_args)->default_value(""), "uhd receive device address args")
    ("file", po::value<std::string>(&file)->default_value("usrp_samples.dat"), "name of the file to write binary samples to")
    ("type", po::value<std::string>(&type)->default_value("short"), "sample type in file: double, float, or short")
    ("nsamps", po::value<size_t>(&total_num_samps)->default_value(0), "total number of samples to receive")
    ("settling", po::value<float>(&settling)->default_value(float(0.2)), "settling time (seconds) before receiving")
    ("spb", po::value<size_t>(&spb)->default_value(0), "samples per buffer, 0 for default")
    ("tx-rate", po::value<double>(&tx_rate), "rate of transmit outgoing samples")
    ("rx-rate", po::value<double>(&rx_rate), "rate of receive incoming samples")
    ("tx-freq", po::value<double>(&tx_freq), "transmit RF center frequency in Hz")
    ("rx-freq", po::value<double>(&rx_freq), "receive RF center frequency in Hz")
    ("ampl", po::value<float>(&ampl)->default_value(float(0.3)), "amplitude of the waveform [0 to 0.7]")
    ("tx-gain", po::value<double>(&tx_gain), "gain for the transmit RF chain")
    ("rx-gain", po::value<double>(&rx_gain), "gain for the receive RF chain")
    ("tx-ant", po::value<std::string>(&tx_ant), "daughterboard transmit antenna selection")
    ("rx-ant", po::value<std::string>(&rx_ant), "daughterboard receive antenna selection")
    ("tx-subdev", po::value<std::string>(&tx_subdev), "daughterboard transmit subdevice specification")
    ("rx-subdev", po::value<std::string>(&rx_subdev), "daughterboard receive subdevice specification")
    ("tx-bw", po::value<double>(&tx_bw), "daughterboard transmit IF filter bandwidth in Hz")
    ("rx-bw", po::value<double>(&rx_bw), "daughterboard receive IF filter bandwidth in Hz")
    ("wave-type", po::value<std::string>(&wave_type)->default_value("CONST"), "waveform type (CONST, SQUARE, RAMP, SINE)")
    ("wave-freq", po::value<double>(&wave_freq)->default_value(0), "waveform frequency in Hz")
    ("ref", po::value<std::string>(&ref)->default_value("internal"), "clock reference (internal, external, mimo)")
    ("otw", po::value<std::string>(&otw)->default_value("sc16"), "specify the over-the-wire sample mode")
    ("tx-channels", po::value<std::string>(&tx_channels)->default_value("0"), "which TX channel(s) to use (specify \"0\", \"1\", \"0,1\", etc)")
    ("rx-channels", po::value<std::string>(&rx_channels)->default_value("0"), "which RX channel(s) to use (specify \"0\", \"1\", \"0,1\", etc)")
    ("tx-int-n", "tune USRP TX with integer-N tuning")
    ("rx-int-n", "tune USRP RX with integer-N tuning")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")) {
        std::cout << boost::format("UHD TXRX Loopback to File %s") % desc << std::endl;
        return ~0;
    }

    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the transmit usrp device with: %s...") % tx_args << std::endl;
    uhd::usrp::multi_usrp::sptr tx_usrp = uhd::usrp::multi_usrp::make(tx_args);
    std::cout << std::endl;
    std::cout << boost::format("Creating the receive usrp device with: %s...") % rx_args << std::endl;
    uhd::usrp::multi_usrp::sptr rx_usrp = uhd::usrp::multi_usrp::make(rx_args);

    //detect which channels to use
    std::vector<std::string> tx_channel_strings;
    std::vector<size_t> tx_channel_nums;
    boost::split(tx_channel_strings, tx_channels, boost::is_any_of("\"',"));
    for(size_t ch = 0; ch < tx_channel_strings.size(); ch++) {
        size_t chan = boost::lexical_cast<int>(tx_channel_strings[ch]);
        if(chan >= tx_usrp->get_tx_num_channels()) {
            throw std::runtime_error("Invalid TX channel(s) specified.");
        }
        else tx_channel_nums.push_back(boost::lexical_cast<int>(tx_channel_strings[ch]));
    }
    std::vector<std::string> rx_channel_strings;
    std::vector<size_t> rx_channel_nums;
    boost::split(rx_channel_strings, rx_channels, boost::is_any_of("\"',"));
    for(size_t ch = 0; ch < rx_channel_strings.size(); ch++) {
        size_t chan = boost::lexical_cast<int>(rx_channel_strings[ch]);
        if(chan >= rx_usrp->get_rx_num_channels()) {
            throw std::runtime_error("Invalid RX channel(s) specified.");
        }
        else rx_channel_nums.push_back(boost::lexical_cast<int>(rx_channel_strings[ch]));
    }

    //Lock mboard clocks
    tx_usrp->set_clock_source(ref);
    rx_usrp->set_clock_source(ref);

    //always select the subdevice first, the channel mapping affects the other settings
    if (vm.count("tx-subdev")) tx_usrp->set_tx_subdev_spec(tx_subdev);
    if (vm.count("rx-subdev")) rx_usrp->set_rx_subdev_spec(rx_subdev);

    std::cout << boost::format("Using Device: %s") % tx_usrp->get_pp_string() << std::endl;
    std::cout << boost::format("Using Device: %s") % rx_usrp->get_pp_string() << std::endl;

    //set the transmit sample rate
    if (not vm.count("tx-rate")) {
        std::cerr << "Please specify the transmit sample rate with --tx-rate" << std::endl;
        return ~0;
    }
    std::cout << boost::format("Setting TX Rate: %f Msps...") % (tx_rate/1e6) << std::endl;
    tx_usrp->set_tx_rate(tx_rate);
    std::cout << boost::format("Actual TX Rate: %f Msps...") % (tx_usrp->get_tx_rate()/1e6) << std::endl << std::endl;

    //set the receive sample rate
    if (not vm.count("rx-rate")) {
        std::cerr << "Please specify the sample rate with --rx-rate" << std::endl;
        return ~0;
    }
    std::cout << boost::format("Setting RX Rate: %f Msps...") % (rx_rate/1e6) << std::endl;
    rx_usrp->set_rx_rate(rx_rate);
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (rx_usrp->get_rx_rate()/1e6) << std::endl << std::endl;

    //set the transmit center frequency
    if (not vm.count("tx-freq")) {
        std::cerr << "Please specify the transmit center frequency with --tx-freq" << std::endl;
        return ~0;
    }

    for(size_t ch = 0; ch < tx_channel_nums.size(); ch++) {
        std::cout << boost::format("Setting TX Freq: %f MHz...") % (tx_freq/1e6) << std::endl;
        uhd::tune_request_t tx_tune_request(tx_freq);
        if(vm.count("tx-int-n")) tx_tune_request.args = uhd::device_addr_t("mode_n=integer");
        tx_usrp->set_tx_freq(tx_tune_request, tx_channel_nums[ch]);
        std::cout << boost::format("Actual TX Freq: %f MHz...") % (tx_usrp->get_tx_freq(tx_channel_nums[ch])/1e6) << std::endl << std::endl;

        //set the rf gain
        if (vm.count("tx-gain")) {
            std::cout << boost::format("Setting TX Gain: %f dB...") % tx_gain << std::endl;
            tx_usrp->set_tx_gain(tx_gain, tx_channel_nums[ch]);
            std::cout << boost::format("Actual TX Gain: %f dB...") % tx_usrp->get_tx_gain(tx_channel_nums[ch]) << std::endl << std::endl;
        }

        //set the IF filter bandwidth
        if (vm.count("tx-bw")) {
            std::cout << boost::format("Setting TX Bandwidth: %f MHz...") % tx_bw << std::endl;
            tx_usrp->set_tx_bandwidth(tx_bw, tx_channel_nums[ch]);
            std::cout << boost::format("Actual TX Bandwidth: %f MHz...") % tx_usrp->get_tx_bandwidth(tx_channel_nums[ch]) << std::endl << std::endl;
        }

        //set the antenna
        if (vm.count("tx-ant")) tx_usrp->set_tx_antenna(tx_ant, tx_channel_nums[ch]);
    }

    //set the receive center frequency
    if (not vm.count("rx-freq")) {
        std::cerr << "Please specify the center frequency with --rx-freq" << std::endl;
        return ~0;
    }
    std::cout << boost::format("Setting RX Freq: %f MHz...") % (rx_freq/1e6) << std::endl;
    uhd::tune_request_t rx_tune_request(rx_freq);
    if(vm.count("rx-int-n")) rx_tune_request.args = uhd::device_addr_t("mode_n=integer");
    rx_usrp->set_rx_freq(rx_tune_request);
    std::cout << boost::format("Actual RX Freq: %f MHz...") % (rx_usrp->get_rx_freq()/1e6) << std::endl << std::endl;

    //set the receive rf gain
    if (vm.count("rx_gain")) {
        std::cout << boost::format("Setting RX Gain: %f dB...") % rx_gain << std::endl;
        rx_usrp->set_rx_gain(rx_gain);
        std::cout << boost::format("Actual RX Gain: %f dB...") % rx_usrp->get_rx_gain() << std::endl << std::endl;
    }

    //set the receive IF filter bandwidth
    if (vm.count("rx_bw")) {
        std::cout << boost::format("Setting RX Bandwidth: %f MHz...") % rx_bw << std::endl;
        rx_usrp->set_rx_bandwidth(rx_bw);
        std::cout << boost::format("Actual RX Bandwidth: %f MHz...") % rx_usrp->get_rx_bandwidth() << std::endl << std::endl;
    }

    //set the receive antenna
    if (vm.count("ant")) rx_usrp->set_rx_antenna(rx_ant);

    //for the const wave, set the wave freq for small samples per period
    if (wave_freq == 0 and wave_type == "CONST") {
        wave_freq = tx_usrp->get_tx_rate()/2;
    }

    //error when the waveform is not possible to generate
    if (std::abs(wave_freq) > tx_usrp->get_tx_rate()/2) {
        throw std::runtime_error("wave freq out of Nyquist zone");
    }
    if (tx_usrp->get_tx_rate()/std::abs(wave_freq) > wave_table_len/2) {
        throw std::runtime_error("wave freq too small for table");
    }

    //pre-compute the waveform values
    const wave_table_class wave_table(wave_type, ampl);
    const size_t step = boost::math::iround(wave_freq/tx_usrp->get_tx_rate() * wave_table_len);
    size_t index = 0;

    //create a transmit streamer
    //linearly map channels (index0 = channel0, index1 = channel1, ...)
    uhd::stream_args_t stream_args("fc32", otw);
    stream_args.channels = tx_channel_nums;
    uhd::tx_streamer::sptr tx_stream = tx_usrp->get_tx_stream(stream_args);

    //allocate a buffer which we re-use for each channel
    if (spb == 0) spb = tx_stream->get_max_num_samps()*10;
    std::vector<std::complex<float> > buff(spb);
    int num_channels = tx_channel_nums.size();

    //setup the metadata flags
    uhd::tx_metadata_t md;
    md.start_of_burst = true;
    md.end_of_burst   = false;
    md.has_time_spec  = true;
    md.time_spec = uhd::time_spec_t(0.1); //give us 0.1 seconds to fill the tx buffers

    //Check Ref and LO Lock detect
    std::vector<std::string> tx_sensor_names, rx_sensor_names;
    tx_sensor_names = tx_usrp->get_tx_sensor_names(0);
    if (std::find(tx_sensor_names.begin(), tx_sensor_names.end(), "lo_locked") != tx_sensor_names.end()) {
        uhd::sensor_value_t lo_locked = tx_usrp->get_tx_sensor("lo_locked",0);
        std::cout << boost::format("Checking TX: %s ...") % lo_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(lo_locked.to_bool());
    }
    rx_sensor_names = rx_usrp->get_rx_sensor_names(0);
    if (std::find(rx_sensor_names.begin(), rx_sensor_names.end(), "lo_locked") != rx_sensor_names.end()) {
        uhd::sensor_value_t lo_locked = rx_usrp->get_rx_sensor("lo_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % lo_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(lo_locked.to_bool());
    }

    tx_sensor_names = tx_usrp->get_mboard_sensor_names(0);
    if ((ref == "mimo") and (std::find(tx_sensor_names.begin(), tx_sensor_names.end(), "mimo_locked") != tx_sensor_names.end())) {
        uhd::sensor_value_t mimo_locked = tx_usrp->get_mboard_sensor("mimo_locked",0);
        std::cout << boost::format("Checking TX: %s ...") % mimo_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(mimo_locked.to_bool());
    }
    if ((ref == "external") and (std::find(tx_sensor_names.begin(), tx_sensor_names.end(), "ref_locked") != tx_sensor_names.end())) {
        uhd::sensor_value_t ref_locked = tx_usrp->get_mboard_sensor("ref_locked",0);
        std::cout << boost::format("Checking TX: %s ...") % ref_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(ref_locked.to_bool());
    }

    rx_sensor_names = rx_usrp->get_mboard_sensor_names(0);
    if ((ref == "mimo") and (std::find(rx_sensor_names.begin(), rx_sensor_names.end(), "mimo_locked") != rx_sensor_names.end())) {
        uhd::sensor_value_t mimo_locked = rx_usrp->get_mboard_sensor("mimo_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % mimo_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(mimo_locked.to_bool());
    }
    if ((ref == "external") and (std::find(rx_sensor_names.begin(), rx_sensor_names.end(), "ref_locked") != rx_sensor_names.end())) {
        uhd::sensor_value_t ref_locked = rx_usrp->get_mboard_sensor("ref_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % ref_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(ref_locked.to_bool());
    }

    if (total_num_samps == 0) {
        std::signal(SIGINT, &sig_int_handler);
        std::cout << "Press Ctrl + C to stop streaming..." << std::endl;
    }

    //reset usrp time to prepare for transmit/receive
    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;
    tx_usrp->set_time_now(uhd::time_spec_t(0.0));

    //start transmit worker thread
    boost::thread_group transmit_thread;
    transmit_thread.create_thread(boost::bind(&transmit_worker, buff, wave_table, tx_stream, md, step, index, num_channels));

    //recv to file
    if (type == "double") recv_to_file<std::complex<double> >(rx_usrp, "fc64", otw, file, spb, total_num_samps, settling, rx_channel_nums);
    else if (type == "float") recv_to_file<std::complex<float> >(rx_usrp, "fc32", otw, file, spb, total_num_samps, settling, rx_channel_nums);
    else if (type == "short") recv_to_file<std::complex<short> >(rx_usrp, "sc16", otw, file, spb, total_num_samps, settling, rx_channel_nums);
    else {
        //clean up transmit worker
        stop_signal_called = true;
        transmit_thread.join_all();
        throw std::runtime_error("Unknown type " + type);
    }

    //clean up transmit worker
    stop_signal_called = true;
    transmit_thread.join_all();

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;
    return EXIT_SUCCESS;
}
Exemple #22
0
int SHD_SAFE_MAIN(int argc, char *argv[]){
    shd::set_thread_priority_safe();

    //variables to be set by po
    std::string args, ant, subdev, ref;
    size_t num_bins;
    double rate, freq, gain, bw, frame_rate;
    float ref_lvl, dyn_rng;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "multi shd device address args")
        // hardware parameters
        ("rate", po::value<double>(&rate), "rate of incoming samples (sps)")
        ("freq", po::value<double>(&freq), "RF center frequency in Hz")
        ("gain", po::value<double>(&gain), "gain for the RF chain")
        ("ant", po::value<std::string>(&ant), "daughterboard antenna selection")
        ("subdev", po::value<std::string>(&subdev), "daughterboard subdevice specification")
        ("bw", po::value<double>(&bw), "daughterboard IF filter bandwidth in Hz")
        // display parameters
        ("num-bins", po::value<size_t>(&num_bins)->default_value(512), "the number of bins in the DFT")
        ("frame-rate", po::value<double>(&frame_rate)->default_value(5), "frame rate of the display (fps)")
        ("ref-lvl", po::value<float>(&ref_lvl)->default_value(0), "reference level for the display (dB)")
        ("dyn-rng", po::value<float>(&dyn_rng)->default_value(60), "dynamic range for the display (dB)")
        ("ref", po::value<std::string>(&ref)->default_value("internal"), "waveform type (internal, external, mimo)")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help") or not vm.count("rate")){
        std::cout << boost::format("SHD RX ASCII Art DFT %s") % desc << std::endl;
        return ~0;
    }

    //create a smini device
    std::cout << std::endl;
    std::cout << boost::format("Creating the smini device with: %s...") % args << std::endl;
    shd::smini::multi_smini::sptr smini = shd::smini::multi_smini::make(args);

    //Lock mboard clocks
    smini->set_clock_source(ref);

     //always select the subdevice first, the channel mapping affects the other settings
    if (vm.count("subdev")) smini->set_rx_subdev_spec(subdev);

    std::cout << boost::format("Using Device: %s") % smini->get_pp_string() << std::endl;

    //set the sample rate
    if (not vm.count("rate")){
        std::cerr << "Please specify the sample rate with --rate" << std::endl;
        return ~0;
    }
    std::cout << boost::format("Setting RX Rate: %f Msps...") % (rate/1e6) << std::endl;
    smini->set_rx_rate(rate);
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (smini->get_rx_rate()/1e6) << std::endl << std::endl;

    //set the center frequency
    if (not vm.count("freq")){
        std::cerr << "Please specify the center frequency with --freq" << std::endl;
        return ~0;
    }
    std::cout << boost::format("Setting RX Freq: %f MHz...") % (freq/1e6) << std::endl;
    smini->set_rx_freq(freq);
    std::cout << boost::format("Actual RX Freq: %f MHz...") % (smini->get_rx_freq()/1e6) << std::endl << std::endl;

    //set the rf gain
    if (vm.count("gain")){
        std::cout << boost::format("Setting RX Gain: %f dB...") % gain << std::endl;
        smini->set_rx_gain(gain);
        std::cout << boost::format("Actual RX Gain: %f dB...") % smini->get_rx_gain() << std::endl << std::endl;
    }

    //set the IF filter bandwidth
    if (vm.count("bw")){
        std::cout << boost::format("Setting RX Bandwidth: %f MHz...") % bw << std::endl;
        smini->set_rx_bandwidth(bw);
        std::cout << boost::format("Actual RX Bandwidth: %f MHz...") % smini->get_rx_bandwidth() << std::endl << std::endl;
    }

    //set the antenna
    if (vm.count("ant")) smini->set_rx_antenna(ant);

    boost::this_thread::sleep(boost::posix_time::seconds(1)); //allow for some setup time

    //Check Ref and LO Lock detect
    std::vector<std::string> sensor_names;
    sensor_names = smini->get_rx_sensor_names(0);
    if (std::find(sensor_names.begin(), sensor_names.end(), "lo_locked") != sensor_names.end()) {
        shd::sensor_value_t lo_locked = smini->get_rx_sensor("lo_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % lo_locked.to_pp_string() << std::endl;
        SHD_ASSERT_THROW(lo_locked.to_bool());
    }
    sensor_names = smini->get_mboard_sensor_names(0);
    if ((ref == "mimo") and (std::find(sensor_names.begin(), sensor_names.end(), "mimo_locked") != sensor_names.end())) {
        shd::sensor_value_t mimo_locked = smini->get_mboard_sensor("mimo_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % mimo_locked.to_pp_string() << std::endl;
        SHD_ASSERT_THROW(mimo_locked.to_bool());
    }
    if ((ref == "external") and (std::find(sensor_names.begin(), sensor_names.end(), "ref_locked") != sensor_names.end())) {
        shd::sensor_value_t ref_locked = smini->get_mboard_sensor("ref_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % ref_locked.to_pp_string() << std::endl;
        SHD_ASSERT_THROW(ref_locked.to_bool());
    }

    //create a receive streamer
    shd::stream_args_t stream_args("fc32"); //complex floats
    shd::rx_streamer::sptr rx_stream = smini->get_rx_stream(stream_args);

    //allocate recv buffer and metatdata
    shd::rx_metadata_t md;
    std::vector<std::complex<float> > buff(num_bins);
    //------------------------------------------------------------------
    //-- Initialize
    //------------------------------------------------------------------
    initscr(); //curses init
    smini->issue_stream_cmd(shd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS);
    boost::system_time next_refresh = boost::get_system_time();

    //------------------------------------------------------------------
    //-- Main loop
    //------------------------------------------------------------------
    while (true){
        //read a buffer's worth of samples every iteration
        size_t num_rx_samps = rx_stream->recv(
            &buff.front(), buff.size(), md
        );
        if (num_rx_samps != buff.size()) continue;

        //check and update the display refresh condition
        if (boost::get_system_time() < next_refresh) continue;
        next_refresh = boost::get_system_time() + boost::posix_time::microseconds(long(1e6/frame_rate));

        //calculate the dft and create the ascii art frame
        acsii_art_dft::log_pwr_dft_type lpdft(
            acsii_art_dft::log_pwr_dft(&buff.front(), num_rx_samps)
        );
        std::string frame = acsii_art_dft::dft_to_plot(
            lpdft, COLS, LINES,
            smini->get_rx_rate(),
            smini->get_rx_freq(),
            dyn_rng, ref_lvl
        );

        //curses screen handling: clear and print frame
        clear();
        printw("%s", frame.c_str());

        //curses key handling: no timeout, any key to exit
        timeout(0);
        int ch = getch();
        if (ch != KEY_RESIZE and ch != ERR) break;
    }

    //------------------------------------------------------------------
    //-- Cleanup
    //------------------------------------------------------------------
    smini->issue_stream_cmd(shd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS);
    endwin(); //curses done

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return 0;
}
void ShaderWriter::includeFile(string filename, string fromFile) {

	if(fileExists(currentDir() + "/"+ filename)){
		filename = currentDir() + "/"+ filename;
	} else if (fileExists(dirName(fromFile) + "/"+ filename)){
		filename = dirName(fromFile) + "/"+ filename;
	} else if (fileExists(shaderDir() + "/"+ filename)){
		filename = shaderDir() + "/"+ filename;
	} else if(!fileExists(filename)) {
		cerr << "Could not find file: " << filename << endl;
		return;
	}

	ifstream file;
	file.open(filename);

	bool inComment = false;

	char _buff[200];
	while(!file.eof()) {
		file.getline(_buff,sizeof(_buff));

		string buff(_buff);
        
		if(!m_Debug) {
			if(buff[buff.size()-1] == '\r') {
				buff[buff.size()-1] =0;
			}

			if(inComment) {
				size_t i = buff.find("*/");
				if(i != -1){
					buff = buff.substr(i+2);
					inComment = false;
				} else {
					buff="";
				}

			}else{ 

				size_t i = buff.find("//");
				if(i != -1) {
					buff = buff.substr(0,i);
				}

				i = buff.find("/*");
				if(i != -1) {
					buff = buff.substr(0,i);
					inComment =true;
				}

				buff = stringReplace(buff,"\t","");
			}
		}

		if(buff.substr(0,8) == "#include"){
			includeFile(string(buff).substr(9),filename);
		}else{
			m_Shader << buff << endl;
		}
	}
}
Exemple #24
0
/** Actually sends the sMethod action to the command URL specified
 *  in the constructor (url+[/]+sControlPath).
 *
 * \param sMethod method to be invoked. e.g. "SetChannel",
 *                "GetConnectionInfoResult"
 *
 * \param list Parsed as a series of key value pairs for the input params
 *             and then cleared and used for the output params.
 *
 * \param nErrCode set to zero on success, non-zero in case of error.
 *
 * \param sErrCode returns error description from device, when applicable.
 *
 * \param bInQtThread May be set to true if this is run from within
 *                    a QThread with a running an event loop.
 *
 * \return Returns a QDomDocument containing output parameters on success.
 */
QDomDocument SOAPClient::SendSOAPRequest(const QString &sMethod,
                                         QStringMap    &list,
                                         int           &nErrCode,
                                         QString       &sErrDesc,
                                         bool           bInQtThread)
{
    QUrl url(m_url);

    url.setPath(m_sControlPath);

    nErrCode = UPnPResult_Success;
    sErrDesc = "";

    QDomDocument xmlResult;
    if (m_sNamespace.isEmpty())
    {
        nErrCode = UPnPResult_MythTV_NoNamespaceGiven;
        sErrDesc = "No namespace given";
        return xmlResult;
    }

    // --------------------------------------------------------------
    // Add appropriate headers
    // --------------------------------------------------------------

    QHttpRequestHeader header("POST", sMethod, 1, 0);

    header.setValue("CONTENT-TYPE", "text/xml; charset=\"utf-8\"" );
    header.setValue("SOAPACTION",
                    QString("\"%1#%2\"").arg(m_sNamespace).arg(sMethod));

    // --------------------------------------------------------------
    // Build request payload
    // --------------------------------------------------------------

    QByteArray  aBuffer;
    QTextStream os( &aBuffer );

    os.setCodec("UTF-8");

    os << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"; 
    os << "<s:Envelope "
        " s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\""
        " xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
    os << " <s:Body>\r\n";
    os << "  <u:" << sMethod << " xmlns:u=\"" << m_sNamespace << "\">\r\n";

    // --------------------------------------------------------------
    // Add parameters from list
    // --------------------------------------------------------------

    for (QStringMap::iterator it = list.begin(); it != list.end(); ++it)
    {                                                               
        os << "   <" << it.key() << ">";
        os << HTTPRequest::Encode( *it );
        os << "</"   << it.key() << ">\r\n";
    }

    os << "  </u:" << sMethod << ">\r\n";
    os << " </s:Body>\r\n";
    os << "</s:Envelope>\r\n";

    os.flush();

    // --------------------------------------------------------------
    // Perform Request
    // --------------------------------------------------------------

    QBuffer buff(&aBuffer);

    LOG(VB_UPNP, LOG_DEBUG,
        QString("SOAPClient(%1) sending:\n").arg(url.toString()) +
        header.toString() + QString("\n%1\n").arg(aBuffer.constData()));

    QString sXml =
        HttpComms::postHttp(url,
                            &header,
                            &buff, // QIODevice*
                            10000, // ms -- Technically should be 30ms per spec
                            3,     // retries
                            0,     // redirects
                            false, // allow gzip
                            NULL,  // login
                            bInQtThread,
                            QString() // userAgent, UPnP/1.0 very strict on
                                      // format if set
        );

    // --------------------------------------------------------------
    // Parse response
    // --------------------------------------------------------------

    LOG(VB_UPNP, LOG_DEBUG, "SOAPClient response:\n" +
                            QString("%1\n").arg(sXml));

    // TODO handle timeout without response correctly.

    list.clear();

    QDomDocument doc;

    if (!doc.setContent(sXml, true, &sErrDesc, &nErrCode))
    {
        LOG(VB_UPNP, LOG_ERR,
            QString("SendSOAPRequest( %1 ) - Invalid response from %2")
                .arg(sMethod).arg(url.toString()) + 
            QString("%1: %2").arg(nErrCode).arg(sErrDesc));

        return xmlResult;
    }

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QString      sResponseName = sMethod + "Response";
    QDomNodeList oNodeList     =
        doc.elementsByTagNameNS(m_sNamespace, sResponseName);

    if (oNodeList.count() == 0)
    {
        // --------------------------------------------------------------
        // Must be a fault... parse it to return reason
        // --------------------------------------------------------------

        nErrCode = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorCode", 500);
        sErrDesc = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorDescription", "");
        if (sErrDesc.isEmpty())
            sErrDesc = QString("Unknown #%1").arg(nErrCode);

        QDomNode oNode  = FindNode( "Envelope/Body/Fault", doc );

        oNode = xmlResult.importNode( oNode, true );
        xmlResult.appendChild( oNode );

        return xmlResult;
    }

    QDomNode oMethod = oNodeList.item(0);
    if (oMethod.isNull())
        return xmlResult;

    QDomNode oNode = oMethod.firstChild(); 
    for (; !oNode.isNull(); oNode = oNode.nextSibling())
    {
        QDomElement e = oNode.toElement();
        if (e.isNull())
            continue;

        QString sName  = e.tagName();
        QString sValue = "";
    
        QDomText  oText = oNode.firstChild().toText();
    
        if (!oText.isNull())
            sValue = oText.nodeValue();

        list.insert(QUrl::fromPercentEncoding(sName.toUtf8()),
                    QUrl::fromPercentEncoding(sValue.toUtf8()));
    }

    // Create copy of oMethod that can be used with xmlResult.

    oMethod = xmlResult.importNode( oMethod.firstChild(), true  );

    // importNode does not attach the new nodes to the document,
    // do it here.

    xmlResult.appendChild( oMethod );

    return xmlResult;
}
Exemple #25
0
bool 
FileUtils::fileCopy( 
    const String &source, 
    const String& dest,
    const bool replace )
{
    ASSERT_D( source.length() > 0 );
    ASSERT_D( dest.length() > 0 );

#if defined(_WINDOWS) || defined(WIN32)
    return ::CopyFile( source.c_str(), dest.c_str(), replace ? FALSE : TRUE ) == TRUE;
#else

    // validate the source file 
    FileAttributes attrs;
    bool res = FileUtils::getAttributes( source, attrs );
    if ( !res || attrs.isDirectory() )
    {
        return false;
    }

    // if the destination file exists, replace is false, then we don't 
    // allow the procedure to complete
    FileAttributes destattrs;
    if ( FileUtils::getAttributes( dest, destattrs ) && 
         !destattrs.isDirectory() && 
         (!replace || destattrs.isReadonly()) )
    {
        return false;
    }

#ifdef __GNUG__
            IFSTREAM input( source.c_str(),
                                 std::ios::in |
                                 std::ios::binary );
            OFSTREAM output( dest.c_str(),
                                 std::ios::out |
                                 std::ios::binary );
#else
            IFSTREAM input( source.c_str(),
                                 std::ios_base::in |
                                 std::ios_base::binary );
            OFSTREAM output( dest.c_str(),
                                 std::ios::out |
                                 std::ios::binary );
#endif

    if ( input.good() && output.good() )
    {
        std::auto_ptr<char> buff( new char[COPY_BUFF_SIZE] );
        if ( buff.get() != NULL )
        {
            const char* pBuff = buff.get();
#ifdef __GNUG__
            input.seekg( 0, std::ios::end );
            int numBytesLeft = input.tellg() ;
            input.seekg( 0, std::ios::beg );
#else
            input.seekg( 0, std::ios_base::end );
            int numBytesLeft = input.tellg() ;
            input.seekg( 0, std::ios_base::beg );
#endif

            while ( numBytesLeft > 0 && res )
            {
                int numToRead = (numBytesLeft > COPY_BUFF_SIZE) ? COPY_BUFF_SIZE : numBytesLeft;
                res = ( input.read( (char*)pBuff, numToRead ) && 
                        output.write( pBuff, numToRead ) );
                numBytesLeft -= numToRead;
            }
        }
    
        if ( res )
        {
            res = FileUtils::setAttributes( dest, attrs );
        }
    }
    
    return res;
#endif

}
Exemple #26
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args;
    double seconds_in_future;
    size_t total_num_samps;
    double rate;
    float ampl;
    double freq;
    double rep_rate;
    double gain;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "multi uhd device address args")
        ("secs", po::value<double>(&seconds_in_future)->default_value(1.5), "delay before first burst")
        ("repeat", "repeat burst")
        ("rep-delay", po::value<double>(&rep_rate)->default_value(0.5), "delay between bursts")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(10000), "total number of samples to transmit")
        ("rate", po::value<double>(&rate)->default_value(100e6/16), "rate of outgoing samples")
        ("ampl", po::value<float>(&ampl)->default_value(float(0.3)), "amplitude of each sample")
        ("freq", po::value<double>(&freq)->default_value(0), "center frequency")
        ("gain", po::value<double>(&gain)->default_value(0), "gain")
        ("dilv", "specify to disable inner-loop verbose")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD TX Timed Samples %s") % desc << std::endl;
        return ~0;
    }

    bool verbose = vm.count("dilv") == 0;
    bool repeat = vm.count("repeat") != 0;

    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

    //set the tx sample rate
    std::cout << boost::format("Setting TX Rate: %f Msps...") % (rate/1e6) << std::endl;
    usrp->set_tx_rate(rate);
    std::cout << boost::format("Actual TX Rate: %f Msps...") % (usrp->get_tx_rate()/1e6) << std::endl << std::endl;

    std::cout << boost::format("Setting TX Freq: %f MHz...") % (freq/1e6) << std::endl;
    for(size_t i=0; i < usrp->get_tx_num_channels(); i++) usrp->set_tx_freq(freq, i);
    std::cout << boost::format("Actual TX Freq: %f MHz...") % (usrp->get_tx_freq()/1e6) << std::endl << std::endl;

    std::cout << boost::format("Setting TX Gain: %f...") % (gain) << std::endl;
    for(size_t i=0; i < usrp->get_tx_num_channels(); i++) usrp->set_tx_gain(gain, i);
    std::cout << boost::format("Actual TX Gain: %f...") % (usrp->get_tx_gain()) << std::endl << std::endl;

    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;
    usrp->set_time_now(uhd::time_spec_t(0.0));

    //create a transmit streamer
    uhd::stream_args_t stream_args("fc32"); //complex floats
    uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args);

    //allocate buffer with data to send
    const size_t spb = tx_stream->get_max_num_samps();

    std::vector<std::complex<float> > buff(spb, std::complex<float>(ampl, ampl));
    std::vector<std::complex<float> *> buffs(usrp->get_tx_num_channels(), &buff.front());

    std::signal(SIGINT, &sig_int_handler);
    if(repeat) std::cout << "Press Ctrl + C to quit..." << std::endl;

    double time_to_send = seconds_in_future;

    do {
        //setup metadata for the first packet
        uhd::tx_metadata_t md;
        md.start_of_burst = true;
        md.end_of_burst = false;
        md.has_time_spec = true;
        md.time_spec = uhd::time_spec_t(time_to_send);

        //the first call to send() will block this many seconds before sending:
        double timeout = std::max(rep_rate, seconds_in_future) + 0.1; //timeout (delay before transmit + padding)

        size_t num_acc_samps = 0; //number of accumulated samples
        while(num_acc_samps < total_num_samps){
            size_t samps_to_send = std::min(total_num_samps - num_acc_samps, spb);

            //send a single packet
            size_t num_tx_samps = tx_stream->send(
                buffs, samps_to_send, md, timeout
            );
                
            //do not use time spec for subsequent packets
            md.has_time_spec = false;
            md.start_of_burst = false;

            if (num_tx_samps < samps_to_send) std::cerr << "Send timeout..." << std::endl;
            if(verbose) std::cout << boost::format("Sent packet: %u samples") % num_tx_samps << std::endl;

            num_acc_samps += num_tx_samps;
        }

        md.end_of_burst = true;
        tx_stream->send(buffs, 0, md, timeout);

        time_to_send += rep_rate;

        std::cout << std::endl << "Waiting for async burst ACK... " << std::flush;
        uhd::async_metadata_t async_md;
        bool got_async_burst_ack = false;
        //loop through all messages for the ACK packet (may have underflow messages in queue)
        while (not got_async_burst_ack and usrp->get_device()->recv_async_msg(async_md, seconds_in_future)){
            got_async_burst_ack = (async_md.event_code == uhd::async_metadata_t::EVENT_CODE_BURST_ACK);
        }
        std::cout << (got_async_burst_ack? "success" : "fail") << std::endl;
    } while (not stop_signal_called and repeat);

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return EXIT_SUCCESS;
}
Exemple #27
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "single uhd device address args")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD Test Timed Commands %s") % desc << std::endl;
        return ~0;
    }

    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

    //check if timed commands are supported
    std::cout << std::endl;
    std::cout << "Testing support for timed commands on this hardware... " << std::flush;
    try{
        usrp->set_command_time(uhd::time_spec_t(0.0));
        usrp->clear_command_time();
    }
    catch (const std::exception &e){
        std::cout << "fail" << std::endl;
        std::cerr << "Got exception: " << e.what() << std::endl;
        std::cerr << "Timed commands are not supported on this hardware." << std::endl;
        return ~0;
    }
    std::cout << "pass" << std::endl;

    //readback time really fast, time diff is small
    std::cout << std::endl;
    std::cout << "Perform fast readback of registers:" << std::endl;
    uhd::time_spec_t total_time;
    for (size_t i = 0; i < 100; i++){
        const uhd::time_spec_t t0 = usrp->get_time_now();
        const uhd::time_spec_t t1 = usrp->get_time_now();
        total_time += (t1-t0);
    }
    std::cout << boost::format(
        " Difference between paired reads: %f us"
    ) % (total_time.get_real_secs()/100*1e6) << std::endl;

    //test timed control command
    //issues get_time_now() command twice a fixed time apart
    //outputs difference for each response time vs. the expected time
    //and difference between actual and expected time deltas
    std::cout << std::endl;
    std::cout << "Testing control timed command:" << std::endl;
    const uhd::time_spec_t span = uhd::time_spec_t(0.1);
    const uhd::time_spec_t now = usrp->get_time_now();
    const uhd::time_spec_t cmd_time1 = now + uhd::time_spec_t(0.1);
    const uhd::time_spec_t cmd_time2 = cmd_time1 + span;
    usrp->set_command_time(cmd_time1);
    uhd::time_spec_t response_time1 = usrp->get_time_now();
    usrp->set_command_time(cmd_time2);
    uhd::time_spec_t response_time2 = usrp->get_time_now();
    usrp->clear_command_time();
    std::cout << boost::format(
        " Span      : %f us\n"
        " Now       : %f us\n"
        " Response 1: %f us\n"
        " Response 2: %f us"
    ) % (span.get_real_secs()*1e6) % (now.get_real_secs()*1e6) % (response_time1.get_real_secs()*1e6) % (response_time2.get_real_secs()*1e6) << std::endl;
    std::cout << boost::format(
        " Difference of response time 1: %f us"
    ) % ((response_time1 - cmd_time1).get_real_secs()*1e6) << std::endl;
    std::cout << boost::format(
        " Difference of response time 2: %f us"
    ) % ((response_time2 - cmd_time2).get_real_secs()*1e6) << std::endl;
    std::cout << boost::format(
        " Difference between actual and expected time delta: %f us"
    ) % ((response_time2 - response_time1 - span).get_real_secs()*1e6) << std::endl;

    //use a timed command to start a stream at a specific time
    //this is not the right way start streaming at time x,
    //but it should approximate it within control RTT/2
    //setup streaming
    std::cout << std::endl;
    std::cout << "About to start streaming using timed command:" << std::endl;

    //create a receive streamer
    uhd::stream_args_t stream_args("fc32"); //complex floats
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
    stream_cmd.num_samps = 100;
    stream_cmd.stream_now = false;
    const uhd::time_spec_t stream_time = usrp->get_time_now() + uhd::time_spec_t(0.1);
    stream_cmd.time_spec = stream_time;
    rx_stream->issue_stream_cmd(stream_cmd);

    //meta-data will be filled in by recv()
    uhd::rx_metadata_t md;

    //allocate buffer to receive with samples
    std::vector<std::complex<float> > buff(stream_cmd.num_samps);

    const size_t num_rx_samps = rx_stream->recv(&buff.front(), buff.size(), md, 1.0);
    if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE){
        throw std::runtime_error(str(boost::format(
            "Receiver error %s"
        ) % md.strerror()));
    }
    std::cout << boost::format(
        " Received packet: %u samples, %u full secs, %f frac secs"
    ) % num_rx_samps % md.time_spec.get_full_secs() % md.time_spec.get_frac_secs() << std::endl;
    std::cout << boost::format(
        " Stream time was: %u full secs, %f frac secs"
    ) % stream_time.get_full_secs() % stream_time.get_frac_secs() << std::endl;
    std::cout << boost::format(
        " Difference between stream time and first packet: %f us"
    ) % ((md.time_spec-stream_time).get_real_secs()*1e6) << std::endl;

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return EXIT_SUCCESS;
}
/**
 * Read in psm details from a string out of tab delimited file
 * @param dataStream filestream of tab delimited file, only passed to close on exception
 * TODO: remove dataStream parameter and return int with type of error to handle upstream.
 * @param line tab delimited string containing the psm details
 */
void DataSet::readPsm(const std::string line, const unsigned int lineNr, 
                      const std::vector<OptionalField>& optionalFields) {
  istringstream buff(line);
  string tmp;
  unsigned int numFeatures = FeatureNames::getNumFeatures();
  
  PSMDescription *myPsm = new PSMDescription();
  buff >> myPsm->id >> tmp; // read PSMid and get rid of label_
  if (!buff.good()) {
    ostringstream temp;
    temp << "ERROR: Reading tab file, error reading PSM on line " << lineNr << \
        ". Could not read PSMid or label_." << std::endl;
    throw MyException(temp.str());
  }
  
  bool hasScannr = false;
  std::vector<OptionalField>::const_iterator it = optionalFields.begin();
  for ( ; it != optionalFields.end(); ++it) {
    switch (*it) {
      case SCANNR: {
        buff >> myPsm->scan;
        if (!buff.good()) {
          ostringstream temp;
          temp << "ERROR: Reading tab file, error reading scan number of PSM with id " << myPsm->id << \
              ". Check if the scan number is an integer." << std::endl;
          throw MyException(temp.str());
        } else {
          hasScannr = true;
        }
        break;
      } case EXPMASS: {
        buff >> myPsm->expMass;
        break;
      } case CALCMASS: {
        buff >> myPsm->calcMass;
        break;
      } default: {
        ostringstream temp;
        temp << "ERROR: Unknown optional field." << std::endl;
        throw MyException(temp.str());
        break;
      }
    }
  }
  if (!hasScannr) myPsm->scan = lineNr;
  
  if (calcDOC_) {
    numFeatures -= DescriptionOfCorrect::numDOCFeatures();
    buff >> myPsm->retentionTime;
    buff >> myPsm->massDiff;
  }
  double *featureRow = new double[FeatureNames::getNumFeatures()];
  myPsm->features = featureRow;
  for (register unsigned int j = 0; j < numFeatures; j++) {
    buff >> featureRow[j];
  }
  if (!buff.good()) {
    ostringstream temp;
    temp << "ERROR: Reading tab file, error reading in the feature vector of PSM with id " << myPsm->id << \
     ". Check if there are enough features on this line and if they are all floating point numbers or integers." << std::endl;
    throw MyException(temp.str());
  }
  
  std::string peptide_seq = "";
  buff >> peptide_seq;
  myPsm->peptide = peptide_seq;
  if (!buff.good()) {
    ostringstream temp;
    temp << "ERROR: Reading tab file, error reading PSM with id " << myPsm->id << ". Check if" << \
      " a peptide and at least one protein are specified." << std::endl;
    throw MyException(temp.str());
  } else if (peptide_seq.size() < 5) {
    ostringstream temp;
    temp << "ERROR: Reading tab file, the peptide sequence " << peptide_seq << \
      " with PSM id " << myPsm->id << " is too short." << std::endl;
    throw MyException(temp.str());
  } else if (peptide_seq.at(1) != '.' && peptide_seq.at(peptide_seq.size()-1) != '.') {
    ostringstream temp;
    temp << "ERROR: Reading tab file, the peptide sequence " << peptide_seq << \
      " with PSM id " << myPsm->id << " does not contain one or two of its flanking amino acids." << std::endl;
    throw MyException(temp.str());
  }
  
  while (!!buff) {
    buff >> tmp;
    if (tmp.size() > 0) {
      myPsm->proteinIds.insert(tmp);
    }
  }
  
  registerPsm(myPsm);
}
int main(int argc, char *argv[])
{
    uint32_t i,j, fault;
    std::string args;
    args="addr=192.168.10.2";
    
    // create USRP device
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    
    // init USRP
    usrp->set_clock_source("internal");
    if (verbose) std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;
    
    // setup tx sample rate and frequency
    usrp->set_tx_rate(TX_SAMPLE_RATE);
    uhd::tune_request_t tune_request(TX_FREQ);
    usrp->set_tx_freq(tune_request, CHANNEL);
    usrp->set_tx_gain(TX_GAIN, CHANNEL);
    
    // create a transmit streamer 
    uhd::stream_args_t stream_args("fc32");
    stream_args.channels = channel_nums;
    uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args);

    // allocate buffer with data
    const size_t spb = tx_stream->get_max_num_samps();
    std::vector<std::complex<float> > buff(spb, std::complex<float>(ampl, ampl));


    // setup RXFE gpio
    usrp->set_gpio_attr("RXA", "CTRL", RXFE_CONTROL, RXFE_MASK); // set GPIO to manual control
    usrp->set_gpio_attr("RXA", "DDR", RXFE_MASK, RXFE_MASK); // set everybody as outputs
    
    // setup control gpio
    usrp->set_gpio_attr("TXA", "CTRL", CONTROL_CONTROL, CONTROL_MASK); // set GPIO to manual control
    usrp->set_gpio_attr("TXA", "DDR", CONTROL_TR_MASK, CONTROL_TR_MASK); // set TR as outputs 
    usrp->set_gpio_attr("TXA", "DDR", 0x00, CONTROL_FAULT_MASK); // set fault as input 

    // start up with rxfe disabled, rx mode
    usrp->set_gpio_attr("RXA", "OUT", 0x00, RXFE_AMP_MASK);
    usrp->set_gpio_attr("RXA", "OUT", 0xFF, RXFE_ATT_MASK);
    usrp->set_gpio_attr("TXA", "OUT", CONTROL_RX, CONTROL_TR_MASK);

    // reset the clock to 0 
    usrp->set_time_now(uhd::time_spec_t(0.0));

    // cycle through dio settings
    while(1) {
        for(j = 0; j < 4; j++) {
            usrp->set_gpio_attr("RXA", "OUT", j << 6, RXFE_AMP_MASK);
            for(i = 0; i < 32; i++) {
                
                fault = (usrp->get_gpio_attr("TXA", "READBACK") & CONTROL_FAULT_MASK);
                usrp->set_gpio_attr("RXA", "OUT", i, RXFE_ATT_MASK);

                if(i % 2) {
                    usrp->set_gpio_attr("TXA", "OUT", CONTROL_RX, CONTROL_TR_MASK);
                }
                else {
                    usrp->set_gpio_attr("TXA", "OUT", CONTROL_TX, CONTROL_TR_MASK);
                }

                printf("fault state: %d, att state: %d, tx state %d\n", fault, i, i % 2);
                sleep(1); 
            }
        }
    }

    return 0;
}
//HeadFile作成
int Initialize_stdin()
{
  // -i "filepath" -pipe が同時に指定されていた。
  if (NumLoadedFiles != 1)
    return 1;

  //HeadFile
  //  標準入力の先頭部をファイルに書き出す。
  //  ファイルにすることでseekに対応
  _setmode(_fileno(stdin), _O_BINARY);
  fdStdin = _fileno(stdin);

  //WindowsのTempフォルダにDGI_temp_0000000_2を作成
  {
    DWORD pid = GetCurrentProcessId();
    std::random_device rnd;
    std::mt19937 mt(rnd());
    UINT32 rnd_num = mt() % (1000 * 1000);
    std::string tmp_path;
    tmp_path = "DGI_temp_" + std::to_string(pid) + std::to_string(rnd_num) + "_";
    tmp_path = std::string(_tempnam(NULL, tmp_path.c_str()));
    HeadFilePath = tmp_path;
  }
  fdHeadFile = _open(HeadFilePath.c_str(), _O_CREAT | _O_RDWR | _O_BINARY, _S_IREAD | _S_IWRITE);
  if (fdHeadFile == -1)
    return 1;
  int head_size;
  {
    const double mini_MB = 6.0;
    double size = HeadFileSize_CmdLine;
    size = mini_MB < size ? size : mini_MB;
    head_size = (int)(size * 1024 * 1024);
  }


  //標準入力からデータ取得、HeadFile書込
  const int buff_size = 1024 * 32;
  std::vector<BYTE> buff(buff_size);
  int cur_size = 0;                  //HeadFileに書込済サイズ

  while (cur_size < head_size)
  {
    int read = _read(fdStdin, &buff.front(), buff_size);
    if (read == -1)
    {
      Sleep(30);
      continue;//fail to connect. wait.
    }
    else if (read == 0)
      break;//end of stream.

    int written = _write(fdHeadFile, &buff.front(), read);
    if (written != read)
      return 1;
    cur_size += written;
  }
  if (head_size <= cur_size)
    head_size = cur_size;
  else
    return 1;//fail to read. too short stream.


  //Infileにセット
  strcpy(Infilename[0], HeadFilePath.c_str());
  Infile[0] = fdHeadFile;
  _lseeki64(Infile[0], 0, SEEK_SET);

  return 0;
}