Portapack应用开发教程(四)GPS应用具体更改

我把我做的更改加了注释

gps_sim_app.cpp

#include "gps_sim_app.hpp"
#include "string_format.hpp"

#include "ui_fileman.hpp"
#include "io_file.hpp"

#include "baseband_api.hpp"
#include "portapack.hpp"
#include "portapack_persistent_memory.hpp"

using namespace portapack;

namespace ui {

void GpsSimAppView::set_ready() {
	ready_signal = true;
}
//读取iq数据文件对应的txt文件
void GpsSimAppView::on_file_changed(std::filesystem::path new_file_path) {
	File data_file, info_file;
	char file_data[257];
	
	// Get file size
	auto data_open_error = data_file.open("/" + new_file_path.string());
	if (data_open_error.is_valid()) {
		file_error();
		return;
	}
	
	file_path = new_file_path;
	
	// Get original record frequency if available
	std::filesystem::path info_file_path = file_path;
	info_file_path.replace_extension(u".TXT");
	
	sample_rate = 500000;
	
	auto info_open_error = info_file.open("/" + info_file_path.string());
	if (!info_open_error.is_valid()) {
		memset(file_data, 0, 257);
		auto read_size = info_file.read(file_data, 256);
		if (!read_size.is_error()) {
			auto pos1 = strstr(file_data, "center_frequency=");//读到中心频率
			if (pos1) {
				pos1 += 17;
				field_frequency.set_value(strtoll(pos1, nullptr, 10));
			} //把读取到的值保存到field_frequency变量中
			
			auto pos2 = strstr(file_data, "sample_rate=");//读到采样率
			if (pos2) {
				pos2 += 12;
				sample_rate = strtoll(pos2, nullptr, 10);
			}//把读取到的值保存到sample_rate变量中
		}
	}
	//这个是把采样率显示到界面上,unit_auto_scale函数我点开看了
    //最后一个参数是小数点后的精确到第几位,本来是0,这样2.6MHz只能显示为2.0MHz
    //我现在改为1后才能正常显示2.6MHz
	text_sample_rate.set(unit_auto_scale(sample_rate, 3, 1) + "Hz");
	
	auto file_size = data_file.size();
	auto duration = (file_size * 1000) / (1 * 2 * sample_rate);
	//这个duration是文件持续多久,根据文件尺寸计算,本来计算的是不对的
    //因为C16比C8尺寸大一倍,现在文件尺寸小了,时间算起来会比正确的小一倍,所以要改一改分母
	progressbar.set_max(file_size);
	text_filename.set(file_path.filename().string().substr(0, 12));
	text_duration.set(to_string_time_ms(duration));
	
	button_play.focus();
}

void GpsSimAppView::on_tx_progress(const uint32_t progress) {
	progressbar.set_value(progress);
}

void GpsSimAppView::focus() {
	button_open.focus();
}

void GpsSimAppView::file_error() {
	nav_.display_modal("Error", "File read error.");
}

bool GpsSimAppView::is_active() const {
	return (bool)replay_thread;
}

void GpsSimAppView::toggle() {
	if( is_active() ) {
		stop(false);
	} else {
		start();
	}
}

void GpsSimAppView::start() {
	stop(false);

	std::unique_ptr<stream::Reader> reader;
	
	auto p = std::make_unique<FileReader>();
	auto open_error = p->open(file_path);
	if( open_error.is_valid() ) {
		file_error();
	} else {
		reader = std::move(p);
	}

	if( reader ) {
		button_play.set_bitmap(&bitmap_stop);
		baseband::set_sample_rate(sample_rate * 4);
		//设置基带采样率,本来是8倍过采样,500kHz变为4MHz,我这里也是过*8,用8倍过采样
        //做出来的频谱跟正常的gps信号类似,但是手机收不到信号
        //改为*4后,带宽缩小一倍,手机反而能收到信号,但是锁定不了
		replay_thread = std::make_unique<ReplayThread>(
			std::move(reader),
			read_size, buffer_count,
			&ready_signal,
			[](uint32_t return_code) {
				ReplayThreadDoneMessage message { return_code };
				EventDispatcher::send_message(message);
			}
		);
	}
	
	radio::enable({
		receiver_model.tuning_frequency(),
		sample_rate * 4, //这里跟上面说的差不多,本来是*8,现在改为*4后反而可以让手机收到gps
		baseband_bandwidth,
		rf::Direction::Transmit,
		receiver_model.rf_amp(),
		static_cast<int8_t>(receiver_model.lna()),
		static_cast<int8_t>(receiver_model.vga())
	});
}

void GpsSimAppView::stop(const bool do_loop) {
	if( is_active() )
		replay_thread.reset();
	
	if (do_loop && check_loop.value()) {
		start();
	} else {
		radio::disable();
		button_play.set_bitmap(&bitmap_play);
	}
	
	ready_signal = false;
}

void GpsSimAppView::handle_replay_thread_done(const uint32_t return_code) {
	if (return_code == ReplayThread::END_OF_FILE) {
		stop(true);
	} else if (return_code == ReplayThread::READ_ERROR) {
		stop(false);
		file_error();
	}
	
	progressbar.set_value(0);
}

GpsSimAppView::GpsSimAppView(
	NavigationView& nav
) : nav_ (nav)
{
	baseband::run_image(portapack::spi_flash::image_tag_gps);

	add_children({
		&labels,
		&button_open,
		&text_filename,
		&text_sample_rate,
		&text_duration,
		&progressbar,
		&field_frequency,
		&field_lna,
		&field_rf_amp,
		&check_loop,
		&button_play,
		&waterfall,
	});
	
	field_frequency.set_value(target_frequency());
	field_frequency.set_step(receiver_model.frequency_step());
	field_frequency.on_change = [this](rf::Frequency f) {
		this->on_target_frequency_changed(f);
	};
	field_frequency.on_edit = [this, &nav]() {
		// TODO: Provide separate modal method/scheme?
		auto new_view = nav.push<FrequencyKeypadView>(this->target_frequency());
		new_view->on_changed = [this](rf::Frequency f) {
			this->on_target_frequency_changed(f);
			this->field_frequency.set_value(f);
		};
	};

	field_frequency.set_step(5000);
	
	button_play.on_select = [this](ImageButton&) {
		this->toggle();
	};
	
	button_open.on_select = [this, &nav](Button&) {
		auto open_view = nav.push<FileLoadView>(".C8");
        //这里本来是".C16",只会显示C16后缀的文件,现在被我改为C8了,显示C8后缀的文件
		open_view->on_changed = [this](std::filesystem::path new_file_path) {
			on_file_changed(new_file_path);
		};
	};
}

GpsSimAppView::~GpsSimAppView() {
	radio::disable();
	baseband::shutdown();
}

void GpsSimAppView::on_hide() {
	// TODO: Terrible kludge because widget system doesn't notify Waterfall that
	// it's being shown or hidden.
	waterfall.on_hide();
	View::on_hide();
}

void GpsSimAppView::set_parent_rect(const Rect new_parent_rect) {
	View::set_parent_rect(new_parent_rect);

	const ui::Rect waterfall_rect { 0, header_height, new_parent_rect.width(), new_parent_rect.height() - header_height };
	waterfall.set_parent_rect(waterfall_rect);
}

void GpsSimAppView::on_target_frequency_changed(rf::Frequency f) {
	set_target_frequency(f);
}

void GpsSimAppView::set_target_frequency(const rf::Frequency new_value) {
	persistent_memory::set_tuned_frequency(new_value);;
}

rf::Frequency GpsSimAppView::target_frequency() const {
	return persistent_memory::tuned_frequency();
}

} /* namespace ui */

