コード例 #1
1
ファイル: hackrf_rxtx.c プロジェクト: glenoverby/hackrf
int main(int argc, char** argv) {
	int opt;
	char path_file[PATH_FILE_MAX_LEN];
	char date_time[DATE_TIME_MAX_LEN];
	const char* rxpath = NULL;
	const char* txpath = NULL;
	int result;
	time_t rawtime;
	struct tm * timeinfo;
	long int file_pos;
	int exit_code = EXIT_SUCCESS;
	struct timeval t_end;
	float time_diff;
	unsigned int lna_gain=8, vga_gain=20, txvga_gain=0;
	int udpport = 8192;
  
	while( (opt = getopt(argc, argv, "wr:t:f:i:o:m:a:p:s:n:b:l:g:x:c:u:")) != EOF )
	{
		result = HACKRF_SUCCESS;
		switch( opt ) 
		{
		case 'w':
			receive_wav = true;
			break;
		
		case 'r':
			receive = true;
			rxpath = optarg;
			break;
		
		case 't':
			transmit = true;
			txpath = optarg;
			break;

		case 'f':
			automatic_tuning = true;
			result = parse_u64(optarg, &freq_hz);
			break;

		case 'i':
			if_freq = true;
			result = parse_u64(optarg, &if_freq_hz);
			break;

		case 'o':
			lo_freq = true;
			result = parse_u64(optarg, &lo_freq_hz);
			break;

		case 'm':
			image_reject = true;
			result = parse_u32(optarg, &image_reject_selection);
			break;

		case 'a':
			amp = true;
			result = parse_u32(optarg, &amp_enable);
			break;

		case 'p':
			antenna = true;
			result = parse_u32(optarg, &antenna_enable);
			break;

		case 'l':
			result = parse_u32(optarg, &lna_gain);
			break;

		case 'g':
			result = parse_u32(optarg, &vga_gain);
			break;

		case 'x':
			result = parse_u32(optarg, &txvga_gain);
			break;

		case 's':
			sample_rate = true;
			result = parse_u32(optarg, &sample_rate_hz);
			break;

		case 'n':
			limit_num_samples = true;
			result = parse_u64(optarg, &samples_to_xfer);
			bytes_to_xfer = samples_to_xfer * 2ull;
			break;

		case 'b':
			baseband_filter_bw = true;
			result = parse_u32(optarg, &baseband_filter_bw_hz);
			break;

		case 'c':
			transmit = true;
			signalsource = true;
			result = parse_u32(optarg, &amplitude);
			break;

		case 'u':
			udpport = atoi(optarg);
			break;

		default:
			printf("unknown argument '-%c %s'\n", opt, optarg);
			usage();
			return EXIT_FAILURE;
		}
		
		if( result != HACKRF_SUCCESS ) {
			printf("argument error: '-%c %s' %s (%d)\n", opt, optarg, hackrf_error_name(result), result);
			return EXIT_FAILURE;
		}		
	}

	if (samples_to_xfer >= SAMPLES_TO_XFER_MAX) {
		printf("argument error: num_samples must be less than %s/%sMio\n",
			u64toa(SAMPLES_TO_XFER_MAX,&ascii_u64_data1),
			u64toa((SAMPLES_TO_XFER_MAX/FREQ_ONE_MHZ),&ascii_u64_data2));
		return EXIT_FAILURE;
	}

	if (if_freq || lo_freq || image_reject) {
		/* explicit tuning selected */
		if (!if_freq) {
			printf("argument error: if_freq_hz must be specified for explicit tuning.\n");
			return EXIT_FAILURE;
		}
		if (!image_reject) {
			printf("argument error: image_reject must be specified for explicit tuning.\n");
			return EXIT_FAILURE;
		}
		if (!lo_freq && (image_reject_selection != RF_PATH_FILTER_BYPASS)) {
			printf("argument error: lo_freq_hz must be specified for explicit tuning unless image_reject is set to bypass.\n");
			return EXIT_FAILURE;
		}
		if ((if_freq_hz > IF_MAX_HZ) || (if_freq_hz < IF_MIN_HZ)) {
			printf("argument error: if_freq_hz shall be between %s and %s.\n",
				u64toa(IF_MIN_HZ,&ascii_u64_data1),
				u64toa(IF_MAX_HZ,&ascii_u64_data2));
			return EXIT_FAILURE;
		}
		if ((lo_freq_hz > LO_MAX_HZ) || (lo_freq_hz < LO_MIN_HZ)) {
			printf("argument error: lo_freq_hz shall be between %s and %s.\n",
				u64toa(LO_MIN_HZ,&ascii_u64_data1),
				u64toa(LO_MAX_HZ,&ascii_u64_data2));
			return EXIT_FAILURE;
		}
		if (image_reject_selection > 2) {
			printf("argument error: image_reject must be 0, 1, or 2 .\n");
			return EXIT_FAILURE;
		}
		if (automatic_tuning) {
			printf("warning: freq_hz ignored by explicit tuning selection.\n");
			automatic_tuning = false;
		}
		switch (image_reject_selection) {
		case RF_PATH_FILTER_BYPASS:
			freq_hz = if_freq_hz;
			break;
		case RF_PATH_FILTER_LOW_PASS:
			freq_hz = abs(if_freq_hz - lo_freq_hz);
			break;
		case RF_PATH_FILTER_HIGH_PASS:
			freq_hz = if_freq_hz + lo_freq_hz;
			break;
		default:
			freq_hz = DEFAULT_FREQ_HZ;
			break;
		}
		printf("explicit tuning specified for %s Hz.\n",
			u64toa(freq_hz,&ascii_u64_data1));

	} else if (automatic_tuning) {
		if( (freq_hz > FREQ_MAX_HZ) || (freq_hz < FREQ_MIN_HZ) )
		{
			printf("argument error: freq_hz shall be between %s and %s.\n",
				u64toa(FREQ_MIN_HZ,&ascii_u64_data1),
				u64toa(FREQ_MAX_HZ,&ascii_u64_data2));
			return EXIT_FAILURE;
		}
	} else {
		/* Use default freq */
		freq_hz = DEFAULT_FREQ_HZ;
		automatic_tuning = true;
	}

	if( amp ) {
		if( amp_enable > 1 )
		{
			printf("argument error: amp_enable shall be 0 or 1.\n");
			return EXIT_FAILURE;
		}
	}

	if (antenna) {
		if (antenna_enable > 1) {
			printf("argument error: antenna_enable shall be 0 or 1.\n");
			return EXIT_FAILURE;
		}
	}

	if( sample_rate == false ) 
	{
		sample_rate_hz = DEFAULT_SAMPLE_RATE_HZ;
	}

	if( baseband_filter_bw )
	{
		/* Compute nearest freq for bw filter */
		baseband_filter_bw_hz = hackrf_compute_baseband_filter_bw(baseband_filter_bw_hz);
	}else
	{
		/* Compute default value depending on sample rate */
		baseband_filter_bw_hz = hackrf_compute_baseband_filter_bw_round_down_lt(sample_rate_hz);
	}

	if (baseband_filter_bw_hz > BASEBAND_FILTER_BW_MAX) {
		printf("argument error: baseband_filter_bw_hz must be less or equal to %u Hz/%.03f MHz\n",
				BASEBAND_FILTER_BW_MAX, (float)(BASEBAND_FILTER_BW_MAX/FREQ_ONE_MHZ));
		return EXIT_FAILURE;
	}

	if (baseband_filter_bw_hz < BASEBAND_FILTER_BW_MIN) {
		printf("argument error: baseband_filter_bw_hz must be greater or equal to %u Hz/%.03f MHz\n",
				BASEBAND_FILTER_BW_MIN, (float)(BASEBAND_FILTER_BW_MIN/FREQ_ONE_MHZ));
		return EXIT_FAILURE;
	}

	if( receive ) {
		transceiver_mode = TRANSCEIVER_MODE_RX;
	} else if( transmit ) {
		transceiver_mode = TRANSCEIVER_MODE_TX;
	}

	if (signalsource) {
		transceiver_mode = TRANSCEIVER_MODE_SS;
		if (amplitude >127) {
			printf("argument error: amplitude shall be in between 0 and 128.\n");
			return EXIT_FAILURE;
		}
	}

	if( receive_wav )
	{
		time (&rawtime);
		timeinfo = localtime (&rawtime);
		transceiver_mode = TRANSCEIVER_MODE_RX;
		/* File format HackRF Year(2013), Month(11), Day(28), Hour Min Sec+Z, Freq kHz, IQ.wav */
		strftime(date_time, DATE_TIME_MAX_LEN, "%Y%m%d_%H%M%S", timeinfo);
		snprintf(path_file, PATH_FILE_MAX_LEN, "HackRF_%sZ_%ukHz_IQ.wav", date_time, (uint32_t)(freq_hz/(1000ull)) );
		rxpath = path_file;
		printf("Receive wav file: %s\n", rxpath);
	}	

	// In signal source mode, the PATH argument is neglected.
	if (transceiver_mode != TRANSCEIVER_MODE_SS) {
		if( rxpath == NULL && txpath == NULL) {
			printf("specify a path to a file to transmit/receive\n");
			return EXIT_FAILURE;
		}
	}

	result = hackrf_init();
	if( result != HACKRF_SUCCESS ) {
		printf("hackrf_init() failed: %s (%d)\n", hackrf_error_name(result), result);
		return EXIT_FAILURE;
	}
	
	result = hackrf_open(&device);
	if( result != HACKRF_SUCCESS ) {
		printf("hackrf_open() failed: %s (%d)\n", hackrf_error_name(result), result);
		return EXIT_FAILURE;
	}
	
	if (transceiver_mode != TRANSCEIVER_MODE_SS) {
		if( rxpath != NULL )
		{
			rxfd = fopen(rxpath, "wb");
			if( rxfd == NULL ) {
				printf("Failed to open file: %s\n", rxpath);
				return EXIT_FAILURE;
			}
			/* Change fd buffer to have bigger one to store or read data on/to HDD */
			setvbuf(rxfd , NULL , _IOFBF , FD_BUFFER_SIZE);
		}
		if( txpath != NULL )
		{
			txfd = fopen(txpath, "rb");
			if( txfd == NULL ) {
				printf("Failed to open file: %s\n", txpath);
				return EXIT_FAILURE;
			}
			/* Change fd buffer to have bigger one to store or read data on/to HDD */
			setvbuf(txfd , NULL , _IOFBF , FD_BUFFER_SIZE);
		}
	}

	/* Write Wav header */
	if( receive_wav ) 
	{
		fwrite(&wave_file_hdr, 1, sizeof(t_wav_file_hdr), rxfd);
	}
	
#ifdef _MSC_VER
	SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
#else
	signal(SIGINT, &sigint_callback_handler);
	//signal(SIGILL, &sigint_callback_handler);
	//signal(SIGFPE, &sigint_callback_handler);
	//signal(SIGSEGV, &sigint_callback_handler);
	//signal(SIGTERM, &sigint_callback_handler);
	//signal(SIGABRT, &sigint_callback_handler);
#endif
	printf("call hackrf_sample_rate_set(%u Hz/%.03f MHz)\n", sample_rate_hz,((float)sample_rate_hz/(float)FREQ_ONE_MHZ));
	result = hackrf_set_sample_rate_manual(device, sample_rate_hz, 1);
	if( result != HACKRF_SUCCESS ) {
		printf("hackrf_sample_rate_set() failed: %s (%d)\n", hackrf_error_name(result), result);
		return EXIT_FAILURE;
	}

	printf("call hackrf_baseband_filter_bandwidth_set(%d Hz/%.03f MHz)\n",
			baseband_filter_bw_hz, ((float)baseband_filter_bw_hz/(float)FREQ_ONE_MHZ));
	result = hackrf_set_baseband_filter_bandwidth(device, baseband_filter_bw_hz);
	if( result != HACKRF_SUCCESS ) {
		printf("hackrf_baseband_filter_bandwidth_set() failed: %s (%d)\n", hackrf_error_name(result), result);
		return EXIT_FAILURE;
	}

	result = hackrf_set_vga_gain(device, vga_gain);
	result |= hackrf_set_lna_gain(device, lna_gain);
	result |= hackrf_set_txvga_gain(device, txvga_gain);
	if (rxfd != NULL) {
		result |= hackrf_start_rx(device, rx_callback, NULL);
	} else {
		result |= hackrf_start_tx(device, tx_callback, NULL);
	}

#if 0
	if( transceiver_mode == TRANSCEIVER_MODE_RX ) {
		result |= hackrf_start_rx(device, rx_callback, NULL);
	} else {
		result |= hackrf_start_tx(device, tx_callback, NULL);
	}
#endif

	if( result != HACKRF_SUCCESS ) {
		printf("hackrf_start_?x() failed: %s (%d)\n", hackrf_error_name(result), result);
		return EXIT_FAILURE;
	}

	if (automatic_tuning) {
		printf("call hackrf_set_freq(%s Hz/%.03f MHz)\n",
			u64toa(freq_hz, &ascii_u64_data1),((double)freq_hz/(double)FREQ_ONE_MHZ) );
		result = hackrf_set_freq(device, freq_hz);
		if( result != HACKRF_SUCCESS ) {
			printf("hackrf_set_freq() failed: %s (%d)\n", hackrf_error_name(result), result);
			return EXIT_FAILURE;
		}
	} else {
		printf("call hackrf_set_freq_explicit() with %s Hz IF, %s Hz LO, %s\n",
				u64toa(if_freq_hz,&ascii_u64_data1),
				u64toa(lo_freq_hz,&ascii_u64_data2),
				hackrf_filter_path_name(image_reject_selection));
		result = hackrf_set_freq_explicit(device, if_freq_hz, lo_freq_hz,
				image_reject_selection);
		if (result != HACKRF_SUCCESS) {
			printf("hackrf_set_freq_explicit() failed: %s (%d)\n",
					hackrf_error_name(result), result);
			return EXIT_FAILURE;
		}
	}

	if( amp ) {
		printf("call hackrf_set_amp_enable(%u)\n", amp_enable);
		result = hackrf_set_amp_enable(device, (uint8_t)amp_enable);
		if( result != HACKRF_SUCCESS ) {
			printf("hackrf_set_amp_enable() failed: %s (%d)\n", hackrf_error_name(result), result);
			return EXIT_FAILURE;
		}
	}

	if (antenna) {
		printf("call hackrf_set_antenna_enable(%u)\n", antenna_enable);
		result = hackrf_set_antenna_enable(device, (uint8_t)antenna_enable);
		if (result != HACKRF_SUCCESS) {
			printf("hackrf_set_antenna_enable() failed: %s (%d)\n", hackrf_error_name(result), result);
			return EXIT_FAILURE;
		}
	}

	if( limit_num_samples ) {
		printf("samples_to_xfer %s/%sMio\n",
		u64toa(samples_to_xfer,&ascii_u64_data1),
		u64toa((samples_to_xfer/FREQ_ONE_MHZ),&ascii_u64_data2) );
	}
	
	gettimeofday(&t_start, NULL);
	gettimeofday(&time_start, NULL);

	printf("Stop with Ctrl-C\n");
	while(  /*(hackrf_is_streaming(device) == HACKRF_TRUE) && */
			(request_exit == false) ) 
	{
#if 0
		uint32_t byte_count_now;
		struct timeval time_now;
		float time_difference, rate;
		sleep(1);
		
		gettimeofday(&time_now, NULL);
		
		byte_count_now = byte_count;
		byte_count = 0;
		
		time_difference = TimevalDiff(&time_now, &time_start);
		rate = (float)byte_count_now / time_difference;
		printf("%4.1f MiB / %5.3f sec = %4.1f MiB/second\n",
				(byte_count_now / 1e6f), time_difference, (rate / 1e6f) );

		time_start = time_now;

		if (byte_count_now == 0) {
			exit_code = EXIT_FAILURE;
			printf("\nCouldn't transfer any bytes for one second.\n");
			break;
		}
#endif
		printf("hackrf_is%s_streaming\n", 
			hackrf_is_streaming(device)==HACKRF_TRUE ? "":"_not");
		usbsoftrock(udpport);
	}
	
	result = hackrf_is_streaming(device);	
	if (request_exit)
	{
		printf("\nUser cancel, exiting...\n");
	} else {
		printf("\nExiting... hackrf_is_streaming() result: %s (%d)\n", hackrf_error_name(result), result);
	}
	do_exit = true;
	
	gettimeofday(&t_end, NULL);
	time_diff = TimevalDiff(&t_end, &t_start);
	printf("Total time: %5.5f s\n", time_diff);
	
	if(device != NULL)
	{
		if( receive ) 
		{
			result = hackrf_stop_rx(device);
			if( result != HACKRF_SUCCESS ) {
				printf("hackrf_stop_rx() failed: %s (%d)\n", hackrf_error_name(result), result);
			}else {
				printf("hackrf_stop_rx() done\n");
			}
		}
	
		if( transmit ) 
		{
			result = hackrf_stop_tx(device);
			if( result != HACKRF_SUCCESS ) {
				printf("hackrf_stop_tx() failed: %s (%d)\n", hackrf_error_name(result), result);
			}else {
				printf("hackrf_stop_tx() done\n");
			}
		}
		
		result = hackrf_close(device);
		if( result != HACKRF_SUCCESS ) 
		{
			printf("hackrf_close() failed: %s (%d)\n", hackrf_error_name(result), result);
		}else {
			printf("hackrf_close() done\n");
		}
		
		hackrf_exit();
		printf("hackrf_exit() done\n");
	}
		
	if(rxfd != NULL)
	{
		if( receive_wav ) 
		{
			/* Get size of file */
			file_pos = ftell(rxfd);
			/* Update Wav Header */
			wave_file_hdr.hdr.size = file_pos+8;
			wave_file_hdr.fmt_chunk.dwSamplesPerSec = sample_rate_hz;
			wave_file_hdr.fmt_chunk.dwAvgBytesPerSec = wave_file_hdr.fmt_chunk.dwSamplesPerSec*2;
			wave_file_hdr.data_chunk.chunkSize = file_pos - sizeof(t_wav_file_hdr);
			/* Overwrite header with updated data */
			rewind(rxfd);
			fwrite(&wave_file_hdr, 1, sizeof(t_wav_file_hdr), rxfd);
		}	
		fclose(rxfd);
		rxfd = NULL;
		printf("fclose(rxfd) done\n");
	}
	printf("exit\n");
	return exit_code;
}
コード例 #2
0
ファイル: HackRFSource.cpp プロジェクト: f4exb/sdrdaemon
void HackRFSource::get_device_names(std::vector<std::string>& devices)
{
    hackrf_device *hackrf_ptr;
    read_partid_serialno_t read_partid_serialno;
    hackrf_error rc;
    int i;

    rc = (hackrf_error) hackrf_init();

    if (rc != HACKRF_SUCCESS)
    {
        std::cerr << "HackRFSource::get_device_names: Failed to open HackRF library: " << rc << ": " << hackrf_error_name(rc) << std::endl;
        return;
    }

    hackrf_device_list_t *hackrf_devices = hackrf_device_list();

    devices.clear();

    for (i=0; i < hackrf_devices->devicecount; i++)
    {
        rc = (hackrf_error) hackrf_device_list_open(hackrf_devices, i, &hackrf_ptr);

        if (rc == HACKRF_SUCCESS)
        {
            std::cerr << "HackRFSource::get_device_names: try to get device " << i << " serial number" << std::endl;
            rc = (hackrf_error) hackrf_board_partid_serialno_read(hackrf_ptr, &read_partid_serialno);

            if (rc != HACKRF_SUCCESS)
            {
                std::cerr << "HackRFSource::get_device_names: failed to get device " << i << " serial number: " << rc << ": " << hackrf_error_name(rc) << std::endl;
                hackrf_close(hackrf_ptr);
                continue;
            }
            else
            {
                std::cerr << "HackRFSource::get_device_names: device " << i << " OK" << std::endl;
                hackrf_close(hackrf_ptr);
            }

            uint32_t serial_msb = read_partid_serialno.serial_no[2];
            uint32_t serial_lsb = read_partid_serialno.serial_no[3];
            std::ostringstream devname_ostr;

            devname_ostr << "Serial " << std::hex << std::setw(8) << std::setfill('0') << serial_msb << serial_lsb;
            devices.push_back(devname_ostr.str());
        }
        else
        {
            std::cerr << "HackRFSource::get_device_names: failed to open device " << i << std::endl;
        }
    }

    hackrf_device_list_free(hackrf_devices);
    rc = (hackrf_error) hackrf_exit();
    std::cerr << "HackRFSource::get_device_names: HackRF library exit: " << rc << ": " << hackrf_error_name(rc) << std::endl;
}
コード例 #3
0
ファイル: hackRFSource.cpp プロジェクト: wpats/scanner
HackRFSource::~HackRFSource()
{
  if (this->m_dev != nullptr) {
    int status = hackrf_stop_rx(this->m_dev);
    double centerFrequency = this->GetCurrentFrequency();
    HANDLE_ERROR("Failed to stop RX streaming at %u: %%s\n", centerFrequency);
    status = hackrf_close(this->m_dev);
    HANDLE_ERROR("Error closing hackrf: %%s\n");
  }
}
コード例 #4
0
static void hackrf_check_status(int status, const char *message, const char *file, int line) {
    if (status != 0) {
        fprintf(stderr, "NRF HackRF fatal error: %s\n", message);
        if (device != NULL) {
            hackrf_close(device);
        }
        hackrf_exit();
        exit(EXIT_FAILURE);
    }
}
コード例 #5
0
ファイル: HackRFSource.cpp プロジェクト: f4exb/sdrdaemon
HackRFSource::~HackRFSource()
{
    if (m_dev) {
        hackrf_close(m_dev);
    }

    hackrf_error rc = (hackrf_error) hackrf_exit();
    std::cerr << "HackRFSource::~HackRFSource: HackRF library exit: " << rc << ": " << hackrf_error_name(rc) << std::endl;

    m_this = 0;
}
コード例 #6
0
ファイル: main.cpp プロジェクト: rgerganov/usdr
void close_hackrf()
{
    int result = hackrf_stop_rx(device);
    if (result != HACKRF_SUCCESS) {
        fprintf(stderr, "hackrf_stop_rx() failed: (%d)\n", result);
    }
    result = hackrf_close(device);
    if (result != HACKRF_SUCCESS) {
        fprintf(stderr, "hackrf_close() failed: (%d)\n", result);
    }
    hackrf_exit();
}
コード例 #7
0
ファイル: hackRFSource.cpp プロジェクト: wpats/scanner
void HackRFSource::handle_error(int status, const char * format, ...)
{
  if (status != 0) {
    char buffer[256];
    va_list args;
    va_start(args, format);
    vsprintf(buffer, format, args);
    fprintf(stderr, buffer, hackrf_error_name(static_cast<hackrf_error>(status)));
    hackrf_close(this->m_dev);
    exit(1);
  }
}
コード例 #8
0
ファイル: hackrf_tcp.c プロジェクト: stevecast2024/hackrf-1
static void sighandler(int signum)
{
	fprintf(stderr, "Signal caught, exiting!\n");
	if (!do_exit) {
		//rtlsdr_cancel_async(dev);
		hackrf_stop_rx(dev);
		hackrf_close(dev);
		sleep(1.2);
		hackrf_init();
		hackrf_open(&dev);
		do_exit = 1;
	}
}
コード例 #9
0
/* ======================================================================== */
static void mdlTerminate(SimStruct *S)
/* ======================================================================== */
{
	/* check if HackRF object has been created */
	if (ssGetPWorkValue(S, DEVICE))
	{
		struct hackrf_device *device = (struct hackrf_device *)ssGetPWorkValue(S, DEVICE);

		hackrf_stop_tx(device);
		hackrf_close(device);
		hackrf_exit();
	}


	/* release thread stuff */
	if (ssGetPWorkValue(S, MUTEX)) {
		pthread_mutex_t *mutex = (pthread_mutex_t *)ssGetPWorkValue(S, MUTEX);
		pthread_mutex_destroy(mutex);
		free(mutex);
		mutex = NULL;
	}
	if (ssGetPWorkValue(S, COND_VAR)) {
		pthread_cond_t* cond_var = (pthread_cond_t *)ssGetPWorkValue(S, COND_VAR);
		pthread_cond_destroy(cond_var);
		free(cond_var);
		cond_var = NULL;
	}
	/* destroy sample buffer struct */
	if (ssGetPWorkValue(S, SBUF))
	{
		SampleBuffer *sbuf = (SampleBuffer *)ssGetPWorkValue(S, SBUF);

		if (sbuf->underrun_before) {
			ssPrintf("\n");
		}

		if (sbuf->buf) {
			for (unsigned int i = 0; i < sbuf->num; ++i) {
				if (sbuf->buf[i])
					free(sbuf->buf[i]);
			}
			free(sbuf->buf);
		}
		free(sbuf);
	}


}
コード例 #10
0
ファイル: hackrf_tcp.c プロジェクト: stevecast2024/hackrf-1
BOOL WINAPI
sighandler(int signum)
{
	if (CTRL_C_EVENT == signum) {
		fprintf(stderr, "Signal caught, exiting!\n");
		//rtlsdr_cancel_async(dev);
		hackrf_stop_rx(dev);
		hackrf_close(dev);
		sleep(1.2);
		hackrf_init();
		hackrf_open(&dev);
		do_exit = 1;
		return TRUE;
	}
	return FALSE;
}
コード例 #11
0
ファイル: hackrfoutput.cpp プロジェクト: sigysmund/sdrangel
void HackRFOutput::closeDevice()
{
    if (m_deviceAPI->getSourceBuddies().size() == 0)
    {
        qDebug("HackRFOutput::closeDevice: closing device since Rx side is not open");

        if(m_dev != 0) // close HackRF
        {
            hackrf_close(m_dev);
            //hackrf_exit(); // TODO: this may not work if several HackRF Devices are running concurrently. It should be handled globally in the application
        }
    }

    m_sharedParams.m_dev = 0;
    m_dev = 0;
}
コード例 #12
0
ファイル: reader.c プロジェクト: YanLinAung/frequensea
int main(int argc, char **argv) {
    if (argc != 3) {
        usage();
        exit(1);
    }
    double freq_mhz = atof(argv[1]);
    FREQUENCY = freq_mhz * 1e6;
    int count = atoi(argv[2]);
    BUFFER_SIZE = NRF_SAMPLES_LENGTH * count;
    buffer = calloc(BUFFER_SIZE, 1);

    int status;
    hackrf_device *device;

    status = hackrf_init();
    CHECK_STATUS(status, "hackrf_init");

    status = hackrf_open(&device);
    CHECK_STATUS(status, "hackrf_open");

    status = hackrf_set_freq(device, FREQUENCY);
    CHECK_STATUS(status, "hackrf_set_freq");

    status = hackrf_set_sample_rate(device, SAMPLE_RATE);
    CHECK_STATUS(status, "hackrf_set_sample_rate");

    status = hackrf_set_amp_enable(device, 0);
    CHECK_STATUS(status, "hackrf_set_amp_enable");

    status = hackrf_set_lna_gain(device, 32);
    CHECK_STATUS(status, "hackrf_set_lna_gain");

    status = hackrf_set_vga_gain(device, 34);
    CHECK_STATUS(status, "hackrf_set_vga_gain");

    status = hackrf_start_rx(device, receive_sample_block, NULL);
    CHECK_STATUS(status, "hackrf_start_rx");

    while (buffer_pos < BUFFER_SIZE) {
        sleep(1);
    }

    hackrf_stop_rx(device);
    hackrf_close(device);
    hackrf_exit();
    return 0;
}
コード例 #13
0
ファイル: rfcap.c プロジェクト: YanLinAung/frequensea
int main(int argc, char **argv) {
    int status;

    if (argc != 3) {
        printf("Usage: rfcap FREQ N_SAMPLES\n");
        exit(EXIT_FAILURE);
    }

    current_freq = atof(argv[1]);
    n_samples = atoi(argv[2]);

    status = hackrf_init();
    HACKRF_CHECK_STATUS(status, "hackrf_init");

    status = hackrf_open(&device);
    HACKRF_CHECK_STATUS(status, "hackrf_open");

    status = hackrf_set_freq(device, current_freq * 1e6);
    HACKRF_CHECK_STATUS(status, "hackrf_set_freq");

    status = hackrf_set_sample_rate(device, 10e6);
    HACKRF_CHECK_STATUS(status, "hackrf_set_sample_rate");

    status = hackrf_set_amp_enable(device, 0);
    HACKRF_CHECK_STATUS(status, "hackrf_set_amp_enable");

    status = hackrf_set_lna_gain(device, 32);
    HACKRF_CHECK_STATUS(status, "hackrf_set_lna_gain");

    status = hackrf_set_vga_gain(device, 30);
    HACKRF_CHECK_STATUS(status, "hackrf_set_lna_gain");

    status = hackrf_start_rx(device, receive_sample_block, NULL);
    HACKRF_CHECK_STATUS(status, "hackrf_start_rx");

    while (receive_count < n_samples) {
        usleep(100);
    }

    hackrf_stop_rx(device);
    hackrf_close(device);
    hackrf_exit();
    return 0;
}
コード例 #14
0
ファイル: hackrf_transfer.c プロジェクト: TritonSailor/hackrf
int main(int argc, char** argv) {
	int opt;
	char path_file[PATH_FILE_MAX_LEN];
	char date_time[DATE_TIME_MAX_LEN];
	const char* path = NULL;
	int result;
	time_t rawtime;
	struct tm * timeinfo;
	long int file_pos;
	int exit_code = EXIT_SUCCESS;
	struct timeval t_end;
	float time_diff;
	unsigned int lna_gain=8, vga_gain=20, txvga_gain=0;
  
	while( (opt = getopt(argc, argv, "wr:t:f:a:s:n:b:l:i:x:")) != EOF )
	{
		result = HACKRF_SUCCESS;
		switch( opt ) 
		{
		case 'w':
			receive_wav = true;
			break;
		
		case 'r':
			receive = true;
			path = optarg;
			break;
		
		case 't':
			transmit = true;
			path = optarg;
			break;
		
		case 'f':
			freq = true;
			result = parse_u64(optarg, &freq_hz);
			break;

		case 'a':
			amp = true;
			result = parse_u32(optarg, &amp_enable);
			break;

		case 'l':
			result = parse_u32(optarg, &lna_gain);
			break;

		case 'i':
			result = parse_u32(optarg, &vga_gain);
			break;

		case 'x':
			result = parse_u32(optarg, &txvga_gain);
			break;

		case 's':
			sample_rate = true;
			result = parse_u32(optarg, &sample_rate_hz);
			break;

		case 'n':
			limit_num_samples = true;
			result = parse_u64(optarg, &samples_to_xfer);
			bytes_to_xfer = samples_to_xfer * 2ull;
			break;

		case 'b':
			baseband_filter_bw = true;
			result = parse_u32(optarg, &baseband_filter_bw_hz);
			break;

		default:
			printf("unknown argument '-%c %s'\n", opt, optarg);
			usage();
			return EXIT_FAILURE;
		}
		
		if( result != HACKRF_SUCCESS ) {
			printf("argument error: '-%c %s' %s (%d)\n", opt, optarg, hackrf_error_name(result), result);
			usage();
			return EXIT_FAILURE;
		}		
	}

	if (samples_to_xfer >= SAMPLES_TO_XFER_MAX) {
		printf("argument error: num_samples must be less than %llu/%lluMio\n",
				SAMPLES_TO_XFER_MAX, SAMPLES_TO_XFER_MAX/FREQ_ONE_MHZ);
		usage();
		return EXIT_FAILURE;
	}

	if( freq ) {
		if( (freq_hz >= FREQ_MAX_HZ) || (freq_hz < FREQ_MIN_HZ) )
		{
			printf("argument error: set_freq_hz shall be between [%llu, %llu[.\n", FREQ_MIN_HZ, FREQ_MAX_HZ);
			usage();
			return EXIT_FAILURE;
		}
	}else
	{
		/* Use default freq */
		freq_hz = DEFAULT_FREQ_HZ;
	}

	if( amp ) {
		if( amp_enable > 1 )
		{
			printf("argument error: set_amp shall be 0 or 1.\n");
			usage();
			return EXIT_FAILURE;
		}
	}

	if( sample_rate == false ) 
	{
		sample_rate_hz = DEFAULT_SAMPLE_RATE_HZ;
	}

	if( baseband_filter_bw )
	{
		/* Compute nearest freq for bw filter */
		baseband_filter_bw_hz = hackrf_compute_baseband_filter_bw(baseband_filter_bw_hz);
	}else
	{
		/* Compute default value depending on sample rate */
		baseband_filter_bw_hz = hackrf_compute_baseband_filter_bw_round_down_lt(sample_rate_hz);
	}

	if (baseband_filter_bw_hz > BASEBAND_FILTER_BW_MAX) {
		printf("argument error: baseband_filter_bw_hz must be less or equal to %u Hz/%.03f MHz\n",
				BASEBAND_FILTER_BW_MAX, (float)(BASEBAND_FILTER_BW_MAX/FREQ_ONE_MHZ));
		usage();
		return EXIT_FAILURE;
	}

	if (baseband_filter_bw_hz < BASEBAND_FILTER_BW_MIN) {
		printf("argument error: baseband_filter_bw_hz must be greater or equal to %u Hz/%.03f MHz\n",
				BASEBAND_FILTER_BW_MIN, (float)(BASEBAND_FILTER_BW_MIN/FREQ_ONE_MHZ));
		usage();
		return EXIT_FAILURE;
	}

	if( (transmit == false) && (receive == receive_wav) )
	{
		printf("receive -r and receive_wav -w options are mutually exclusive\n");
		usage();
		return EXIT_FAILURE;
	}
	
	if( receive_wav == false )
	{
		if( transmit == receive ) 
		{
			if( transmit == true ) 
			{
				printf("receive -r and transmit -t options are mutually exclusive\n");
			} else
			{
				printf("specify either transmit -t or receive -r or receive_wav -w option\n");
			}
			usage();
			return EXIT_FAILURE;
		}
	}
	
	if( receive ) {
		transceiver_mode = TRANSCEIVER_MODE_RX;
	}
	
	if( transmit ) {
		transceiver_mode = TRANSCEIVER_MODE_TX;
	}

	if( receive_wav ) 
	{
		time (&rawtime);
		timeinfo = localtime (&rawtime);
		transceiver_mode = TRANSCEIVER_MODE_RX;
		/* File format HackRF Year(2013), Month(11), Day(28), Hour Min Sec+Z, Freq kHz, IQ.wav */
		strftime(date_time, DATE_TIME_MAX_LEN, "%Y%m%d_%H%M%S", timeinfo);
		snprintf(path_file, PATH_FILE_MAX_LEN, "HackRF_%sZ_%ukHz_IQ.wav", date_time, (uint32_t)(freq_hz/(1000ull)) );
		path = path_file;
		printf("Receive wav file: %s\n", path);
	}	

	if( path == NULL ) {
		printf("specify a path to a file to transmit/receive\n");
		usage();
		return EXIT_FAILURE;
	}
	
	result = hackrf_init();
	if( result != HACKRF_SUCCESS ) {
		printf("hackrf_init() failed: %s (%d)\n", hackrf_error_name(result), result);
		usage();
		return EXIT_FAILURE;
	}
	
	result = hackrf_open(&device);
	if( result != HACKRF_SUCCESS ) {
		printf("hackrf_open() failed: %s (%d)\n", hackrf_error_name(result), result);
		usage();
		return EXIT_FAILURE;
	}
	
	if( transceiver_mode == TRANSCEIVER_MODE_RX ) 
	{
		fd = fopen(path, "wb");
	} else {
		fd = fopen(path, "rb");
	}
	
	if( fd == NULL ) {
		printf("Failed to open file: %s\n", path);
		return EXIT_FAILURE;
	}
	/* Change fd buffer to have bigger one to store or read data on/to HDD */
	result = setvbuf(fd , NULL , _IOFBF , FD_BUFFER_SIZE);
	if( result != 0 ) {
		printf("setvbuf() failed: %d\n", result);
		usage();
		return EXIT_FAILURE;
	}
	
	/* Write Wav header */
	if( receive_wav ) 
	{
		fwrite(&wave_file_hdr, 1, sizeof(t_wav_file_hdr), fd);
	}
	
#ifdef _MSC_VER
	SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
#else
	signal(SIGINT, &sigint_callback_handler);
	signal(SIGILL, &sigint_callback_handler);
	signal(SIGFPE, &sigint_callback_handler);
	signal(SIGSEGV, &sigint_callback_handler);
	signal(SIGTERM, &sigint_callback_handler);
	signal(SIGABRT, &sigint_callback_handler);
#endif
	printf("call hackrf_sample_rate_set(%u Hz/%.03f MHz)\n", sample_rate_hz,((float)sample_rate_hz/(float)FREQ_ONE_MHZ));
	result = hackrf_sample_rate_set(device, sample_rate_hz);
	if( result != HACKRF_SUCCESS ) {
		printf("hackrf_sample_rate_set() failed: %s (%d)\n", hackrf_error_name(result), result);
		usage();
		return EXIT_FAILURE;
	}

	printf("call hackrf_baseband_filter_bandwidth_set(%d Hz/%.03f MHz)\n",
			baseband_filter_bw_hz, ((float)baseband_filter_bw_hz/(float)FREQ_ONE_MHZ));
	result = hackrf_baseband_filter_bandwidth_set(device, baseband_filter_bw_hz);
	if( result != HACKRF_SUCCESS ) {
		printf("hackrf_baseband_filter_bandwidth_set() failed: %s (%d)\n", hackrf_error_name(result), result);
		usage();
		return EXIT_FAILURE;
	}

	if( transceiver_mode == TRANSCEIVER_MODE_RX ) {
		result = hackrf_set_vga_gain(device, vga_gain);
		result |= hackrf_set_lna_gain(device, lna_gain);
		result |= hackrf_start_rx(device, rx_callback, NULL);
	} else {
		result = hackrf_set_txvga_gain(device, txvga_gain);
		result |= hackrf_start_tx(device, tx_callback, NULL);
	}
	if( result != HACKRF_SUCCESS ) {
		printf("hackrf_start_?x() failed: %s (%d)\n", hackrf_error_name(result), result);
		usage();
		return EXIT_FAILURE;
	}

	printf("call hackrf_set_freq(%llu Hz/%.03f MHz)\n", freq_hz, ((float)freq_hz/(float)FREQ_ONE_MHZ) );
	result = hackrf_set_freq(device, freq_hz);
	if( result != HACKRF_SUCCESS ) {
		printf("hackrf_set_freq() failed: %s (%d)\n", hackrf_error_name(result), result);
		usage();
		return EXIT_FAILURE;
	}

	if( amp ) {
		printf("call hackrf_set_amp_enable(%u)\n", amp_enable);
		result = hackrf_set_amp_enable(device, (uint8_t)amp_enable);
		if( result != HACKRF_SUCCESS ) {
			printf("hackrf_set_amp_enable() failed: %s (%d)\n", hackrf_error_name(result), result);
			usage();
			return EXIT_FAILURE;
		}
	}
	
	if( limit_num_samples ) {
		printf("samples_to_xfer %llu/%lluMio\n", samples_to_xfer, (samples_to_xfer/FREQ_ONE_MHZ) );
	}
	
	gettimeofday(&t_start, NULL);
	gettimeofday(&time_start, NULL);

	printf("Stop with Ctrl-C\n");
	while( (hackrf_is_streaming(device) == HACKRF_TRUE) &&
			(do_exit == false) ) 
	{
		uint32_t byte_count_now;
		struct timeval time_now;
		float time_difference, rate;
		sleep(1);
		
		gettimeofday(&time_now, NULL);
		
		byte_count_now = byte_count;
		byte_count = 0;
		
		time_difference = TimevalDiff(&time_now, &time_start);
		rate = (float)byte_count_now / time_difference;
		printf("%4.1f MiB / %5.3f sec = %4.1f MiB/second\n",
				(byte_count_now / 1e6f), time_difference, (rate / 1e6f) );

		time_start = time_now;

		if (byte_count_now == 0) {
			exit_code = EXIT_FAILURE;
			printf("\nCouldn't transfer any bytes for one second.\n");
			break;
		}
	}
	
	result = hackrf_is_streaming(device);	
	if (do_exit)
	{
		printf("\nUser cancel, exiting...\n");
	} else {
		printf("\nExiting... hackrf_is_streaming() result: %s (%d)\n", hackrf_error_name(result), result);
	}
	
	gettimeofday(&t_end, NULL);
	time_diff = TimevalDiff(&t_end, &t_start);
	printf("Total time: %5.5f s\n", time_diff);
	
	if(device != NULL)
	{
		if( receive ) 
		{
			result = hackrf_stop_rx(device);
			if( result != HACKRF_SUCCESS ) {
				printf("hackrf_stop_rx() failed: %s (%d)\n", hackrf_error_name(result), result);
			}else {
				printf("hackrf_stop_rx() done\n");
			}
		}
	
		if( transmit ) 
		{
			result = hackrf_stop_tx(device);
			if( result != HACKRF_SUCCESS ) {
				printf("hackrf_stop_tx() failed: %s (%d)\n", hackrf_error_name(result), result);
			}else {
				printf("hackrf_stop_tx() done\n");
			}
		}
		
		result = hackrf_close(device);
		if( result != HACKRF_SUCCESS ) 
		{
			printf("hackrf_close() failed: %s (%d)\n", hackrf_error_name(result), result);
		}else {
			printf("hackrf_close() done\n");
		}
		
		hackrf_exit();
		printf("hackrf_exit() done\n");
	}
		
	if(fd != NULL)
	{
		if( receive_wav ) 
		{
			/* Get size of file */
			file_pos = ftell(fd);
			/* Update Wav Header */
			wave_file_hdr.hdr.size = file_pos+8;
			wave_file_hdr.fmt_chunk.dwSamplesPerSec = sample_rate_hz;
			wave_file_hdr.fmt_chunk.dwAvgBytesPerSec = wave_file_hdr.fmt_chunk.dwSamplesPerSec*2;
			wave_file_hdr.data_chunk.chunkSize = file_pos - sizeof(t_wav_file_hdr);
			/* Overwrite header with updated data */
			rewind(fd);
			fwrite(&wave_file_hdr, 1, sizeof(t_wav_file_hdr), fd);
		}	
		fclose(fd);
		fd = NULL;
		printf("fclose(fd) done\n");
	}
	printf("exit\n");
	return exit_code;
}
コード例 #15
0
/* Entry point to C/C++ */
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
	int result =HACKRF_SUCCESS,i;
	struct hackrf_device *_device [10];
	hackrf_device_list_t *list;
	uint8_t board_id = BOARD_ID_INVALID;
	char version[255 + 1];
	read_partid_serialno_t read_partid_serialno;
	
	result = hackrf_init();
	if (result != HACKRF_SUCCESS) {
		mexPrintf("hackrf_init() failed: %s (%d)\n",hackrf_error_name((hackrf_error)result), result);
	}
	list = hackrf_device_list();
	
	if (list->devicecount < 1 ) {
		mexPrintf("No HackRF boards found.\n");
	}	
		
	for (i = 0; i < list->devicecount; i++){
	mexPrintf("Found HackRF board %d:\n", i);
	if (list->serial_numbers[i])
			mexPrintf("USB descriptor string: %s\n", list->serial_numbers[i]);
			
		result = hackrf_device_list_open(list, i, &_device [i]);	
			if (result != HACKRF_SUCCESS) {
			mexPrintf("hackrf_open() failed: %s (%d)\n",hackrf_error_name((hackrf_error)result), result);
		}
	
		result = hackrf_board_id_read(_device[i], &board_id);
		if (result != HACKRF_SUCCESS) {
			mexPrintf("hackrf_board_id_read() failed: %s (%d)\n",hackrf_error_name((hackrf_error)result), result);
		}
		mexPrintf("Board ID Number: %d (%s)\n", board_id,hackrf_board_id_name((hackrf_board_id)board_id));
		
		result = hackrf_version_string_read(_device[i], &version[0], 255);
		if (result != HACKRF_SUCCESS) {
			mexPrintf("hackrf_version_string_read() failed: %s (%d)\n",hackrf_error_name((hackrf_error)result), result);

		}
		printf("Firmware Version: %s\n", version);

		result = hackrf_board_partid_serialno_read(_device[i], &read_partid_serialno);	
		if (result != HACKRF_SUCCESS) {
			mexPrintf( "hackrf_board_partid_serialno_read() failed: %s (%d)\n",hackrf_error_name((hackrf_error)result), result);
		}
		printf("Part ID Number: 0x%08x 0x%08x\n", 
					read_partid_serialno.part_id[0],
					read_partid_serialno.part_id[1]);
		printf("Serial Number: 0x%08x 0x%08x 0x%08x 0x%08x\n", 
					read_partid_serialno.serial_no[0],
					read_partid_serialno.serial_no[1],
					read_partid_serialno.serial_no[2],
					read_partid_serialno.serial_no[3]);
		
		result = hackrf_close(_device[i]);
		if (result != HACKRF_SUCCESS) {
			mexPrintf("hackrf_close() failed: %s (%d)\n",hackrf_error_name((hackrf_error)result), result);
		}
		
	
	}
	
	hackrf_device_list_free(list);
	hackrf_exit();
	
		
}
コード例 #16
0
ファイル: hackrf_sweep.c プロジェクト: BietteMaxime/hackrf
int main(int argc, char** argv) {
	int opt, i, result = 0;
	const char* path = NULL;
	const char* serial_number = NULL;
	int exit_code = EXIT_SUCCESS;
	struct timeval time_now;
	float time_diff;
	float sweep_rate;
	unsigned int lna_gain=16, vga_gain=20;
	uint32_t freq_min = 0;
	uint32_t freq_max = 6000;
	uint32_t requested_fft_bin_width;


	while( (opt = getopt(argc, argv, "a:f:p:l:g:d:n:N:w:1BIr:h?")) != EOF ) {
		result = HACKRF_SUCCESS;
		switch( opt ) 
		{
		case 'd':
			serial_number = optarg;
			break;

		case 'a':
			amp = true;
			result = parse_u32(optarg, &amp_enable);
			break;

		case 'f':
			result = parse_u32_range(optarg, &freq_min, &freq_max);
			if(freq_min >= freq_max) {
				fprintf(stderr,
						"argument error: freq_max must be greater than freq_min.\n");
				usage();
				return EXIT_FAILURE;
			}
			if(FREQ_MAX_MHZ <freq_max) {
				fprintf(stderr,
						"argument error: freq_max may not be higher than %u.\n",
						FREQ_MAX_MHZ);
				usage();
				return EXIT_FAILURE;
			}
			if(MAX_SWEEP_RANGES <= num_ranges) {
				fprintf(stderr,
						"argument error: specify a maximum of %u frequency ranges.\n",
						MAX_SWEEP_RANGES);
				usage();
				return EXIT_FAILURE;
			}
			frequencies[2*num_ranges] = (uint16_t)freq_min;
			frequencies[2*num_ranges+1] = (uint16_t)freq_max;
			num_ranges++;
			break;

		case 'p':
			antenna = true;
			result = parse_u32(optarg, &antenna_enable);
			break;

		case 'l':
			result = parse_u32(optarg, &lna_gain);
			break;

		case 'g':
			result = parse_u32(optarg, &vga_gain);
			break;

		case 'n':
			result = parse_u32(optarg, &num_samples);
			break;

		case 'N':
			finite_mode = true;
			result = parse_u32(optarg, &num_sweeps);
			break;

		case 'w':
			result = parse_u32(optarg, &requested_fft_bin_width);
			fftSize = DEFAULT_SAMPLE_RATE_HZ / requested_fft_bin_width;
			break;

		case '1':
			one_shot = true;
			break;

		case 'B':
			binary_output = true;
			break;

		case 'I':
			ifft_output = true;
			break;

		case 'r':
			path = optarg;
			break;

		case 'h':
		case '?':
			usage();
			return EXIT_SUCCESS;

		default:
			fprintf(stderr, "unknown argument '-%c %s'\n", opt, optarg);
			usage();
			return EXIT_FAILURE;
		}
		
		if( result != HACKRF_SUCCESS ) {
			fprintf(stderr, "argument error: '-%c %s' %s (%d)\n", opt, optarg, hackrf_error_name(result), result);
			usage();
			return EXIT_FAILURE;
		}		
	}

	if (lna_gain % 8)
		fprintf(stderr, "warning: lna_gain (-l) must be a multiple of 8\n");

	if (vga_gain % 2)
		fprintf(stderr, "warning: vga_gain (-g) must be a multiple of 2\n");

	if (num_samples % SAMPLES_PER_BLOCK) {
		fprintf(stderr, "warning: num_samples (-n) must be a multiple of 8192\n");
		return EXIT_FAILURE;
	}

	if (num_samples < SAMPLES_PER_BLOCK) {
		fprintf(stderr, "warning: num_samples (-n) must be at least 8192\n");
		return EXIT_FAILURE;
	}

	if( amp ) {
		if( amp_enable > 1 ) {
			fprintf(stderr, "argument error: amp_enable shall be 0 or 1.\n");
			usage();
			return EXIT_FAILURE;
		}
	}

	if (antenna) {
		if (antenna_enable > 1) {
			fprintf(stderr, "argument error: antenna_enable shall be 0 or 1.\n");
			usage();
			return EXIT_FAILURE;
		}
	}

	if (0 == num_ranges) {
		frequencies[0] = (uint16_t)freq_min;
		frequencies[1] = (uint16_t)freq_max;
		num_ranges++;
	}

	if(binary_output && ifft_output) {
		fprintf(stderr, "argument error: binary output (-B) and IFFT output (-I) are mutually exclusive.\n");
		return EXIT_FAILURE;
	}

	if(ifft_output && (1 < num_ranges)) {
		fprintf(stderr, "argument error: only one frequency range is supported in IFFT output (-I) mode.\n");
		return EXIT_FAILURE;
	}

	if(4 > fftSize) {
		fprintf(stderr,
				"argument error: FFT bin width (-w) must be no more than one quarter the sample rate\n");
		return EXIT_FAILURE;
	}

	if(8184 < fftSize) {
		fprintf(stderr,
				"argument error: FFT bin width (-w) too small, resulted in more than 8184 FFT bins\n");
		return EXIT_FAILURE;
	}

	/* In interleaved mode, the FFT bin selection works best if the total
	 * number of FFT bins is equal to an odd multiple of four.
	 * (e.g. 4, 12, 20, 28, 36, . . .)
	 */
	while((fftSize + 4) % 8) {
		fftSize++;
	}

	fft_bin_width = (double)DEFAULT_SAMPLE_RATE_HZ / fftSize;
	fftwIn = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * fftSize);
	fftwOut = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * fftSize);
	fftwPlan = fftwf_plan_dft_1d(fftSize, fftwIn, fftwOut, FFTW_FORWARD, FFTW_MEASURE);
	pwr = (float*)fftwf_malloc(sizeof(float) * fftSize);
	window = (float*)fftwf_malloc(sizeof(float) * fftSize);
	for (i = 0; i < fftSize; i++) {
		window[i] = (float) (0.5f * (1.0f - cos(2 * M_PI * i / (fftSize - 1))));
	}

	result = hackrf_init();
	if( result != HACKRF_SUCCESS ) {
		fprintf(stderr, "hackrf_init() failed: %s (%d)\n", hackrf_error_name(result), result);
		usage();
		return EXIT_FAILURE;
	}
	
	result = hackrf_open_by_serial(serial_number, &device);
	if( result != HACKRF_SUCCESS ) {
		fprintf(stderr, "hackrf_open() failed: %s (%d)\n", hackrf_error_name(result), result);
		usage();
		return EXIT_FAILURE;
	}

	if((NULL == path) || (strcmp(path, "-") == 0)) {
		fd = stdout;
	} else {
		fd = fopen(path, "wb");
	}

	if(NULL == fd) {
		fprintf(stderr, "Failed to open file: %s\n", path);
		return EXIT_FAILURE;
	}
	/* Change fd buffer to have bigger one to store or read data on/to HDD */
	result = setvbuf(fd , NULL , _IOFBF , FD_BUFFER_SIZE);
	if( result != 0 ) {
		fprintf(stderr, "setvbuf() failed: %d\n", result);
		usage();
		return EXIT_FAILURE;
	}

