uhd_io.cpp 26.9 KB
Newer Older
M
manjaro-xfce 已提交
1 2 3 4 5
#include <stdio.h>
#include <string>
#include <signal.h>
#include <atomic>
#include <vector>
M
manjaro-xfce 已提交
6
#include <mutex>
M
manjaro-xfce 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include "uhd_thread.h"
#include "cmdlineparser.h"
#include "tb_interface.h"
#include <uhd.h>
using namespace TASKBUS;
using namespace std;
typedef short SPTYPE;
static std::atomic<bool> stop_signal_called (false);
#define UHD_DO(X) \
{\
	uhd_error e = (X);\
	char buf_errs[512];\
	if (e) { snprintf(buf_errs,sizeof(buf_errs),"Error in line %d, NO %d.",__LINE__,e);\
	std::string ev = __FILE__;\
	ev += ":";\
	ev += buf_errs;\
	return_code = 1;\
	throw ev;\
	}\
	};
void sigint_handler(int code){
	(void)code;
	stop_signal_called = true;
}

M
manjaro-xfce 已提交
32 33 34 35 36
/*!
 * \brief The tag_timestmp struct
 * Defines the fine-timestamp used for both RX and TX.
 * TM Stamp is in unit Seconds.
 */
M
manjaro-xfce 已提交
37 38 39 40
struct tag_timestmp{
	quint64 sec;
	double frag;
};
M
manjaro-xfce 已提交
41 42 43 44 45 46
/*!
 * \brief The tag_sig_block struct
 * RX Buf Node struct,with timestamp and block buffer.
 * RX Buf is formed with RX Buf Nodes,
 * each node contains several sample points for each channel.
 */
M
manjaro-xfce 已提交
47 48 49 50 51
struct tag_sig_block{
	struct tag_timestmp{
		quint64 sec;
		double frag;
	} tmstmp;
M
manjaro-xfce 已提交
52
	//valid sample points in buffer. Buffer is pre-alloced.
M
manjaro-xfce 已提交
53
	size_t ch_len;
M
manjaro-xfce 已提交
54
	//buffer for each channel
M
manjaro-xfce 已提交
55
	std::vector<std::vector<unsigned char> > ch_data;
M
manjaro-xfce 已提交
56
	//buffer prt for each channel.
M
manjaro-xfce 已提交
57 58 59
	std::vector<void *> ch_ptr;
};

M
manjaro-xfce 已提交
60 61 62 63 64 65 66 67 68 69 70 71
/*!
 * \brief The tag_tx_plain struct
 * Time plan for TX.
 */
struct tag_tx_plain{
	struct tag_timestmp{
		quint64 sec;
		double frag;
	} tmstmp;
	qint64 length_left;
};

72 73
void cmd_dealing(uhd_usrp_handle usrp,std::vector<unsigned char> & cmd);

M
manjaro-xfce 已提交
74