gps_sim_app.hpp

#ifndef __GPS_SIM_APP_HPP__
#define __GPS_SIM_APP_HPP__

#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
#include "replay_thread.hpp"
#include "ui_spectrum.hpp"

#include <string>
#include <memory>

namespace ui {

class GpsSimAppView : public View {
public:
	GpsSimAppView(NavigationView& nav);
	~GpsSimAppView();

	void on_hide() override;
	void set_parent_rect(const Rect new_parent_rect) override;
	void focus() override;

	std::string title() const override { return "GPS Simulator"; };
	//这是界面上方的标题
private:
	NavigationView& nav_;
	
	static constexpr ui::Dim header_height = 3 * 16;
	
	uint32_t sample_rate = 0;
	static constexpr uint32_t baseband_bandwidth = 2000000;
    //本来这里是2500000也就是2.5MHz的基带带宽,我打算发射2MHz的数据,所以改为了2000000
	const size_t read_size { 16384 };
	const size_t buffer_count { 3 };

	void on_file_changed(std::filesystem::path new_file_path);
	void on_target_frequency_changed(rf::Frequency f);
	void on_tx_progress(const uint32_t progress);
	
	void set_target_frequency(const rf::Frequency new_value);
	rf::Frequency target_frequency() const;

	void toggle();
	void start();
	void stop(const bool do_loop);
	bool is_active() const;
	void set_ready();
	void handle_replay_thread_done(const uint32_t return_code);
	void file_error();

	std::filesystem::path file_path { };
	std::unique_ptr<ReplayThread> replay_thread { };
	bool ready_signal { false };

	Labels labels {
		{ { 10 * 8, 2 * 16 }, "LNA:   A:", Color::light_grey() }
	};
	
	Button button_open {
		{ 0 * 8, 0 * 16, 10 * 8, 2 * 16 },
		"Open file"
	};
	
	Text text_filename {
		{ 11 * 8, 0 * 16, 12 * 8, 16 },
		"-"
	};
	Text text_sample_rate {
		{ 24 * 8, 0 * 16, 6 * 8, 16 },
		"-"
	};
	