#ifdef _MSC_VER
	SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
#else
	signal(SIGINT, &sigint_callback_handler);
	signal(SIGILL, &sigint_callback_handler);
	signal(SIGFPE, &sigint_callback_handler);
	signal(SIGSEGV, &sigint_callback_handler);
	signal(SIGTERM, &sigint_callback_handler);
	signal(SIGABRT, &sigint_callback_handler);
#endif
	fprintf(stderr, "call hackrf_sample_rate_set(%.03f MHz)\n",
		   ((float)DEFAULT_SAMPLE_RATE_HZ/(float)FREQ_ONE_MHZ));
	result = hackrf_set_sample_rate_manual(device, DEFAULT_SAMPLE_RATE_HZ, 1);
	if( result != HACKRF_SUCCESS ) {
		fprintf(stderr, "hackrf_sample_rate_set() failed: %s (%d)\n",
			   hackrf_error_name(result), result);
		usage();
		return EXIT_FAILURE;
	}

	fprintf(stderr, "call hackrf_baseband_filter_bandwidth_set(%.03f MHz)\n",
			((float)DEFAULT_BASEBAND_FILTER_BANDWIDTH/(float)FREQ_ONE_MHZ));
	result = hackrf_set_baseband_filter_bandwidth(device, DEFAULT_BASEBAND_FILTER_BANDWIDTH);
	if( result != HACKRF_SUCCESS ) {
		fprintf(stderr, "hackrf_baseband_filter_bandwidth_set() failed: %s (%d)\n",
			   hackrf_error_name(result), result);
		usage();
		return EXIT_FAILURE;
	}

	result = hackrf_set_vga_gain(device, vga_gain);
	result |= hackrf_set_lna_gain(device, lna_gain);

	/*
	 * For each range, plan a whole number of tuning steps of a certain
	 * bandwidth. Increase high end of range if necessary to accommodate a
	 * whole number of steps, minimum 1.
	 */
	for(i = 0; i < num_ranges; i++) {
		step_count = 1 + (frequencies[2*i+1] - frequencies[2*i] - 1)
				/ TUNE_STEP;
		frequencies[2*i+1] = (uint16_t) (frequencies[2*i] + step_count * TUNE_STEP);
		fprintf(stderr, "Sweeping from %u MHz to %u MHz\n",
				frequencies[2*i], frequencies[2*i+1]);
	}

	if(ifft_output) {
		ifftwIn = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * fftSize * step_count);
		ifftwOut = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * fftSize * step_count);
		ifftwPlan = fftwf_plan_dft_1d(fftSize * step_count, ifftwIn, ifftwOut, FFTW_BACKWARD, FFTW_MEASURE);
	}

	result |= hackrf_start_rx(device, rx_callback, NULL);
	if (result != HACKRF_SUCCESS) {
		fprintf(stderr, "hackrf_start_rx() failed: %s (%d)\n", hackrf_error_name(result), result);
		usage();
		return EXIT_FAILURE;
	}

	result = hackrf_init_sweep(device, frequencies, num_ranges, num_samples * 2,
			TUNE_STEP * FREQ_ONE_MHZ, OFFSET, INTERLEAVED);
	if( result != HACKRF_SUCCESS ) {
		fprintf(stderr, "hackrf_init_sweep() failed: %s (%d)\n",
			   hackrf_error_name(result), result);
		return EXIT_FAILURE;
	}

	if (amp) {
		fprintf(stderr, "call hackrf_set_amp_enable(%u)\n", amp_enable);
		result = hackrf_set_amp_enable(device, (uint8_t)amp_enable);
		if (result != HACKRF_SUCCESS) {
			fprintf(stderr, "hackrf_set_amp_enable() failed: %s (%d)\n",
				   hackrf_error_name(result), result);
			usage();
			return EXIT_FAILURE;
		}
	}

	if (antenna) {
		fprintf(stderr, "call hackrf_set_antenna_enable(%u)\n", antenna_enable);
		result = hackrf_set_antenna_enable(device, (uint8_t)antenna_enable);
		if (result != HACKRF_SUCCESS) {
			fprintf(stderr, "hackrf_set_antenna_enable() failed: %s (%d)\n",
				   hackrf_error_name(result), result);
			usage();
			return EXIT_FAILURE;
		}
	}

	gettimeofday(&t_start, NULL);

	fprintf(stderr, "Stop with Ctrl-C\n");
	while((hackrf_is_streaming(device) == HACKRF_TRUE) && (do_exit == false)) {
		float time_difference;
		m_sleep(50);

		gettimeofday(&time_now, NULL);
		
		time_difference = TimevalDiff(&time_now, &t_start);
		sweep_rate = (float)sweep_count / time_difference;
		fprintf(stderr, "%" PRIu64 " total sweeps completed, %.2f sweeps/second\n",
				sweep_count, sweep_rate);

		if (byte_count == 0) {
			exit_code = EXIT_FAILURE;
			fprintf(stderr, "\nCouldn't transfer any data for one second.\n");
			break;
		}
		byte_count = 0;
	}

	result = hackrf_is_streaming(device);	
	if (do_exit) {
		fprintf(stderr, "\nExiting...\n");
	} else {
		fprintf(stderr, "\nExiting... hackrf_is_streaming() result: %s (%d)\n",
			   hackrf_error_name(result), result);
	}

	gettimeofday(&time_now, NULL);
	time_diff = TimevalDiff(&time_now, &t_start);
	fprintf(stderr, "Total sweeps: %" PRIu64 " in %.5f seconds (%.2f sweeps/second)\n",
			sweep_count, time_diff, sweep_rate);

	if(device != NULL) {
		result = hackrf_stop_rx(device);
		if(result != HACKRF_SUCCESS) {
			fprintf(stderr, "hackrf_stop_rx() failed: %s (%d)\n",
				   hackrf_error_name(result), result);
		} else {
			fprintf(stderr, "hackrf_stop_rx() done\n");
		}

		result = hackrf_close(device);
		if(result != HACKRF_SUCCESS) {
			fprintf(stderr, "hackrf_close() failed: %s (%d)\n",
				   hackrf_error_name(result), result);
		} else {
			fprintf(stderr, "hackrf_close() done\n");
		}

		hackrf_exit();
		fprintf(stderr, "hackrf_exit() done\n");
	}

	if(fd != NULL) {
		fclose(fd);
		fd = NULL;
		fprintf(stderr, "fclose(fd) done\n");
	}
	fftwf_free(fftwIn);
	fftwf_free(fftwOut);
	fftwf_free(pwr);
	fftwf_free(window);
	fftwf_free(ifftwIn);
	fftwf_free(ifftwOut);
	fprintf(stderr, "exit\n");
	return exit_code;
}
コード例 #17
0
ファイル: hackrf_beep.c プロジェクト: rufty/hackrf_beep
int
main ( int argc, char** argv )
  {
  /*
   * Setup.
   */
  // How did it do?
  int result ;
  // Signal and carrier angle.
  double sa, ca ;
  // Sample offsets.
  co = 0 ; mo = 0 ; so = 0 ;
  // Sample number.
  sn = 0L ;
  // Mark or space?
  ms = false ;
  // Catch signals that we want to handle gracefully.
  signal ( SIGINT, &sigint_callback_handler ) ;
  signal ( SIGILL, &sigint_callback_handler ) ;
  signal ( SIGFPE, &sigint_callback_handler ) ;
  signal ( SIGSEGV, &sigint_callback_handler ) ;
  signal ( SIGTERM, &sigint_callback_handler ) ;
  signal ( SIGABRT, &sigint_callback_handler ) ;
  // This takes a bit.
  fprintf ( stderr, "Precalculating lookup tables...\n" ) ;
  /*
   * Precalc waveforms.
   */
  // Lookup for 1200Hz.
  for ( int s = 0 ; s < 6666; s++ )
    {
    sa = s * tau / 6666.0 ;
    for ( int c = 0; c < 10; c++ )
      {
      ca = c * tau / 10.0 ;
      mi[s][c] = ( int8_t ) ( 127.0 * sin ( ca - dm * cos ( sa ) ) ) ;
      mq[s][c] = ( int8_t ) ( 127.0 * cos ( ca - dm * cos ( sa ) ) ) ;
      }
    }
  // Lookup for 2200Hz.
  for ( int s = 0 ; s < 3636; s++ )
    {
    sa = s * tau / 3636.0 ;
    for ( int c = 0; c < 10; c++ )
      {
      ca = c * tau / 10.0 ;
      si[s][c] = ( int8_t ) ( 127.0 * sin ( ca - dm * cos ( sa ) ) ) ;
      sq[s][c] = ( int8_t ) ( 127.0 * cos ( ca - dm * cos ( sa ) ) ) ;
      }
    }
  /*
   * Setup the HackRF for transmitting at full power, 8M samples/s, 144MHz
   */
  // Ok.
  fprintf ( stderr, "Setting up the HackRF...\n" ) ;
  // Initialize the HackRF.
  result = hackrf_init() ;
  if ( result != HACKRF_SUCCESS )
    {
    fprintf ( stderr, "hackrf_init() failed: %s (%d)\n", hackrf_error_name ( result ), result ) ;
    return EXIT_FAILURE ;
    }
  // Open the HackRF.
  result = hackrf_open ( &device ) ;
  if ( result != HACKRF_SUCCESS )
    {
    fprintf ( stderr, "hackrf_open() failed: %s (%d)\n", hackrf_error_name ( result ), result ) ;
    return EXIT_FAILURE ;
    }
  // Set the sample rate.
  result = hackrf_set_sample_rate_manual ( device, sr, 1 ) ;
  if ( result != HACKRF_SUCCESS )
    {
    fprintf ( stderr, "hackrf_sample_rate_set() failed: %s (%d)\n", hackrf_error_name ( result ), result ) ;
    return EXIT_FAILURE ;
    }
  // Set the filter bandwith to default.
  result = hackrf_set_baseband_filter_bandwidth ( device, hackrf_compute_baseband_filter_bw_round_down_lt ( sr ) ) ;
  if ( result != HACKRF_SUCCESS )
    {
    fprintf ( stderr, "hackrf_baseband_filter_bandwidth_set() failed: %s (%d)\n", hackrf_error_name ( result ), result ) ;
    return EXIT_FAILURE ;
    }
  // Set the gain.
  result = hackrf_set_txvga_gain ( device, gain ) ;
  result |= hackrf_start_tx ( device, tx_callback, NULL ) ;
  if ( result != HACKRF_SUCCESS )
    {
    fprintf ( stderr, "hackrf_start_tx() failed: %s (%d)\n", hackrf_error_name ( result ), result ) ;
    return EXIT_FAILURE ;
    }
  // Set the transmit frequency.
  result = hackrf_set_freq ( device, tf ) ;
  if ( result != HACKRF_SUCCESS )
    {
    fprintf ( stderr, "hackrf_set_freq() failed: %s (%d)\n", hackrf_error_name ( result ), result ) ;
    return EXIT_FAILURE ;
    }
  // Turn on the amp.
  result = hackrf_set_amp_enable ( device, ( uint8_t ) 1 ) ;
  if ( result != HACKRF_SUCCESS )
    {
    fprintf ( stderr, "hackrf_set_amp_enable() failed: %s (%d)\n", hackrf_error_name ( result ), result ) ;
    return EXIT_FAILURE ;
    }
  /*
   * Transmitting.
   */
  // Ready?
  fprintf ( stderr, "Transmitting, stop with Ctrl-C\n" ) ;
  // Spin until done or killed.
  while ( ( hackrf_is_streaming ( device ) == HACKRF_TRUE ) && ( do_exit == false ) ) sleep ( 1 ) ;
  /*
   * Clean up and shut down.
   */
  // What happened?
  result = hackrf_is_streaming ( device ) ;
  if ( do_exit )
    {
    printf ( "\nUser cancel, exiting...\n" ) ;
    }
  else
    {
    fprintf ( stderr, "\nExiting... hackrf_is_streaming() result: %s (%d)\n", hackrf_error_name ( result ), result ) ;
    }
  // Shut down the HackRF.
  if ( device != NULL )
    {
    result = hackrf_stop_tx ( device ) ;
    if ( result != HACKRF_SUCCESS )
      {
      fprintf ( stderr, "hackrf_stop_tx() failed: %s (%d)\n", hackrf_error_name ( result ), result ) ;
      }
    result = hackrf_close ( device ) ;
    if ( result != HACKRF_SUCCESS )
      {
      fprintf ( stderr, "hackrf_close() failed: %s (%d)\n", hackrf_error_name ( result ), result ) ;
      }
    hackrf_exit() ;
    }
  // That's all, folks!!!
  return EXIT_SUCCESS ;
  }