M
manjaro-xfce 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
static char error_string[512];
int do_iio(const cmdlineParser & args)
{
	int return_code = EXIT_SUCCESS;
	std::string dev_args = args.toString("dev_args","");

	const long long time_sync =2;//For multi channel-Sync;
	//RX Channels, Default 0
	std::vector<size_t> rx_channels = args.toUInt64Array("rx_channels");
	adjuestUnit<size_t>(rx_channels,0);
	int rx_channel_count = rx_channels.size();
	if (rx_channel_count>2)
		rx_channel_count = 2;
	//RX Sample Rate in Hz
	double rx_rate		=   args.toDouble("rx_rate",1)*1e6;
	//RX Freq in MHz --> Hz
	std::vector<double> rx_freq      =   args.toDoubleArray("rx_rf");
	adjuestUnit<double> (rx_channel_count,rx_freq,1000,1e6);
	//Rx Gain
	std::vector<double> rx_gain      =   args.toDoubleArray("rx_gain");
	adjuestUnit<double> (rx_channel_count,rx_gain,30);
	//AGC
	std::vector<int>    rx_agc		=   args.toIntArray("rx_agc");
	adjuestUnit<int> (rx_channel_count,rx_agc,0);
	//RX Bw in MHz --> Hz
	std::vector<double> rx_bw		=   args.toDoubleArray("rx_bw");
	adjuestUnit<double> (rx_channel_count,rx_bw ,0 ,1e6);
	//RX Antenna
103
	std::vector<std::string> rx_atn  =   args.toStringArray("rx_atn");
M
manjaro-xfce 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

	adjustString (rx_channel_count,rx_atn,"RX2");
	//RX switch
	bool  rx_on         =   args.toInt("rx_on",0)?true:false;
	//TX Channels, Default 0
	std::vector<size_t> tx_channels = args.toUInt64Array("tx_channels");
	adjuestUnit<size_t>(tx_channels,0);
	int tx_channel_count = tx_channels.size();
	if(tx_channel_count>2)
		tx_channel_count = 2;
	//TX Sample Rate in MHz -->Hz
	double tx_rate		=   args.toDouble("tx_rate",1.0)*1e6;
	//TX Freq in MHz -->Hz
	std::vector<double> tx_freq		=   args.toDoubleArray("tx_rf");
	adjuestUnit<double> (tx_channel_count,tx_freq,2000,1e6);
	//Tx Gain in dB
	std::vector<double> tx_gain      =   args.toDoubleArray("tx_gain");
	adjuestUnit<double> (tx_channel_count,tx_gain,30);
	//TX BW in MHz -->Hz
	std::vector<double> tx_bw		=   args.toDoubleArray("tx_bw");
M
manjaro-xfce 已提交
124
	adjuestUnit<double> (tx_channel_count,tx_bw,0 ,1e6);
M
manjaro-xfce 已提交
125
	//TX Antenna
126
	std::vector<std::string> tx_atn  =   args.toStringArray("tx_atn");
M
manjaro-xfce 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139
	adjustString (rx_channel_count,tx_atn,"TX/RX");
	//TX switch
	bool  tx_on         =   args.toInt("tx_on",0)?true:false;
	if (!rx_on && !tx_on)
	{
		fprintf(stderr,"Both RX and TX switch are OFF, nothing can do.\n");
		return 0;
	}
	const quint32 instance	  = args.toUInt("instance",0);
	const quint32 i_wav_rx[2]	  = {args.toUInt("wav_rx0",0),args.toUInt("wav_rx1",0)};
	const quint32 i_wav_tx[2]	  = {args.toUInt("wav_tx0",0),args.toUInt("wav_tx1",0)};
	const quint32 i_rx_tm = args.toInt("rx_time",0);
	const quint32 i_tx_tm = args.toInt("tx_time",0);
140
	const quint32 i_txWaterMark = args.toInt("tx_mark",0);
141

M
manjaro-xfce 已提交
142 143 144 145 146 147 148 149
	//设备句柄
	uhd_usrp_handle usrp = nullptr;
	uhd_rx_streamer_handle rx_streamer = nullptr;
	uhd_rx_metadata_handle rx_meta = nullptr;
	uhd_tx_streamer_handle tx_streamer = nullptr;
	uhd_tx_metadata_handle tx_meta = nullptr;


150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
	//发射缓存要提前配置,以便及时反馈水位
	//Time plan for tx
	std::list<tag_tx_plain> tx_plan;
	std::mutex mtx_plan;

	//ring buffer In IQ Points, TX io
	const quint64 sz_buffer_tx = 256 * 1024 * 1024;
	std::vector<std::vector<SPTYPE> > buf_tx_array;
	std::vector<quint64> tx_pos;
	std::vector<quint64> stdin_pos;
	std::vector<void *> tx_buff_ptr;
	size_t num_sps_sent = 0;
	for (int ch = 0;ch<tx_channel_count;++ch)
	{
		buf_tx_array.push_back(std::vector<SPTYPE>(sz_buffer_tx + 1024*1024*32,0));
		stdin_pos.push_back(0);
		tx_pos.push_back(0);
		tx_buff_ptr.push_back(0);
	}
	std::mutex push_mtx;
	std::mutex * pMtx = (i_wav_rx[0]+i_wav_rx[1]+i_txWaterMark)>0?&push_mtx:nullptr;

	qint64 total_points_left = -1;
	//Define StdIn Thread, Producer
	std::function<void()> thread_stdin = [&]()->void
	{
		try{
			//Read STDIN
			while (!stop_signal_called)
			{
				subject_package_header header;
				std::vector<unsigned char> packagedta = pull_subject(&header);
				if (!is_valid_header(header))
				{
					fprintf(stderr,"Recived BAD Command.");
					fflush(stderr);
					QThread::msleep(100);
					continue;
				}
				if (packagedta.size())
				{
					if ( is_control_subject(header))
					{
						//收到命令进程退出的广播消息,退出
						if (strstr((const char *)packagedta.data(),"function=quit;")!=nullptr)
						{
							fprintf(stderr,"Recived Quit Command.");
							fflush(stderr);
							stop_signal_called = true;
						}
						else
							cmd_dealing(usrp,packagedta);
					}
					else
					{
						if (header.subject_id==i_tx_tm)
						{
							if (packagedta.size()==sizeof(tag_tx_plain))
							{
								tag_tx_plain * plan = (tag_tx_plain *) (packagedta.data());
								if (total_points_left<=0)
									total_points_left = plan->length_left;
								fprintf(stderr,"plan %d points\n",plan->length_left);
								mtx_plan.lock();
								tx_plan.push_back(*plan);
								mtx_plan.unlock();
							}
							else
								fprintf(stderr,"Error Timeplan subject size %d recieved. Expected should be %d.\n",
										(int)packagedta.size(),(int)sizeof(tag_tx_plain));

						}
						else
						{
							fprintf(stderr,"recv %d points\n",packagedta.size()/2/sizeof(SPTYPE));
							for (int ch = 0; ch < tx_channel_count;++ch)
							{
								if (header.subject_id == i_wav_tx[ch])
								{
									SPTYPE * buf_tx_ptr = buf_tx_array[ch].data();
									quint64 sps_rev = packagedta.size()/2/sizeof(SPTYPE);
									short * iq = (short *)(packagedta.data());
									memcpy(&buf_tx_ptr[(stdin_pos[ch] * 2)% sz_buffer_tx],
											iq,  sps_rev * sizeof(SPTYPE)*2
											);
									const quint64 bgnext = ((stdin_pos[ch] + sps_rev) * 2) % sz_buffer_tx;
									if (bgnext < sps_rev * 2 && bgnext>0)
									{
										memcpy(buf_tx_ptr, buf_tx_ptr + sz_buffer_tx, bgnext * sizeof(SPTYPE) );
									}
									stdin_pos[ch] += sps_rev;
								}//end if (header.subject_id == i_wav_tx[ch])
							}//end for (int ch = 0; ch < tx_channel_count;++ch)
							if (total_points_left<0&&i_txWaterMark>0)
							{
								qint64 watM = stdin_pos[0] - tx_pos[0];
								if (tx_channel_count>1)
								{
									qint64 wat2 = stdin_pos[1] - tx_pos[1];
									if (wat2 < watM)
										watM = wat2;
								}
								TASKBUS::push_subject(
											i_txWaterMark,
											instance,
											sizeof(qint64),
											(unsigned char *) &watM,
											pMtx);
							}//end if (total_points_left<0)
						}//end else if (header.subject_id==i_tx_tm)
					}//end else if if ( is_control_subject(header))
				}//end if (packagedta.size())
			}//end while (!stop_signal_called)
		}//end try
		catch (std::string er)
		{
			fputs(er.c_str(),stderr);
			stop_signal_called = true;
		}
	};//end std::function<void()> thread_stdin = [&]()->void
	uhd_io_thread th_wav_stdin(thread_stdin,0);
	th_wav_stdin.start(QThread::HighestPriority);

M
manjaro-xfce 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
	try{
		fprintf(stderr, "Creating USRP with args \"%s\"...\n", dev_args.c_str());
		UHD_DO(uhd_usrp_make(&usrp, dev_args.c_str()));

		fflush(stderr);
		// Ctrl+C will exit loop
		signal(SIGINT, &sigint_handler);
		if (rx_on)
		{
			// Create RX streamer
			UHD_DO(uhd_rx_streamer_make(&rx_streamer));
			// Create RX metadata
			UHD_DO(uhd_rx_metadata_make(&rx_meta));
			//RXPer-Channel Settings
			for (int ch = 0; ch < rx_channel_count;++ch)
			{
				fprintf(stderr, "Setting RX Channel: %d=%lu...\n",ch, rx_channels[ch]);
				UHD_DO(uhd_usrp_set_rx_antenna(usrp,rx_atn[ch].c_str(),ch));
				fprintf(stderr, "Setting RX Rate: %lf...\n", rx_rate);
				UHD_DO(uhd_usrp_set_rx_rate(usrp, rx_rate, rx_channels[ch]));
				// See what rate actually is
				UHD_DO(uhd_usrp_get_rx_rate(usrp, rx_channels[ch], &rx_rate));
				fprintf(stderr, "Actual RX Rate: %lf...\n", rx_rate);
				// Set gain
				fprintf(stderr, "Setting RX Gain: %lf dB...\n", rx_gain[ch]);
				UHD_DO(uhd_usrp_set_rx_gain(usrp, rx_gain[ch], rx_channels[ch], ""));
				// See what gain actually is
				UHD_DO(uhd_usrp_get_rx_gain(usrp, rx_channels[ch], "", &rx_gain[ch]));
				fprintf(stderr, "Actual RX Gain: %lf...\n", rx_gain[ch]);
				if (rx_agc[ch])
				{
					uhd_usrp_set_rx_agc(usrp,true,rx_channels[ch]);
					uhd_usrp_set_rx_dc_offset_enabled(usrp,true,rx_channels[ch]);
				}
307 308 309 310 311 312 313 314 315 316
				else
					annouce_handle(
								args.toString("instance","0"),
								"0",
								QString("rxgain_%1").arg(ch).toStdString(),
								QString("%1").arg(rx_gain[ch]).toStdString(),
								QString("rxgain_%1").arg(ch).toStdString(),
								"int",
								"0:100"
								   );
M
manjaro-xfce 已提交
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
				// Set frequency
				// Create other necessary structs
				uhd_tune_request_t rx_tune_request =
				{
					/*.target_freq = */rx_freq[ch],
					/*.rf_freq_policy = */UHD_TUNE_REQUEST_POLICY_AUTO,
					/*.rf_freq = */0,
					/*.dsp_freq_policy = */UHD_TUNE_REQUEST_POLICY_AUTO,
					/*.dsp_freq = */0,
					/*.args = */0
				};
				uhd_tune_result_t rx_tune_result;

				fprintf(stderr, "Setting RX frequency: %lf MHz...\n", rx_freq[ch]/1e6);
				UHD_DO(uhd_usrp_set_rx_freq(usrp, &rx_tune_request, rx_channels[ch], &rx_tune_result));
				// See what frequency actually isrx_streamer
				UHD_DO(uhd_usrp_get_rx_freq(usrp, rx_channels[ch], &rx_freq[ch]));
				fprintf(stderr, "Actual RX frequency: %lf MHz...\n", rx_freq[ch] / 1e6);
335 336 337 338 339 340 341 342 343
				annouce_handle(
							args.toString("instance","0"),
							"0",
							QString("rxfreq_%1").arg(ch).toStdString(),
							QString("%1").arg(rx_freq[ch]).toStdString(),
							QString("rxfreq_%1").arg(ch).toStdString(),
							"double",
							"0:6000000000","100000","0"
							   );
M
manjaro-xfce 已提交
344 345 346 347 348 349
				fprintf(stderr, "Setting RX Bandwidth: %lf MHz...\n", rx_bw[ch]/1e6);
				UHD_DO(uhd_usrp_set_rx_bandwidth(usrp, rx_bw[ch], rx_channels[ch]));
				//Band
				UHD_DO(uhd_usrp_get_rx_bandwidth(usrp, rx_channels[ch], &rx_bw[ch]));
				fprintf(stderr, "Actual RX Bandwidth: %lf MHz...\n", rx_bw[ch] / 1e6);
				fflush(stderr);
M
manjaro-xfce 已提交
350
			}//end for (int ch = 0; ch < rx_channel_count;++ch)
M
manjaro-xfce 已提交
351 352 353 354 355 356 357 358
			annouce_handle(
						args.toString("instance","0"),
						"0",
						"rx_time",
						"",
						"rx_time",
						"string"
						   );
M
manjaro-xfce 已提交
359
		}//end if (rx_on)
M
manjaro-xfce 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
		if (tx_on)
		{
			// Create TX streamer
			UHD_DO(uhd_tx_streamer_make(&tx_streamer));
			// Create TX metadata
			UHD_DO(uhd_tx_metadata_make(&tx_meta, false, 0,0, false, false));

			//TX Per-Channel Settings
			for (int ch = 0;ch < tx_channel_count;++ch)
			{
				fprintf(stderr, "Setting TX Channel: %d=%lu...\n",ch, tx_channels[ch]);
				UHD_DO(uhd_usrp_set_tx_antenna(usrp,tx_atn[ch].c_str(),ch));
				// Set rate
				fprintf(stderr, "Setting TX Rate: %lf...\n", tx_rate);
				UHD_DO(uhd_usrp_set_tx_rate(usrp, tx_rate, tx_channels[ch]));
				// See what rate actually is
				UHD_DO(uhd_usrp_get_tx_rate(usrp, tx_channels[ch], &tx_rate));
				fprintf(stderr, "Actual TX Rate: %lf...\n\n", tx_rate);
				// Set gain
				fprintf(stderr, "Setting TX Gain: %lf db...\n", tx_gain[ch]);
				UHD_DO(uhd_usrp_set_tx_gain(usrp, tx_gain[ch],tx_channels[ch], ""));
				// See what gain actually is
				UHD_DO(uhd_usrp_get_tx_gain(usrp, tx_channels[ch], "", &tx_gain[ch]));
				fprintf(stderr, "Actual TX Gain: %lf...\n", tx_gain[ch]);
384 385 386 387 388 389 390 391 392 393
				annouce_handle(
							args.toString("instance","0"),
							"0",
							QString("txgain_%1").arg(ch).toStdString(),
							QString("%1").arg(tx_gain[ch]).toStdString(),
							QString("txgain_%1").arg(ch).toStdString(),
							"int",
							"0:100"
							   );

M
manjaro-xfce 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
				// Create other necessary structs for TX
				uhd_tune_request_t tx_tune_request = {
					/*.target_freq = */tx_freq[ch],
					/*.rf_freq_policy = */UHD_TUNE_REQUEST_POLICY_AUTO,
					/*.rf_freq = */0,
					/*.dsp_freq_policy = */UHD_TUNE_REQUEST_POLICY_AUTO,
					/*.dsp_freq = */0,
					/*.args = */0
				};
				uhd_tune_result_t tx_tune_result;
				// Set frequency
				fprintf(stderr, "Setting TX frequency: %f MHz...\n", tx_freq[ch] / 1e6);
				UHD_DO(uhd_usrp_set_tx_freq(usrp, &tx_tune_request, tx_channels[ch], &tx_tune_result));

				// See what frequency actually is
				UHD_DO(uhd_usrp_get_tx_freq(usrp, tx_channels[ch], &tx_freq[ch]));
				fprintf(stderr, "Actual TX frequency: %f MHz...\n", tx_freq[ch] / 1e6);
411 412 413 414 415 416 417 418 419
				annouce_handle(
							args.toString("instance","0"),
							"0",
							QString("txfreq_%1").arg(ch).toStdString(),
							QString("%1").arg(tx_freq[ch]).toStdString(),
							QString("txfreq_%1").arg(ch).toStdString(),
							"double",
							"0:6000000000","100000","0"
							   );
M
manjaro-xfce 已提交
420 421 422 423 424 425
				//Band
				fprintf(stderr, "Setting TX Bandwidth: %f MHz...\n", tx_bw[ch]/1e6);
				UHD_DO(uhd_usrp_set_tx_bandwidth(usrp, tx_bw[ch],tx_channels[ch]));

				UHD_DO(uhd_usrp_get_tx_bandwidth(usrp, tx_channels[ch], &tx_bw[ch]));
				fprintf(stderr, "Actual TX Bandwidth: %f MHz...\n", tx_bw[ch] / 1e6);
M
manjaro-xfce 已提交
426 427
			}//end for (int ch = 0;ch < tx_channel_count;++ch)
		}//end if (tx_on)
M
manjaro-xfce 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
		char rx_cpu_format[] = "sc16";
		char rx_otw_format[] = "sc16";
		char rx_args[] = "";

		uhd_stream_args_t rx_stream_args = {
			/* .cpu_format = */rx_cpu_format,
			/* .otw_format = */rx_otw_format,
			/* .args = */rx_args,
			/* .channel_list = */rx_channels.data(),
			/*.n_channels = */rx_channel_count
		};
		uhd_stream_cmd_t rx_stream_cmd = {
			/*.stream_mode = */UHD_STREAM_MODE_START_CONTINUOUS,
			/*.num_samps = */0,
			/*.stream_now = */false,
			/*.time_spec_full_secs = */time_sync,
			/*.time_spec_frac_secs = */0
		};

		//char tx_cpu_format[] = "fc32";
		char tx_cpu_format[] = "sc16";
		char tx_otw_format[] = "sc16";
		char tx_args[] = "";

		uhd_stream_args_t tx_stream_args = {
			/*.cpu_format = */tx_cpu_format,
			/*.otw_format = */tx_otw_format,
			/*.args = */tx_args,
			/*.channel_list = */tx_channels.data(),
			/* .n_channels = */tx_channel_count
		};
		size_t rx_sps_buff = 0;
		size_t tx_sps_buff = 0;
		if (rx_on)
		{
			// Set up streamer
			UHD_DO(uhd_usrp_get_rx_stream(usrp, &rx_stream_args, rx_streamer));
			// Set up buffer
			UHD_DO(uhd_rx_streamer_max_num_samps(rx_streamer, &rx_sps_buff));
			fprintf(stderr, "RX Buffer size in samples: %zu\n", rx_sps_buff);
		}
		if (tx_on)
		{
			UHD_DO(uhd_usrp_get_tx_stream(usrp, &tx_stream_args, tx_streamer));
			// Set up buffer
			UHD_DO(uhd_tx_streamer_max_num_samps(tx_streamer, &tx_sps_buff));
			fprintf(stderr, "TX Buffer size in samples: %zu\n", tx_sps_buff);
			fflush(stderr);
		}

		//ring buffer in short inters
479
		const quint64 sz_buffer_rx = 16384;
M
manjaro-xfce 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
		std::vector<tag_sig_block> buf_rx_list;
		//In Blocks, RX io
		quint64 rx_pos = 0,stdout_pos = 0;
		for (size_t buf_ct = 0; buf_ct < sz_buffer_rx; ++buf_ct)
		{
			tag_sig_block block;
			block.tmstmp.frag = 0;
			block.tmstmp.sec = 0;
			block.ch_len = 0;
			//IQ样点
			for (int ch = 0;ch<rx_channel_count;++ch)
				block.ch_data.push_back(std::vector<unsigned char>(rx_sps_buff*2*sizeof(SPTYPE),0));
			buf_rx_list.push_back(std::move(block));
		}
		for (size_t buf_ct = 0; buf_ct < sz_buffer_rx; ++buf_ct)
		{
			for (int ch = 0;ch<rx_channel_count;++ch)
				buf_rx_list[buf_ct].ch_ptr.push_back((void *)buf_rx_list[buf_ct].ch_data[ch].data());
		}

		//reset time
		uhd_usrp_set_time_now(usrp,0,0,0);
		//Define RX Thread, Producer
		std::function<void()> thread_rx = [&]()->void
		{
			try{
				// Issue stream command
				fprintf(stderr, "Issuing stream command.\n");
				UHD_DO(uhd_rx_streamer_issue_stream_cmd(rx_streamer, &rx_stream_cmd));
				//Read, RX
				while (!stop_signal_called) {
					buf_rx_list[rx_pos % sz_buffer_rx].tmstmp.sec = 0;
					buf_rx_list[rx_pos % sz_buffer_rx].tmstmp.frag = 0;
					// Handle data
					UHD_DO(uhd_rx_streamer_recv(
							   rx_streamer,
							   buf_rx_list[rx_pos % sz_buffer_rx].ch_ptr.data(),
							   rx_sps_buff,
							   &rx_meta, 5, true, &buf_rx_list[rx_pos % sz_buffer_rx].ch_len));
					uhd_rx_metadata_error_code_t error_code;
					UHD_DO(uhd_rx_metadata_error_code(rx_meta, &error_code));
					if(error_code != UHD_RX_METADATA_ERROR_CODE_NONE){
						fprintf(stderr, "Warning: Error code 0x%x 16was returned during streaming.\n", error_code);
						fputs(error_string,stderr);
					}
					else
					{
						bool hasTm;
						UHD_DO(uhd_rx_metadata_has_time_spec(rx_meta, &hasTm));
						if (hasTm)
						{
M
manjaro-xfce 已提交
531
							int64_t rx_time_sec;
M
manjaro-xfce 已提交
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
							double rx_time_frag;
							uhd_rx_metadata_time_spec(rx_meta,
													  &rx_time_sec, & rx_time_frag);
							buf_rx_list[rx_pos % sz_buffer_rx].tmstmp.sec = rx_time_sec;
							buf_rx_list[rx_pos % sz_buffer_rx].tmstmp.frag = rx_time_frag;
						}
					}
					++rx_pos;
				}
			}
			catch (std::string er)
			{
				fputs(er.c_str(),stderr);
				stop_signal_called = true;
			}
M
manjaro-xfce 已提交
547
		};//end std::function<void()> thread_rx = [&]()->void
M
manjaro-xfce 已提交
548 549 550 551 552 553


		//Define StdOut Thread, Consumer
		std::function<void()> thread_stdout = [&]()->void
		{
			try{
M
manjaro-xfce 已提交
554
				unsigned int ct_br = 0;
555
				//Read, RX
M
manjaro-xfce 已提交
556 557 558 559 560 561 562
				while (!stop_signal_called)
				{
					if (stdout_pos >= rx_pos)
					{
						QThread::msleep(1);
						continue;
					}
M
manjaro-xfce 已提交
563 564 565 566 567 568 569
					if (++ct_br % 1000==0)
						set_handle(args.toString("instance","0"),
									"0",
									"rx_time",
									QString("%1.%2")
								   .arg(buf_rx_list[stdout_pos % sz_buffer_rx].tmstmp.sec)
									.arg(buf_rx_list[stdout_pos % sz_buffer_rx].tmstmp.frag).toStdString());
M
manjaro-xfce 已提交
570 571 572 573 574 575
					if (i_rx_tm)
					{
						TASKBUS::push_subject(
									i_rx_tm,
									instance,
									sizeof(tag_timestmp),
丁劲犇's avatar
丁劲犇 已提交
576 577
									(unsigned char *) &buf_rx_list[stdout_pos % sz_buffer_rx].tmstmp,
									pMtx);
M
manjaro-xfce 已提交
578 579
					}
					for (int ch = 0;ch<rx_channel_count;++ch)
M
manjaro-xfce 已提交
580
					{
M
manjaro-xfce 已提交
581 582 583 584 585 586 587
						if (i_wav_rx[ch]>0)
						{
							tag_sig_block & dta = buf_rx_list[stdout_pos % sz_buffer_rx];
							TASKBUS::push_subject(
										i_wav_rx[ch],
										instance,
										buf_rx_list[stdout_pos % sz_buffer_rx].ch_len * 2 * sizeof(SPTYPE),
丁劲犇's avatar
丁劲犇 已提交
588 589
										(unsigned char *) dta.ch_data[ch].data(),
										pMtx);
M
manjaro-xfce 已提交
590 591 592 593 594 595 596 597 598 599
						}
					}
					++stdout_pos;
				}
			}
			catch (std::string er)
			{
				fputs(er.c_str(),stderr);
				stop_signal_called = true;
			}
M
manjaro-xfce 已提交
600
		};//end std::function<void()> thread_stdout = [&]()->void
M
manjaro-xfce 已提交
601 602 603 604 605 606 607 608 609

		const int tx_frame = 10000;
		//Define thread_tx, Consumer
		std::function<void()> thread_tx = [&]()->void
		{
			try{
				while (!stop_signal_called)
				{
					bool can_send = true;
M
manjaro-xfce 已提交
610 611 612 613 614
					if (total_points_left==0)
					{
						QThread::msleep(1);
						continue;
					}
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
					else if (total_points_left<0)
					{
						if (i_txWaterMark>0)
						{
							qint64 watM = stdin_pos[0] - tx_pos[0];
							if (tx_channel_count>1)
							{
								qint64 wat2 = stdin_pos[1] - tx_pos[1];
								if (wat2 < watM)
									watM = wat2;
							}
							TASKBUS::push_subject(
										i_txWaterMark,
										instance,
										sizeof(qint64),
丁劲犇's avatar
丁劲犇 已提交
630 631
										(unsigned char *) &watM,
										pMtx);
632 633 634

						}
					}
M
manjaro-xfce 已提交
635 636 637
					for (int ch=0;ch<tx_channel_count && can_send;++ch)
					{
						SPTYPE * buf_tx_ptr = buf_tx_array[ch].data();
M
manjaro-xfce 已提交
638 639
						//连续模式数据不够
						if (stdin_pos[ch] < (tx_sps_buff + tx_frame)*10 && total_points_left<0)
M
manjaro-xfce 已提交
640 641 642 643
						{
							can_send = false;
							continue;
						}
M
manjaro-xfce 已提交
644 645 646 647 648 649 650
						//连续模式数据不够
						if (tx_pos[ch] + (long long) (tx_sps_buff + tx_frame) >= stdin_pos[ch] && total_points_left<0)
						{
							can_send = false;
							continue;
						}
						//突发模式数据不够
M
manjaro-xfce 已提交
651 652
						if (total_points_left >0 &&  tx_pos[ch] + (long long) (tx_sps_buff ) > stdin_pos[ch]
								&&  tx_pos[ch] + (long long) (total_points_left ) > stdin_pos[ch]
M
manjaro-xfce 已提交
653
								)
M
manjaro-xfce 已提交
654
						{
655
							fprintf(stderr,"total_points LESS! for %d points\n",total_points_left);
M
manjaro-xfce 已提交
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
							can_send = false;
							continue;
						}
						const quint64 bgnext = ((tx_pos[ch] + tx_sps_buff) * 2) % sz_buffer_tx;
						//Dealing with the tail
						if (bgnext < tx_sps_buff * 2 && bgnext>0)
						{
							memcpy( buf_tx_ptr + sz_buffer_tx, buf_tx_ptr, bgnext * sizeof(SPTYPE) );
						}
						SPTYPE * tx_buff = &buf_tx_ptr[(tx_pos[ch] * 2) % sz_buffer_tx];
						tx_buff_ptr[ch] = (void *)tx_buff;
					}
					if (!can_send)
					{
						QThread::msleep(1);
					}
M
manjaro-xfce 已提交
672 673
					//Continous
					else if (total_points_left<0)
M
manjaro-xfce 已提交
674 675 676 677
					{
						UHD_DO(uhd_tx_streamer_send(tx_streamer,
													(const void **)tx_buff_ptr.data(),
													tx_sps_buff, &tx_meta,0.1, &num_sps_sent));
678
						//tx_meta->tx_metadata_ctmstmppp.start_of_burst = false;
M
manjaro-xfce 已提交
679 680 681
						for(int ch = 0;ch<tx_channel_count;++ch)
							tx_pos[ch] += num_sps_sent;
					}
M
manjaro-xfce 已提交
682 683 684 685
					//Burst
					else
					{
						assert(total_points_left>0);
686
						uhd_tx_metadata_handle tx_meta_burst = nullptr;
M
manjaro-xfce 已提交
687 688 689 690 691 692
						size_t emit_points = tx_sps_buff;
						//Mutex is not needed.
						tag_tx_plain * plan = &tx_plan.front();
						//First pack
						if (plan->length_left==total_points_left)
						{
M
manjaro-xfce 已提交
693
							//fprintf(stderr,"total_points start for %d points\n",total_points_left);
M
manjaro-xfce 已提交
694
							if (total_points_left <= (qint64)tx_sps_buff)
695
							{
696 697 698
								UHD_DO(uhd_tx_metadata_make(&tx_meta_burst,
															plan->tmstmp.sec?true:false,
															plan->tmstmp.sec,plan->tmstmp.frag,true,true));
699
							}
M
manjaro-xfce 已提交
700
							else
701
							{
702 703 704
								UHD_DO(uhd_tx_metadata_make(&tx_meta_burst,
															plan->tmstmp.sec?true:false,
															plan->tmstmp.sec,plan->tmstmp.frag,true,false));
705
							}
M
manjaro-xfce 已提交
706 707 708 709
						}
						//Last pack
						else if (total_points_left <= (qint64)tx_sps_buff)
						{
M
manjaro-xfce 已提交
710
							//fprintf(stderr,"total_points end for %d points\n",total_points_left);
M
manjaro-xfce 已提交
711
							emit_points = total_points_left;
712
							UHD_DO(uhd_tx_metadata_make(&tx_meta_burst,false,0,0,false,true));
M
manjaro-xfce 已提交
713 714
						}
						else
M
manjaro-xfce 已提交
715 716
						{
							//fprintf(stderr,"total_points middle for %d points\n",total_points_left);
717
							UHD_DO(uhd_tx_metadata_make(&tx_meta_burst,false,0,0,false,false));
M
manjaro-xfce 已提交
718
						}
M
manjaro-xfce 已提交
719 720 721

						UHD_DO(uhd_tx_streamer_send(tx_streamer,
													(const void **)tx_buff_ptr.data(),
722
													emit_points, &tx_meta_burst,600, &num_sps_sent));
M
manjaro-xfce 已提交
723 724 725 726 727
						//Middle of burst
						for(int ch = 0;ch<tx_channel_count;++ch)
							tx_pos[ch] += num_sps_sent;
						total_points_left -= num_sps_sent;
						assert(total_points_left>=0);
728
						if(total_points_left<=0)
M
manjaro-xfce 已提交
729
						{
M
manjaro-xfce 已提交
730
							//fprintf(stderr,"total_points over\n");
M
manjaro-xfce 已提交
731 732 733 734 735 736 737
							mtx_plan.lock();
							assert(tx_plan.size());
							tx_plan.pop_front();
							if (tx_plan.size())
								total_points_left = tx_plan.front().length_left;
							mtx_plan.unlock();
						}
738
						UHD_DO(uhd_tx_metadata_free(&tx_meta_burst));
M
manjaro-xfce 已提交
739
						//fprintf(stderr,"total_points left %d points\n",total_points_left);
M
manjaro-xfce 已提交
740 741 742
					}//end else if (total_points_left>0)

				}//end while (!stop_signal_called)
M
manjaro-xfce 已提交
743 744 745 746 747 748
			}
			catch(std::string er)
			{
				fputs(er.c_str(),stderr);
				stop_signal_called = true;
			}
M
manjaro-xfce 已提交
749
		};//end std::function<void()> thread_tx = [&]()->void
M
manjaro-xfce 已提交
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780

		uhd_io_thread th_wav_rx(thread_rx,0);
		uhd_io_thread th_wav_stdout(thread_stdout,0);
		uhd_io_thread th_wav_tx(thread_tx,0);

		if (rx_on)
		{
			th_wav_rx.start(QThread::HighestPriority);
			th_wav_stdout.start(QThread::HighestPriority);
		}
		if (tx_on)
		{
			th_wav_tx.start(QThread::HighestPriority);
		}

		while (!stop_signal_called)
		{
			fprintf(stderr,"\nRX:");
			fprintf (stderr,"%lld,%lld;",rx_pos,stdout_pos);
			fprintf(stderr,"\n");
			fprintf(stderr,"TX:");
			for (int ch = 0;ch<tx_channel_count;++ch)
				fprintf (stderr,"%d:%lld,%lld;",ch,stdin_pos[ch],tx_pos[ch]);
			fprintf(stderr,"\n");
			fflush(stderr);
			QThread::msleep(1000);
		}

		th_wav_rx.wait();
		th_wav_stdout.wait();
		th_wav_tx.wait();
M
manjaro-xfce 已提交
781
	}//end top try
M
manjaro-xfce 已提交
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
	catch(std::string s)
	{
		fputs(s.c_str(),stderr);
	}

	fflush(stderr);

	if (tx_streamer) uhd_tx_streamer_free(&tx_streamer);
	if (rx_streamer) uhd_rx_streamer_free(&rx_streamer);
	if (tx_meta) uhd_tx_metadata_free(&tx_meta);
	if (rx_meta) uhd_rx_metadata_free(&rx_meta);

	if(return_code != EXIT_SUCCESS && usrp != nullptr){
		uhd_usrp_last_error(usrp, error_string, 512);
		fprintf(stderr, "USRP reported the following error: %s\n", error_string);
	}
	uhd_usrp_free(&usrp);

800 801
	th_wav_stdin.wait();

M
manjaro-xfce 已提交
802 803 804 805
	fprintf(stderr, (return_code ? "Failure\n" : "Success\n"));
	fflush(stderr);
	return return_code;
}
806 807 808