	Text text_duration {
		{ 11 * 8, 1 * 16, 6 * 8, 16 },
		"-"
	};
	ProgressBar progressbar {
		{ 18 * 8, 1 * 16, 12 * 8, 16 }
	};
	
	FrequencyField field_frequency {
		{ 0 * 8, 2 * 16 },
	};
	LNAGainField field_lna {
		{ 14 * 8, 2 * 16 }
	};
	RFAmpField field_rf_amp {
		{ 19 * 8, 2 * 16 }
	};
	Checkbox check_loop {
		{ 21 * 8, 2 * 16 },
		4,
		"Loop",
		true
	};
	ImageButton button_play {
		{ 28 * 8, 2 * 16, 2 * 8, 1 * 16 },
		&bitmap_play,
		Color::green(),
		Color::black()
	};

	spectrum::WaterfallWidget waterfall { };

	MessageHandlerRegistration message_handler_replay_thread_error {
		Message::ID::ReplayThreadDone,
		[this](const Message* const p) {
			const auto message = *reinterpret_cast<const ReplayThreadDoneMessage*>(p);
			this->handle_replay_thread_done(message.return_code);
		}
	};
	
	MessageHandlerRegistration message_handler_fifo_signal {
		Message::ID::RequestSignal,
		[this](const Message* const p) {
			const auto message = static_cast<const RequestSignalMessage*>(p);
			if (message->signal == RequestSignalMessage::Signal::FillRequest) {
				this->set_ready();
			}
		}
	};
	
	MessageHandlerRegistration message_handler_tx_progress {
		Message::ID::TXProgress,
		[this](const Message* const p) {
			const auto message = *reinterpret_cast<const TXProgressMessage*>(p);
			this->on_tx_progress(message.progress);
		}
	};
};

} /* namespace ui */

#endif/*__GPS_SIM_APP_HPP__*/

proc_gps_sim.app

#include "proc_gps_sim.hpp"
#include "sine_table_int8.hpp"
#include "portapack_shared_memory.hpp"

#include "event_m4.hpp"

#include "utility.hpp"

ReplayProcessor::ReplayProcessor() {
	channel_filter_pass_f = taps_200k_decim_1.pass_frequency_normalized * 1000000;	// 162760.416666667
	channel_filter_stop_f = taps_200k_decim_1.stop_frequency_normalized * 1000000;	// 337239.583333333
	
	spectrum_samples = 0;

	channel_spectrum.set_decimation_factor(1);
	
	configured = false;
}

void ReplayProcessor::execute(const buffer_c8_t& buffer) {
	/* 4MHz, 2048 samples */
	
	if (!configured) return;
	
	// File data is in C16 format, we need C8
	// File samplerate is 500kHz, we're at 4MHz
	// iq_buffer can only be 512 C16 samples (RAM limitation)
	// To fill up the 2048-sample C8 buffer, we need:
	// 2048 samples * 2 bytes per sample = 4096 bytes
	// Since we're oversampling by 4M/500k = 8, we only need 2048/8 = 256 samples from the file and duplicate them 8 times each
	// So 256 * 4 bytes per sample (C16) = 1024 bytes from the file

    //这段英文注释是本来replay里的,不符合我们这里的情况了
    //replay里,读取的文件是C16格式,发送的是C8格式,另外采样率要从500kHz增加到4MHz
    //iq_buffer由于内存限制512个C16采样点不会变
    //2048个C8采样点,一个采样点包含一个int8实部一个int8虚部,这样一个采样点就是2个byte
    //2048个采样点就是4096 byte
    //本来在replay里要从500kHz变为4MHz要做8倍过采样
    //那么要实现2048个采样点实际从文件里只需要1/8的点就行,也就是256个采样点
    //然后每个点重复8次就行,我本来也打算8倍过采样,只不过gps_sim_app.cpp里必须改为*4才有效果
    //所以下面还是按照8倍过采样来做
	if( stream ) {                            
    //sizeof(*buffer.p) = sizeof(C8) = 2*int8 = 2 bytes 
    //buffer是这个函数的输入参数,已经声明为C8类型了
    //buffer.count = 2048
    //这个2048是要给缓存生成的采样点长度
		const size_t bytes_to_read = sizeof(*buffer.p) * 1 * (buffer.count / 8);	
    // 本来是*2 (C16),现在C8所以*1, /8 是过采样导致的,实际只需要读取文件里的1/8
		bytes_read += stream->read(iq_buffer.p, bytes_to_read);
	}
	
	// Fill and "stretch"
	for (size_t i = 0; i < buffer.count; i++) {
        //注释里的是本来用的代码
        //下面是我自己写的 应该效果一样
		/*if (i & 3) { 
            //这里i&3是按位与 i与11做与操作如果i是000 100,也就是4的整数倍?
            //就不会进入这里,首先i长度我不知道,而且为啥是4的整数倍?不是8?
            //如果一旦进入这里,说明i不是8的整数倍,那么buffer.p的取值与前一个取之相同
            //也就是在做过采样的插值操作,中间的点全部重复之前的点
			buffer.p[i] = buffer.p[i - 1];
		} else { 
            //如果i是8的整数倍,要取出一个新的点获得新的数据
            //i>>3,相当于i/8,然后从iq_buffer.p里获得新的数据存入buffer.p就行
			auto re_out = iq_buffer.p[i >> 3].real() ;
			auto im_out = iq_buffer.p[i >> 3].imag() ;
			buffer.p[i] = { (int8_t)re_out, (int8_t)im_out };
		}*/
        //为了更直观,我把按位操作全部替换为我习惯的方式了
        //另外我也根据我理解的过采样,与8的整数倍比较而不是4了
                if (i % 8 != 0) {
			buffer.p[i] = buffer.p[i - 1];
		} else {
			auto re_out = iq_buffer.p[i/8].real() ;
			auto im_out = iq_buffer.p[i/8].imag() ;
			buffer.p[i] = { (int8_t)re_out, (int8_t)im_out };
		}
        
	}
	
	spectrum_samples += buffer.count;
	if( spectrum_samples >= spectrum_interval_samples ) {
		spectrum_samples -= spectrum_interval_samples;
		//channel_spectrum.feed(iq_buffer, channel_filter_pass_f, channel_filter_stop_f);
		
		txprogress_message.progress = bytes_read;	// Inform UI about progress
		txprogress_message.done = false;
		shared_memory.application_queue.push(txprogress_message);
	}
}