コード例 #18
0
static void teardown_hackrf() {
    hackrf_stop_rx(device);
    hackrf_close(device);
    hackrf_exit();
}
コード例 #19
0
ファイル: hackrf_spiflash.c プロジェクト: hlss2000/hackrf
int main(int argc, char** argv)
{
    int opt;
    uint32_t address = 0;
    uint32_t length = MAX_LENGTH;
    uint32_t tmp_length;
    uint16_t xfer_len = 0;
    const char* path = NULL;
    const char* serial_number = NULL;
    hackrf_device* device = NULL;
    int result = HACKRF_SUCCESS;
    int option_index = 0;
    static uint8_t data[MAX_LENGTH];
    uint8_t* pdata = &data[0];
    FILE* fd = NULL;
    bool read = false;
    bool write = false;
    bool verbose = false;

    while ((opt = getopt_long(argc, argv, "a:l:r:w:d:v", long_options,
                              &option_index)) != EOF) {
        switch (opt) {
        case 'a':
            result = parse_u32(optarg, &address);
            break;

        case 'l':
            result = parse_u32(optarg, &length);
            break;

        case 'r':
            read = true;
            path = optarg;
            break;

        case 'w':
            write = true;
            path = optarg;
            break;

        case 'd':
            serial_number = optarg;
            break;

        case 'v':
            verbose = true;
            break;

        default:
            fprintf(stderr, "opt error: %d\n", opt);
            usage();
            return EXIT_FAILURE;
        }

        if (result != HACKRF_SUCCESS) {
            fprintf(stderr, "argument error: %s (%d)\n",
                    hackrf_error_name(result), result);
            usage();
            return EXIT_FAILURE;
        }
    }

    if (write == read) {
        if (write == true) {
            fprintf(stderr, "Read and write options are mutually exclusive.\n");
        } else {
            fprintf(stderr, "Specify either read or write option.\n");
        }
        usage();
        return EXIT_FAILURE;
    }

    if (path == NULL) {
        fprintf(stderr, "Specify a path to a file.\n");
        usage();
        return EXIT_FAILURE;
    }

    if( write )
    {
        fd = fopen(path, "rb");
        if(fd == NULL)
        {
            printf("Error to open file %s\n", path);
            return EXIT_FAILURE;
        }
        /* Get size of the file  */
        fseek(fd, 0, SEEK_END); /* Not really portable but work on major OS Linux/Win32 */
        length = ftell(fd);
        /* Move to start */
        rewind(fd);
        printf("File size %d bytes.\n", length);
    }

    if (length == 0) {
        fprintf(stderr, "Requested transfer of zero bytes.\n");
        if(fd != NULL)
            fclose(fd);
        usage();
        return EXIT_FAILURE;
    }

    if ((length > MAX_LENGTH) || (address > MAX_LENGTH)
            || ((address + length) > MAX_LENGTH)) {
        fprintf(stderr, "Request exceeds size of flash memory.\n");
        if(fd != NULL)
            fclose(fd);
        usage();
        return EXIT_FAILURE;
    }

    if (read) {
        fd = fopen(path, "wb");
        if(fd == NULL)
        {
            printf("Error to open file %s\n", path);
            return EXIT_FAILURE;
        }
    }

    if (fd == NULL) {
        fprintf(stderr, "Failed to open file: %s\n", path);
        return EXIT_FAILURE;
    }

    result = hackrf_init();
    if (result != HACKRF_SUCCESS) {
        fprintf(stderr, "hackrf_init() failed: %s (%d)\n",
                hackrf_error_name(result), result);
        return EXIT_FAILURE;
    }

    result = hackrf_open_by_serial(serial_number, &device);
    if (result != HACKRF_SUCCESS) {
        fprintf(stderr, "hackrf_open() failed: %s (%d)\n",
                hackrf_error_name(result), result);
        return EXIT_FAILURE;
    }

    if (read)
    {
        ssize_t bytes_written;
        tmp_length = length;
        while (tmp_length)
        {
            xfer_len = (tmp_length > 256) ? 256 : tmp_length;
            if( verbose ) printf("Reading %d bytes from 0x%06x.\n", xfer_len, address);
            result = hackrf_spiflash_read(device, address, xfer_len, pdata);
            if (result != HACKRF_SUCCESS) {
                fprintf(stderr, "hackrf_spiflash_read() failed: %s (%d)\n",
                        hackrf_error_name(result), result);
                fclose(fd);
                fd = NULL;
                return EXIT_FAILURE;
            }
            address += xfer_len;
            pdata += xfer_len;
            tmp_length -= xfer_len;
        }
        bytes_written = fwrite(data, 1, length, fd);
        if (bytes_written != length) {
            fprintf(stderr, "Failed write to file (wrote %d bytes).\n",
                    (int)bytes_written);
            fclose(fd);
            fd = NULL;
            return EXIT_FAILURE;
        }
    } else {
        ssize_t bytes_read = fread(data, 1, length, fd);
        if (bytes_read != length) {
            fprintf(stderr, "Failed read file (read %d bytes).\n",
                    (int)bytes_read);
            fclose(fd);
            fd = NULL;
            return EXIT_FAILURE;
        }
        printf("Erasing SPI flash.\n");
        result = hackrf_spiflash_erase(device);
        if (result != HACKRF_SUCCESS) {
            fprintf(stderr, "hackrf_spiflash_erase() failed: %s (%d)\n",
                    hackrf_error_name(result), result);
            fclose(fd);
            fd = NULL;
            return EXIT_FAILURE;
        }
        if( !verbose ) printf("Writing %d bytes at 0x%06x.\n", length, address);
        while (length) {
            xfer_len = (length > 256) ? 256 : length;
            if( verbose ) printf("Writing %d bytes at 0x%06x.\n", xfer_len, address);
            result = hackrf_spiflash_write(device, address, xfer_len, pdata);
            if (result != HACKRF_SUCCESS) {
                fprintf(stderr, "hackrf_spiflash_write() failed: %s (%d)\n",
                        hackrf_error_name(result), result);
                fclose(fd);
                fd = NULL;
                return EXIT_FAILURE;
            }
            address += xfer_len;
            pdata += xfer_len;
            length -= xfer_len;
        }
    }

    result = hackrf_close(device);
    if (result != HACKRF_SUCCESS) {
        fprintf(stderr, "hackrf_close() failed: %s (%d)\n",
                hackrf_error_name(result), result);
        fclose(fd);
        fd = NULL;
        return EXIT_FAILURE;
    }

    hackrf_exit();

    if (fd != NULL) {
        fclose(fd);
    }

    return EXIT_SUCCESS;
}
コード例 #20
0
ファイル: hackrf_cpldjtag.c プロジェクト: TritonSailor/hackrf
int main(int argc, char** argv)
{
	int opt;
	uint32_t length = 0;
	uint32_t total_length = 0;
	const char* path = NULL;
	hackrf_device* device = NULL;
	int result = HACKRF_SUCCESS;
	int option_index = 0;
	FILE* fd = NULL;
	ssize_t bytes_read;
	uint16_t xfer_len = 0;	
	uint8_t* pdata = &data[0];	

	while ((opt = getopt_long(argc, argv, "x:", long_options,
			&option_index)) != EOF) {
		switch (opt) {
		case 'x':
			path = optarg;
			break;

		default:
			usage();
			return EXIT_FAILURE;
		}

		if (result != HACKRF_SUCCESS) {
			fprintf(stderr, "argument error: %s (%d)\n",
					hackrf_error_name(result), result);
			usage();
			return EXIT_FAILURE;
		}
	}

	if (path == NULL) {
		fprintf(stderr, "Specify a path to a file.\n");
		usage();
		return EXIT_FAILURE;
	}

	fd = fopen(path, "rb");
	if (fd == NULL)
	{
		fprintf(stderr, "Failed to open file: %s\n", path);
		return EXIT_FAILURE;
	}	
	/* Get size of the file  */
	fseek(fd, 0, SEEK_END); /* Not really portable but work on major OS Linux/Win32 */
	length = ftell(fd);
	/* Move to start */
	rewind(fd);
	printf("File size %d bytes.\n", length);	

	if (length > MAX_XSVF_LENGTH) {
		fprintf(stderr, "XSVF file too large.\n");
		usage();
		return EXIT_FAILURE;
	}
	
	total_length = length;
	bytes_read = fread(data, 1, total_length, fd);
	if (bytes_read != total_length)
	{
		fprintf(stderr, "Failed to read all bytes (read %d bytes instead of %d bytes).\n",
				(int)bytes_read, total_length);
		fclose(fd);
		fd = NULL;
		return EXIT_FAILURE;
	}

	result = hackrf_init();
	if (result != HACKRF_SUCCESS) {
		fprintf(stderr, "hackrf_init() failed: %s (%d)\n",
				hackrf_error_name(result), result);
		return EXIT_FAILURE;
	}

	result = hackrf_open(&device);
	if (result != HACKRF_SUCCESS) {
		fprintf(stderr, "hackrf_open() failed: %s (%d)\n",
				hackrf_error_name(result), result);
		return EXIT_FAILURE;
	}

	printf("LED1/2/3 blinking means CPLD program success.\nLED3/RED steady means error.\n");
	printf("Wait message 'Write finished' or in case of LED3/RED steady, Power OFF/Disconnect the Jawbreaker.\n");
	while( length )
	{
		xfer_len = (length > PACKET_LEN) ? PACKET_LEN : length;
		result = hackrf_cpld_write(device, xfer_len, pdata, total_length);
		if (result != HACKRF_SUCCESS)
		{
			fprintf(stderr, "hackrf_cpld_write() failed: %s (%d)\n",
					hackrf_error_name(result), result);
			fclose(fd);
			fd = NULL;
			return EXIT_FAILURE;
		}
		pdata += xfer_len;
		length -= xfer_len;
		printf("hackrf_cpld_write() Writing %d bytes, remaining %d bytes.\n",
			xfer_len, length);		
	}
	printf("Write finished.\n");
	printf("Please Power OFF/Disconnect the Jawbreaker.\n");
	fflush(stdout);
		
	result = hackrf_close(device);
	if( result != HACKRF_SUCCESS )
	{
		fprintf(stderr, "hackrf_close() failed: %s (%d)\n",
				hackrf_error_name(result), result);
		fclose(fd);
		fd = NULL;
		return EXIT_FAILURE;
	}

	hackrf_exit();

	if (fd != NULL) {
		fclose(fd);
	}

	return EXIT_SUCCESS;
}
コード例 #21
0
ファイル: dab2eti.cpp プロジェクト: mpbraendli/dabtools
static int do_sdr_decode(struct dab_state_t* dab, int frequency, int gain)
{
  struct sigaction sigact;
  uint32_t dev_index = 0;
  int32_t device_count;
  int i,r;
  char vendor[256], product[256], serial[256];
  uint32_t samp_rate = 2048000;

  memset(&sdr,0,sizeof(struct sdr_state_t));

  sdr.frequency = frequency;

  //fprintf(stderr,"%i\n",sdr.frequency);

  /*---------------------------------------------------
    Looking for device and open connection
    ----------------------------------------------------*/
  if (dab->device_type == DAB_DEVICE_RTLSDR) {
    sdr.convert_unsigned = 1;

    device_count = rtlsdr_get_device_count();
    if (!device_count) {
      fprintf(stderr, "No supported devices found.\n");
      exit(1);
    }

    fprintf(stderr, "Found %d device(s):\n", device_count);
    for (i = 0; i < device_count; i++) {
      rtlsdr_get_device_usb_strings(i, vendor, product, serial);
      fprintf(stderr, "  %d:  %s, %s, SN: %s\n", i, vendor, product, serial);
    }
    fprintf(stderr, "\n");

    fprintf(stderr, "Using device %d: %s\n",dev_index, rtlsdr_get_device_name(dev_index));

    r = rtlsdr_open(&dev, dev_index);
    if (r < 0) {
      fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
      exit(1);
    }

    int gains[100];
    int count = rtlsdr_get_tuner_gains(dev, gains);
    fprintf(stderr, "Supported gain values (%d): ", count);
    for (i = 0; i < count; i++)
      fprintf(stderr, "%.1f ", gains[i] / 10.0);
    fprintf(stderr, "\n");
  }
  else if (dab->device_type == DAB_DEVICE_HACKRF) {
    sdr.convert_unsigned = 0;
    r = hackrf_init();
    if( r != HACKRF_SUCCESS ) {
      hackrf_err("hackrf_init() failed", r);
      return EXIT_FAILURE;
    }

    const char* serial_number = nullptr;
    r = hackrf_open_by_serial(serial_number, &hackrf);
    if( r != HACKRF_SUCCESS ) {
      hackrf_err("hackrf_open() failed", r);
      return EXIT_FAILURE;
    }
  }
  else
  {
    r = -1;
    return EXIT_FAILURE;
  }

  /*-------------------------------------------------
    Set Frequency & Sample Rate
    --------------------------------------------------*/
  if (dab->device_type == DAB_DEVICE_RTLSDR) {
    /* Set the sample rate */
    r = rtlsdr_set_sample_rate(dev, samp_rate);
    if (r < 0)
      fprintf(stderr, "WARNING: Failed to set sample rate.\n");

    /* Set the frequency */
    r = rtlsdr_set_center_freq(dev, sdr.frequency);
    if (r < 0)
      fprintf(stderr, "WARNING: Failed to set center freq.\n");
    else
      fprintf(stderr, "Tuned to %u Hz.\n", sdr.frequency);

    /*------------------------------------------------
      Setting gain  
      -------------------------------------------------*/
    if (gain == AUTO_GAIN) {
      r = rtlsdr_set_tuner_gain_mode(dev, 0);
    } else {
      r = rtlsdr_set_tuner_gain_mode(dev, 1);
      r = rtlsdr_set_tuner_gain(dev, gain);
    }
    if (r != 0) {
      fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
    } else if (gain == AUTO_GAIN) {
      fprintf(stderr, "Tuner gain set to automatic.\n");
    } else {
      fprintf(stderr, "Tuner gain set to %0.2f dB.\n", gain/10.0);
    }
    /*-----------------------------------------------
      /  Reset endpoint (mandatory) 
      ------------------------------------------------*/
    r = rtlsdr_reset_buffer(dev);
  }
  else if (dab->device_type == DAB_DEVICE_HACKRF) {
    int sample_rate_hz = samp_rate;
    fprintf(stderr, "call hackrf_sample_rate_set(%u Hz/%.03f MHz)\n", sample_rate_hz, (sample_rate_hz/1e6));
    int r = hackrf_set_sample_rate_manual(hackrf, sample_rate_hz, 1);
    if( r != HACKRF_SUCCESS ) {
      hackrf_err("hackrf_sample_rate_set() failed", r);
      return EXIT_FAILURE;
    }

    /* possible settings 1.75/2.5/3.5/5/5.5/6/7/8/9/10/12/14/15/20/24/28 */
    int baseband_filter_bw_hz = 2500000;
    fprintf(stderr, "call hackrf_baseband_filter_bandwidth_set(%d Hz/%.03f MHz)\n",
        baseband_filter_bw_hz, ((float)baseband_filter_bw_hz/1e6));
    r = hackrf_set_baseband_filter_bandwidth(hackrf, baseband_filter_bw_hz);
    if( r != HACKRF_SUCCESS ) {
      hackrf_err("hackrf_baseband_filter_bandwidth_set()", r);
      return EXIT_FAILURE;
    }

    r = hackrf_set_vga_gain(hackrf, hackrf_vga_gain);
    r |= hackrf_set_lna_gain(hackrf, hackrf_lna_gain);

    if( r != HACKRF_SUCCESS ) {
      hackrf_err("hackrf_vga gain/lna gain", r);
      return EXIT_FAILURE;
    }

    r = hackrf_set_freq(hackrf, sdr.frequency);
    if( r != HACKRF_SUCCESS ) {
      hackrf_err("hackrf_set_freq()", r);
      return EXIT_FAILURE;
    }
  }
  /*-----------------------------------------------
  / Signal handler
  ------------------------------------------------*/
  sigact.sa_handler = sighandler;
  sigemptyset(&sigact.sa_mask);
  sigact.sa_flags = 0;
  sigaction(SIGINT, &sigact, NULL);
  sigaction(SIGTERM, &sigact, NULL);
  sigaction(SIGQUIT, &sigact, NULL);
  sigaction(SIGPIPE, &sigact, NULL);
  /*-----------------------------------------------
  / start demod thread & rtl read 
  -----------------------------------------------*/

  fprintf(stderr,"Waiting for sync...\n");

  sdr_init(&sdr);
  //dab_fic_parser_init(&sinfo);
  //dab_analyzer_init(&ana);
  pthread_create(&demod_thread, NULL, demod_thread_fn, (void *)(dab));
  if (dab->device_type == DAB_DEVICE_RTLSDR) {
    rtlsdr_read_async(dev, rtlsdr_callback, (void *)(&sdr),
        DEFAULT_ASYNC_BUF_NUMBER, DEFAULT_BUF_LENGTH);
  }
  else if (dab->device_type == DAB_DEVICE_HACKRF) {
    r = hackrf_start_rx(hackrf, hackrf_callback, (void *)(&sdr));

    if( r != HACKRF_SUCCESS ) {
      hackrf_err("hackrf_start_x()", r);
      return EXIT_FAILURE;
    }

    while( ((r=hackrf_is_streaming(hackrf)) == HACKRF_TRUE) &&
        (do_exit == false) ) {
      sleep(1);
      fprintf(stderr, "samples: low: %02.2f%%, saturating: %02.2f%%\n",
          num_low_power * 100.0 / DEFAULT_BUF_LENGTH,
          num_saturated * 100.0 / DEFAULT_BUF_LENGTH);
    }
    hackrf_err("hackrf_is_streaming", r);
  }


  if (do_exit) {
    fprintf(stderr, "\nUser cancel, exiting...\n");}
  else {
    fprintf(stderr, "\nLibrary error %d, exiting...\n", r);}
  if (dab->device_type == DAB_DEVICE_RTLSDR) {
    rtlsdr_cancel_async(dev);
    //dab_demod_close(&dab);
    rtlsdr_close(dev);
  }
  else if (dab->device_type == DAB_DEVICE_HACKRF) {
    if (hackrf != NULL)
    {
      r = hackrf_stop_rx(hackrf);
      if( r != HACKRF_SUCCESS ) {
        hackrf_err("hackrf_stop_rx() failed", r);
      }
      else {
        fprintf(stderr, "hackrf_stop_rx() done\n");
      }

      r = hackrf_close(hackrf);
      if( r != HACKRF_SUCCESS )
      {
        hackrf_err("hackrf_close() failed", r);
      }
      else {
        fprintf(stderr, "hackrf_close() done\n");
      }
    }

    hackrf_exit();
  }
  return 1;
}
コード例 #22
0
ファイル: hackrf_si5351c.c プロジェクト: sikopet/hackrf
int main(int argc, char** argv) {
	int opt;
	uint16_t register_number = REGISTER_INVALID;
	uint16_t register_value;
	
	int result = hackrf_init();
	if( result ) {
		printf("hackrf_init() failed: %s (%d)\n", hackrf_error_name(result), result);
		return -1;
	}
	
	hackrf_device* device = NULL;
	result = hackrf_open(&device);
	if( result ) {
		printf("hackrf_open() failed: %s (%d)\n", hackrf_error_name(result), result);
		return -1;
	}

	int option_index = 0;
	while( (opt = getopt_long(argc, argv, "cn:rw:", long_options, &option_index)) != EOF ) {
		switch( opt ) {
		case 'n':
			result = parse_int(optarg, &register_number);
			break;
		
		case 'w':
			result = parse_int(optarg, &register_value);
			if( result == HACKRF_SUCCESS ) {
				result = write_register(device, register_number, register_value);
			}
			break;
		
		case 'r':
			if( register_number == REGISTER_INVALID ) {
				result = dump_registers(device);
			} else {
				result = dump_register(device, register_number);
			}
			break;
		
		case 'c':
			dump_configuration(device);
			break;

		default:
			usage();
		}
		
		if( result != HACKRF_SUCCESS ) {
			printf("argument error: %s (%d)\n", hackrf_error_name(result), result);
			break;
		}
	}
	
	result = hackrf_close(device);
	if( result ) {
		printf("hackrf_close() failed: %s (%d)\n", hackrf_error_name(result), result);
		return -1;
	}
	
	hackrf_exit();
    
    return 0;
}