void cmd_dealing(uhd_usrp_handle usrp,std::vector<unsigned char> & cmd)
{
809 810
	if (!usrp)
		return ;
811 812 813 814 815 816 817 818 819 820 821
	std::map<std::string,std::string> mcmd = TASKBUS::ctrlpackage_to_map(cmd);
	if (mcmd["function"]=="handle_set")
	{
		if (mcmd["handle"].find("rxgain_")!=mcmd["handle"].npos)
		{
			int channel = atoi(mcmd["handle"].substr(7).c_str());
			int gain = atoi(mcmd["value"].c_str());
			uhd_usrp_set_rx_gain(usrp,gain,channel,"");
			double dgain = 0;
			uhd_usrp_get_rx_gain(usrp, channel, "", &dgain);
			fprintf(stderr, "Actual RX Gain: %lf...\n", dgain);
822

823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
		}
		else if (mcmd["handle"].find("txgain_")!=mcmd["handle"].npos)
		{
			int channel = atoi(mcmd["handle"].substr(7).c_str());
			int gain = atoi(mcmd["value"].c_str());
			uhd_usrp_set_tx_gain(usrp,gain,channel,"");
			double dgain = 0;
			uhd_usrp_get_tx_gain(usrp, channel, "", &dgain);
			fprintf(stderr, "Actual TX Gain: %lf...\n", dgain);

		}
		else if (mcmd["handle"].find("rxfreq_")!=mcmd["handle"].npos)
		{
			int channel = atoi(mcmd["handle"].substr(7).c_str());
			double freq = atof(mcmd["value"].c_str());
			uhd_tune_request_t rx_tune_request =
			{
				/*.target_freq = */freq,
				/*.rf_freq_policy = */UHD_TUNE_REQUEST_POLICY_AUTO,
				/*.rf_freq = */0,
				/*.dsp_freq_policy = */UHD_TUNE_REQUEST_POLICY_AUTO,
				/*.dsp_freq = */0,
				/*.args = */0
			};
			uhd_tune_result_t rx_tune_result;
			fprintf(stderr, "Setting RX frequency: %lf MHz...\n", freq/1e6);
			uhd_usrp_set_rx_freq(usrp, &rx_tune_request, channel, &rx_tune_result);
		}
		else if (mcmd["handle"].find("txfreq_")!=mcmd["handle"].npos)
		{
			int channel = atoi(mcmd["handle"].substr(7).c_str());
			double freq = atof(mcmd["value"].c_str());
			uhd_tune_request_t tx_tune_request =
			{
				/*.target_freq = */freq,
				/*.rf_freq_policy = */UHD_TUNE_REQUEST_POLICY_AUTO,
				/*.rf_freq = */0,
				/*.dsp_freq_policy = */UHD_TUNE_REQUEST_POLICY_AUTO,
				/*.dsp_freq = */0,
				/*.args = */0
			};
			uhd_tune_result_t rx_tune_result;
			fprintf(stderr, "Setting RX frequency: %lf MHz...\n", freq/1e6);
			uhd_usrp_set_tx_freq(usrp, &tx_tune_request, channel, &rx_tune_result);
		}
	}
}