void ReplayProcessor::on_message(const Message* const message) {
	switch(message->id) {
	case Message::ID::UpdateSpectrum:
	case Message::ID::SpectrumStreamingConfig:
		channel_spectrum.on_message(message);
		break;

	case Message::ID::SamplerateConfig:
		samplerate_config(*reinterpret_cast<const SamplerateConfigMessage*>(message));
		break;
	
	case Message::ID::ReplayConfig:
		configured = false;
		bytes_read = 0;
		replay_config(*reinterpret_cast<const ReplayConfigMessage*>(message));
		break;
		
	// App has prefilled the buffers, we're ready to go now
	case Message::ID::FIFOData:
		configured = true;
		break;

	default:
		break;
	}
}

void ReplayProcessor::samplerate_config(const SamplerateConfigMessage& message) {
	baseband_fs = message.sample_rate;
	baseband_thread.set_sampling_rate(baseband_fs);
	spectrum_interval_samples = baseband_fs / spectrum_rate_hz;
}

void ReplayProcessor::replay_config(const ReplayConfigMessage& message) {
	if( message.config ) {
		
		stream = std::make_unique<StreamOutput>(message.config);
		
		// Tell application that the buffers and FIFO pointers are ready, prefill
		shared_memory.application_queue.push(sig_message);
	} else {
		stream.reset();
	}
}

int main() {
	EventDispatcher event_dispatcher { std::make_unique<ReplayProcessor>() };
	event_dispatcher.run();
	return 0;
}

proc_sim_app.hpp

#ifndef __PROC_GPS_SIM_HPP__
#define __PROC_GPS_SIM_HPP__

#include "baseband_processor.hpp"
#include "baseband_thread.hpp"

#include "spectrum_collector.hpp"

#include "stream_output.hpp"

#include <array>
#include <memory>

class ReplayProcessor : public BasebandProcessor {
public:
	ReplayProcessor();

	void execute(const buffer_c8_t& buffer) override;

	void on_message(const Message* const message) override;

private:
	size_t baseband_fs = 0;
	static constexpr auto spectrum_rate_hz = 50.0f;

	BasebandThread baseband_thread { baseband_fs, this, NORMALPRIO + 20, baseband::Direction::Transmit };
   
	std::array<complex8_t, 256> iq { }; 
    //上面的类型complex8_t和下面buffer_c8_t是我改的
    //如果不这么改,我用频谱仪观察发射的波形,完全不是GPS正常的圆拱形了
    //所以这里改的肯定没错
	const buffer_c8_t iq_buffer {  
		iq.data(),
		iq.size(),
		baseband_fs /4 这里/4还是/8貌似没什么区别
	};
	
	uint32_t channel_filter_pass_f = 0;
	uint32_t channel_filter_stop_f = 0;

	std::unique_ptr<StreamOutput> stream { };

	SpectrumCollector channel_spectrum { };
	size_t spectrum_interval_samples = 0;
	size_t spectrum_samples = 0;
	
	bool configured { false };
	uint32_t bytes_read { 0 };

	void samplerate_config(const SamplerateConfigMessage& message);
	void replay_config(const ReplayConfigMessage& message);
	
	TXProgressMessage txprogress_message { };
	RequestSignalMessage sig_message { RequestSignalMessage::Signal::FillRequest };
};

#endif/*__PROC_GPS_SIM_HPP__*/

稍后我会上传正常的GPS波形,以及手机搜星强度,以及我自己的程序生成的波形和手机搜星强度。

我用下面的命令生成了GPS数据文件,我采样率没有用2.6MHz的,而是使用2MHz,这样后面凑过采样比较方便,而且我发现这样也是能定位的

./gps-sdr-sim -e brdc3540.14n -l 40,110,100 -b 8 -s 2000000

1.用GridRF版本的portapack来发射GPS信号

这种方式定位最快速,而且很稳定,锁定后不会丢信号,而且定位精度也很高

 

可以看到信号强度基本都在50以上。 

2.hackrf_transfer

这是我没有用portapack,而是直接用电脑来发射前面生成的数据文件。我在这里提高了发射增益到30,否则频谱上看不到波形。

这种模式搜星要等待一段时间,而且有时候锁定后稍微动一下就会失去锁定。

hackrf_transfer -t gpssim.bin -f 1575420000 -s 2000000 -a 1 -x 30

有时候能锁定,有时候不行。 

3.  4 oversample

这是我自己改的固件,过采样率的几个变量我设置为*4,有个地方是/4,就跟我贴的代码里那样。

界面上的设置是:LNA 32 A 0

这种情况下频谱图变了。

但是手机还是能收到信号,只是不能定位,而且信号强度明显降低了,只有30左右,但是我手机与portpack的距离没变化。

4. 8 oversample

这也是我自己的固件,我把所有*4和/4都改为了*8和/8。也就是说这是完全符合我理解的理论来写的代码

界面设置:LNA 32 A 0

这时候,频谱形状和gridrf是比较像的,只是瀑布图上看得到信号有些断断续续。

这时候手机是完全看不到卫星的。 

总结:

2效果不如1好可能是实时性的问题。忽略掉2不看。

1和3虽然带宽不同,但是3的频谱其实是连续的,这一点和1一样,4虽然带宽和1一样宽,但是瀑布图看得出是有中断的,可能是这个中断导致的问题,我没把缓存用满。

后来我就在想办法怎么把缓存用满,proc_gps_sim.cpp里的bytes_to_read尽量改大些,我干脆把/8去掉了,这样一来,proc_gps_sim.hpp里的iq声明的时候长度声明为2048,否则会出错。然后我在gps_sim_app.cpp的start函数里把过采样*8给去掉了,生成多少我就发多少。gps_sim_app.hpp里的baseband_bandwidth设置为3000000,这个基本上是基带滤波器,比要发射的信号宽一点就行,我发的gps信号在2MHz~2.6MHz,所以3MHz够了。另外,proc_gps_sim.cpp的execute函数的"Fill and "stretch"里实际上我取出来多少就赋值多少,实际没做过采样了。

附上我最新改的代码:

gps_sim_app.cpp


#include "gps_sim_app.hpp"
#include "string_format.hpp"

#include "ui_fileman.hpp"
#include "io_file.hpp"

#include "baseband_api.hpp"
#include "portapack.hpp"
#include "portapack_persistent_memory.hpp"

using namespace portapack;

namespace ui {

void GpsSimAppView::set_ready() {
	ready_signal = true;
}

void GpsSimAppView::on_file_changed(std::filesystem::path new_file_path) {
	File data_file, info_file;
	char file_data[257];
	
	// Get file size
	auto data_open_error = data_file.open("/" + new_file_path.string());
	if (data_open_error.is_valid()) {
		file_error();
		return;
	}
	
	file_path = new_file_path;
	
	// Get original record frequency if available
	std::filesystem::path info_file_path = file_path;
	info_file_path.replace_extension(u".TXT");
	
	sample_rate = 500000;
	
	auto info_open_error = info_file.open("/" + info_file_path.string());
	if (!info_open_error.is_valid()) {
		memset(file_data, 0, 257);
		auto read_size = info_file.read(file_data, 256);
		if (!read_size.is_error()) {
			auto pos1 = strstr(file_data, "center_frequency=");
			if (pos1) {
				pos1 += 17;
				field_frequency.set_value(strtoll(pos1, nullptr, 10));
			}
			
			auto pos2 = strstr(file_data, "sample_rate=");
			if (pos2) {
				pos2 += 12;
				sample_rate = strtoll(pos2, nullptr, 10);
			}
		}
	}
	
	text_sample_rate.set(unit_auto_scale(sample_rate, 3, 1) + "Hz");
	
	auto file_size = data_file.size();
	auto duration = (file_size * 1000) / (1 * 2 * sample_rate);
	
	progressbar.set_max(file_size);
	text_filename.set(file_path.filename().string().substr(0, 12));
	text_duration.set(to_string_time_ms(duration));
	
	button_play.focus();
}

void GpsSimAppView::on_tx_progress(const uint32_t progress) {
	progressbar.set_value(progress);
}

void GpsSimAppView::focus() {
	button_open.focus();
}

void GpsSimAppView::file_error() {
	nav_.display_modal("Error", "File read error.");
}

bool GpsSimAppView::is_active() const {
	return (bool)replay_thread;
}

void GpsSimAppView::toggle() {
	if( is_active() ) {
		stop(false);
	} else {
		start();
	}
}

void GpsSimAppView::start() {
	stop(false);

	std::unique_ptr<stream::Reader> reader;
	
	auto p = std::make_unique<FileReader>();
	auto open_error = p->open(file_path);
	if( open_error.is_valid() ) {
		file_error();
	} else {
		reader = std::move(p);
	}

	if( reader ) {
		button_play.set_bitmap(&bitmap_stop);
		baseband::set_sample_rate(sample_rate );
		
		replay_thread = std::make_unique<ReplayThread>(
			std::move(reader),
			read_size, buffer_count,
			&ready_signal,
			[](uint32_t return_code) {
				ReplayThreadDoneMessage message { return_code };
				EventDispatcher::send_message(message);
			}
		);
	}
	
	radio::enable({
		receiver_model.tuning_frequency(),
		sample_rate ,
		baseband_bandwidth,
		rf::Direction::Transmit,
		receiver_model.rf_amp(),
		static_cast<int8_t>(receiver_model.lna()),
		static_cast<int8_t>(receiver_model.vga())
	});
}

void GpsSimAppView::stop(const bool do_loop) {
	if( is_active() )
		replay_thread.reset();
	
	if (do_loop && check_loop.value()) {
		start();
	} else {
		radio::disable();
		button_play.set_bitmap(&bitmap_play);
	}
	
	ready_signal = false;
}

void GpsSimAppView::handle_replay_thread_done(const uint32_t return_code) {
	if (return_code == ReplayThread::END_OF_FILE) {
		stop(true);
	} else if (return_code == ReplayThread::READ_ERROR) {
		stop(false);
		file_error();
	}
	
	progressbar.set_value(0);
}

GpsSimAppView::GpsSimAppView(
	NavigationView& nav
) : nav_ (nav)
{
	baseband::run_image(portapack::spi_flash::image_tag_gps);

	add_children({
		&labels,
		&button_open,
		&text_filename,
		&text_sample_rate,
		&text_duration,
		&progressbar,
		&field_frequency,
		&field_lna,
		&field_rf_amp,
		&check_loop,
		&button_play,
		&waterfall,
	});
	
	field_frequency.set_value(target_frequency());
	field_frequency.set_step(receiver_model.frequency_step());
	field_frequency.on_change = [this](rf::Frequency f) {
		this->on_target_frequency_changed(f);
	};
	field_frequency.on_edit = [this, &nav]() {
		// TODO: Provide separate modal method/scheme?
		auto new_view = nav.push<FrequencyKeypadView>(this->target_frequency());
		new_view->on_changed = [this](rf::Frequency f) {
			this->on_target_frequency_changed(f);
			this->field_frequency.set_value(f);
		};
	};

	field_frequency.set_step(5000);
	
	button_play.on_select = [this](ImageButton&) {
		this->toggle();
	};
	
	button_open.on_select = [this, &nav](Button&) {
		auto open_view = nav.push<FileLoadView>(".C8");
		open_view->on_changed = [this](std::filesystem::path new_file_path) {
			on_file_changed(new_file_path);
		};
	};
}

GpsSimAppView::~GpsSimAppView() {
	radio::disable();
	baseband::shutdown();
}

void GpsSimAppView::on_hide() {
	// TODO: Terrible kludge because widget system doesn't notify Waterfall that
	// it's being shown or hidden.
	waterfall.on_hide();
	View::on_hide();
}

void GpsSimAppView::set_parent_rect(const Rect new_parent_rect) {
	View::set_parent_rect(new_parent_rect);

	const ui::Rect waterfall_rect { 0, header_height, new_parent_rect.width(), new_parent_rect.height() - header_height };
	waterfall.set_parent_rect(waterfall_rect);
}

void GpsSimAppView::on_target_frequency_changed(rf::Frequency f) {
	set_target_frequency(f);
}

void GpsSimAppView::set_target_frequency(const rf::Frequency new_value) {
	persistent_memory::set_tuned_frequency(new_value);;
}

rf::Frequency GpsSimAppView::target_frequency() const {
	return persistent_memory::tuned_frequency();
}

} /* namespace ui */

gps_sim_app.hpp

#ifndef __GPS_SIM_APP_HPP__
#define __GPS_SIM_APP_HPP__

#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
#include "replay_thread.hpp"
#include "ui_spectrum.hpp"

#include <string>
#include <memory>

namespace ui {

class GpsSimAppView : public View {
public:
	GpsSimAppView(NavigationView& nav);
	~GpsSimAppView();

	void on_hide() override;
	void set_parent_rect(const Rect new_parent_rect) override;
	void focus() override;

	std::string title() const override { return "GPS Simulator"; };
	
private:
	NavigationView& nav_;
	
	static constexpr ui::Dim header_height = 3 * 16;
	
	uint32_t sample_rate = 0;
	static constexpr uint32_t baseband_bandwidth = 3000000; //filter bandwidth
	const size_t read_size { 16384 };
	const size_t buffer_count { 3 };

	void on_file_changed(std::filesystem::path new_file_path);
	void on_target_frequency_changed(rf::Frequency f);
	void on_tx_progress(const uint32_t progress);
	
	void set_target_frequency(const rf::Frequency new_value);
	rf::Frequency target_frequency() const;

	void toggle();
	void start();
	void stop(const bool do_loop);
	bool is_active() const;
	void set_ready();
	void handle_replay_thread_done(const uint32_t return_code);
	void file_error();

	std::filesystem::path file_path { };
	std::unique_ptr<ReplayThread> replay_thread { };
	bool ready_signal { false };

	Labels labels {
		{ { 10 * 8, 2 * 16 }, "LNA:   A:", Color::light_grey() }
	};
	
	Button button_open {
		{ 0 * 8, 0 * 16, 10 * 8, 2 * 16 },
		"Open file"
	};
	
	Text text_filename {
		{ 11 * 8, 0 * 16, 12 * 8, 16 },
		"-"
	};
	Text text_sample_rate {
		{ 24 * 8, 0 * 16, 6 * 8, 16 },
		"-"
	};
	
	Text text_duration {
		{ 11 * 8, 1 * 16, 6 * 8, 16 },
		"-"
	};
	ProgressBar progressbar {
		{ 18 * 8, 1 * 16, 12 * 8, 16 }
	};
	
	FrequencyField field_frequency {
		{ 0 * 8, 2 * 16 },
	};
	LNAGainField field_lna {
		{ 14 * 8, 2 * 16 }
	};
	RFAmpField field_rf_amp {
		{ 19 * 8, 2 * 16 }
	};
	Checkbox check_loop {
		{ 21 * 8, 2 * 16 },
		4,
		"Loop",
		true
	};
	ImageButton button_play {
		{ 28 * 8, 2 * 16, 2 * 8, 1 * 16 },
		&bitmap_play,
		Color::green(),
		Color::black()
	};

	spectrum::WaterfallWidget waterfall { };

	MessageHandlerRegistration message_handler_replay_thread_error {
		Message::ID::ReplayThreadDone,
		[this](const Message* const p) {
			const auto message = *reinterpret_cast<const ReplayThreadDoneMessage*>(p);
			this->handle_replay_thread_done(message.return_code);
		}
	};
	
	MessageHandlerRegistration message_handler_fifo_signal {
		Message::ID::RequestSignal,
		[this](const Message* const p) {
			const auto message = static_cast<const RequestSignalMessage*>(p);
			if (message->signal == RequestSignalMessage::Signal::FillRequest) {
				this->set_ready();
			}
		}
	};
	
	MessageHandlerRegistration message_handler_tx_progress {
		Message::ID::TXProgress,
		[this](const Message* const p) {
			const auto message = *reinterpret_cast<const TXProgressMessage*>(p);
			this->on_tx_progress(message.progress);
		}
	};
};

} /* namespace ui */

#endif/*__GPS_SIM_APP_HPP__*/

proc_gps_sim.cpp


#include "proc_gps_sim.hpp"
#include "sine_table_int8.hpp"
#include "portapack_shared_memory.hpp"

#include "event_m4.hpp"

#include "utility.hpp"

ReplayProcessor::ReplayProcessor() {
	channel_filter_pass_f = taps_200k_decim_1.pass_frequency_normalized * 1000000;	// 162760.416666667
	channel_filter_stop_f = taps_200k_decim_1.stop_frequency_normalized * 1000000;	// 337239.583333333
	
	spectrum_samples = 0;

	channel_spectrum.set_decimation_factor(1);
	
	configured = false;
}

void ReplayProcessor::execute(const buffer_c8_t& buffer) {
	/* 4MHz, 2048 samples */
	
	if (!configured) return;
	
	// File data is in C16 format, we need C8
	// File samplerate is 500kHz, we're at 4MHz
	// iq_buffer can only be 512 C16 samples (RAM limitation)
	// To fill up the 2048-sample C8 buffer, we need:
	// 2048 samples * 2 bytes per sample = 4096 bytes
	// Since we're oversampling by 4M/500k = 8, we only need 2048/8 = 256 samples from the file and duplicate them 8 times each
	// So 256 * 4 bytes per sample (C16) = 1024 bytes from the file
	if( stream ) {                             //sizeof(*buffer.p) = sizeof(C8) = 2*int8 = 2 bytes //buffer.count = 2048
		const size_t bytes_to_read = sizeof(*buffer.p) * 1 * (buffer.count );	// *2 (C16), /8 (oversampling) should be == 1024
		bytes_read += stream->read(iq_buffer.p, bytes_to_read);
	}
	
	// Fill and "stretch"
	for (size_t i = 0; i < buffer.count; i++) {
		/*if (i & 3) {
			buffer.p[i] = buffer.p[i - 1];
		} else {
			auto re_out = iq_buffer.p[i >> 3].real() ;
			auto im_out = iq_buffer.p[i >> 3].imag() ;
			buffer.p[i] = { (int8_t)re_out, (int8_t)im_out };
		}*/
                /*
                if (i % 8 != 0) {
			buffer.p[i] = buffer.p[i - 1];
		} else {
			auto re_out = iq_buffer.p[i/8].real() ;
			auto im_out = iq_buffer.p[i/8].imag() ;
			buffer.p[i] = { (int8_t)re_out, (int8_t)im_out };
		}*/
                
                auto re_out = iq_buffer.p[i].real() ;
	        auto im_out = iq_buffer.p[i].imag() ;
		buffer.p[i] = { (int8_t)re_out, (int8_t)im_out };
	}
	
	spectrum_samples += buffer.count;
	if( spectrum_samples >= spectrum_interval_samples ) {
		spectrum_samples -= spectrum_interval_samples;
		//channel_spectrum.feed(iq_buffer, channel_filter_pass_f, channel_filter_stop_f);
		
		txprogress_message.progress = bytes_read;	// Inform UI about progress
		txprogress_message.done = false;
		shared_memory.application_queue.push(txprogress_message);
	}
}

void ReplayProcessor::on_message(const Message* const message) {
	switch(message->id) {
	case Message::ID::UpdateSpectrum:
	case Message::ID::SpectrumStreamingConfig:
		channel_spectrum.on_message(message);
		break;

	case Message::ID::SamplerateConfig:
		samplerate_config(*reinterpret_cast<const SamplerateConfigMessage*>(message));
		break;
	
	case Message::ID::ReplayConfig:
		configured = false;
		bytes_read = 0;
		replay_config(*reinterpret_cast<const ReplayConfigMessage*>(message));
		break;
		
	// App has prefilled the buffers, we're ready to go now
	case Message::ID::FIFOData:
		configured = true;
		break;

	default:
		break;
	}
}

void ReplayProcessor::samplerate_config(const SamplerateConfigMessage& message) {
	baseband_fs = message.sample_rate;
	baseband_thread.set_sampling_rate(baseband_fs);
	spectrum_interval_samples = baseband_fs / spectrum_rate_hz;
}

void ReplayProcessor::replay_config(const ReplayConfigMessage& message) {
	if( message.config ) {
		
		stream = std::make_unique<StreamOutput>(message.config);
		
		// Tell application that the buffers and FIFO pointers are ready, prefill
		shared_memory.application_queue.push(sig_message);
	} else {
		stream.reset();
	}
}

int main() {
	EventDispatcher event_dispatcher { std::make_unique<ReplayProcessor>() };
	event_dispatcher.run();
	return 0;
}

proc_gps_sim.hpp


#ifndef __PROC_GPS_SIM_HPP__
#define __PROC_GPS_SIM_HPP__

#include "baseband_processor.hpp"
#include "baseband_thread.hpp"

#include "spectrum_collector.hpp"

#include "stream_output.hpp"

#include <array>
#include <memory>

class ReplayProcessor : public BasebandProcessor {
public:
	ReplayProcessor();

	void execute(const buffer_c8_t& buffer) override;

	void on_message(const Message* const message) override;

private:
	size_t baseband_fs = 0;
	static constexpr auto spectrum_rate_hz = 50.0f;

	BasebandThread baseband_thread { baseband_fs, this, NORMALPRIO + 20, baseband::Direction::Transmit };

	std::array<complex8_t, 2048> iq { };
	const buffer_c8_t iq_buffer {
		iq.data(),
		iq.size(),
		baseband_fs 
	};
	
	uint32_t channel_filter_pass_f = 0;
	uint32_t channel_filter_stop_f = 0;

	std::unique_ptr<StreamOutput> stream { };

	SpectrumCollector channel_spectrum { };
	size_t spectrum_interval_samples = 0;
	size_t spectrum_samples = 0;
	
	bool configured { false };
	uint32_t bytes_read { 0 };

	void samplerate_config(const SamplerateConfigMessage& message);
	void replay_config(const ReplayConfigMessage& message);
	
	TXProgressMessage txprogress_message { };
	RequestSignalMessage sig_message { RequestSignalMessage::Signal::FillRequest };
};

#endif/*__PROC_GPS_SIM_HPP__*/

最后还有个关系不大的,除了生成固定采样点,还可以生成一段轨迹,然后用portapack发射出去下面是根据circle.csv轨迹生成的iq数据。

./gps-sdr-sim -e brdc3540.14n -u circle.csv -b 8 -s 2000000

轨迹文件最大支持300秒的长度,8bit 2MHz采样率,大小是1.2GB文件。我测试了手机和gnss-sdr都能锁定,能看到位置在变化。

猜你喜欢

转载自blog.csdn.net/shukebeta008/article/details/104311290