diff --git a/Doxyfile.in b/Doxyfile.in index 98761f3ce..ae6dc49cc 100644 --- a/Doxyfile.in +++ b/Doxyfile.in @@ -8,6 +8,7 @@ INPUT = src-core/common/ccsds \ src-core/projection \ src-core/dsp \ src-core/image \ + src-core/utils \ docs/pages EXCLUDE = src-core/image/font_lib src-core/image/font RECURSIVE = YES diff --git a/plugins/analog_support/noaa_apt/module_noaa_apt_decoder.cpp b/plugins/analog_support/noaa_apt/module_noaa_apt_decoder.cpp index ba84fcbaf..b1af4532d 100644 --- a/plugins/analog_support/noaa_apt/module_noaa_apt_decoder.cpp +++ b/plugins/analog_support/noaa_apt/module_noaa_apt_decoder.cpp @@ -8,6 +8,7 @@ #include "image/io.h" #include "image/processing.h" #include "common/tracking/tle.h" +#include "utils/stats.h" #include "common/dsp/filter/firdes.h" #include "core/resources.h" @@ -1137,7 +1138,7 @@ namespace noaa_apt for (int y = 0; y < 8; y++) vals.push_back(wedge.get((wed.start_line + c * 8 + y) * wedge.width() + x)); - double mean = avg_overflowless(vals); + double mean = satdump::avg_overflowless(vals); double variance = 0; for (double &val : vals) variance += (val - mean) * (val - mean); diff --git a/plugins/analog_support/sstv/lineproc.h b/plugins/analog_support/sstv/lineproc.h index 7b25a49ba..deba993e5 100644 --- a/plugins/analog_support/sstv/lineproc.h +++ b/plugins/analog_support/sstv/lineproc.h @@ -1,7 +1,7 @@ #pragma once #include "image/image.h" -#include "common/utils.h" +#include "utils/stats.h" #include "core/exception.h" #include "logger.h" #include "nlohmann/json.hpp" @@ -108,7 +108,7 @@ namespace sstv // color_sync += newimg_sync.get(line * line_length + p_t) / 255.0; colrsync_wip.push_back(line[p_t]); } - color_sync = get_median(colrsync_wip); // /= color_sync_length; + color_sync = satdump::get_median(colrsync_wip); // /= color_sync_length; bool color_sync_v = color_sync > 0.5; diff --git a/plugins/aws_support/aws/module_aws_instruments.cpp b/plugins/aws_support/aws/module_aws_instruments.cpp index c68c1d836..b325a75ed 100644 --- a/plugins/aws_support/aws/module_aws_instruments.cpp +++ b/plugins/aws_support/aws/module_aws_instruments.cpp @@ -10,6 +10,7 @@ #include "products2/dataset.h" #include "core/resources.h" #include "nlohmann/json_utils.h" +#include "utils/stats.h" #include "common/tracking/tle.h" @@ -80,7 +81,7 @@ namespace aws data_in.close(); - int scid = most_common(aws_scids.begin(), aws_scids.end(), 0); + int scid = satdump::most_common(aws_scids.begin(), aws_scids.end(), 0); aws_scids.clear(); std::string sat_name = "Unknown AWS"; @@ -94,9 +95,9 @@ namespace aws // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = sat_name; - dataset.timestamp = get_median(mwr_reader.timestamps); + dataset.timestamp = satdump::get_median(mwr_reader.timestamps); if (dataset.timestamp == -1) - dataset.timestamp = get_median(mwr_dump_reader.timestamps); + dataset.timestamp = satdump::get_median(mwr_dump_reader.timestamps); std::optional satellite_tle = satdump::general_tle_registry->get_from_norad_time(norad, dataset.timestamp); diff --git a/plugins/earthcare_support/earthcare/module_earthcare_instruments.cpp b/plugins/earthcare_support/earthcare/module_earthcare_instruments.cpp index e6ce7f08e..3e4d6525f 100644 --- a/plugins/earthcare_support/earthcare/module_earthcare_instruments.cpp +++ b/plugins/earthcare_support/earthcare/module_earthcare_instruments.cpp @@ -11,6 +11,7 @@ #include "nlohmann/json_utils.h" #include "core/resources.h" #include "common/tracking/tle.h" +#include "utils/stats.h" #include "image/io.h" @@ -89,7 +90,7 @@ namespace earthcare // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = "EarthCARE"; - dataset.timestamp = get_median(msi_reader.timestamps); + dataset.timestamp = satdump::get_median(msi_reader.timestamps); int norad = 59908; diff --git a/plugins/elektro_arktika_support/elektro_arktika/instruments/msugs/module_msugs.cpp b/plugins/elektro_arktika_support/elektro_arktika/instruments/msugs/module_msugs.cpp index 6ef601b49..936be8cce 100644 --- a/plugins/elektro_arktika_support/elektro_arktika/instruments/msugs/module_msugs.cpp +++ b/plugins/elektro_arktika_support/elektro_arktika/instruments/msugs/module_msugs.cpp @@ -6,6 +6,7 @@ #include "common/utils.h" #include "common/simple_deframer.h" #include "image/io.h" +#include "utils/stats.h" #include "products2/image_product.h" #include "products2/dataset.h" @@ -109,7 +110,7 @@ namespace elektro_arktika // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = sat_name; - dataset.timestamp = get_median(vis1_reader.timestamps); + dataset.timestamp = satdump::get_median(vis1_reader.timestamps); logger->info("----------- MSU-GS"); logger->info("MSU-GS CH1 Lines : " + std::to_string(vis1_reader.frames)); diff --git a/plugins/elektro_arktika_support/elektro_arktika/lrit/module_elektro_lrit_data_decoder_proc.cpp b/plugins/elektro_arktika_support/elektro_arktika/lrit/module_elektro_lrit_data_decoder_proc.cpp index ec94500db..76e40019c 100644 --- a/plugins/elektro_arktika_support/elektro_arktika/lrit/module_elektro_lrit_data_decoder_proc.cpp +++ b/plugins/elektro_arktika_support/elektro_arktika/lrit/module_elektro_lrit_data_decoder_proc.cpp @@ -7,6 +7,7 @@ #include "DecompWT/CompressWT.h" #include "DecompWT/CompressT4.h" #include "image/io.h" +#include "utils/string.h" namespace elektro { @@ -193,7 +194,7 @@ namespace elektro { SegmentIdentificationHeader segment_id_header = file.getHeader(); - std::vector header_parts = splitString(current_filename, '_'); + std::vector header_parts = satdump::splitString(current_filename, '_'); // for (std::string part : header_parts) // logger->trace(part); diff --git a/plugins/eos_support/eos/instruments/modis/calibrator/modis_calibrator_temps.cpp b/plugins/eos_support/eos/instruments/modis/calibrator/modis_calibrator_temps.cpp index 2f6c562cb..12958c529 100644 --- a/plugins/eos_support/eos/instruments/modis/calibrator/modis_calibrator_temps.cpp +++ b/plugins/eos_support/eos/instruments/modis/calibrator/modis_calibrator_temps.cpp @@ -3,7 +3,7 @@ #include "modis_engcoefs.h" #include "modis_defs.h" #include "logger.h" -#include "common/utils.h" +#include "utils/stats.h" namespace eos { @@ -26,7 +26,7 @@ namespace eos if (d_vars[scan2].contains("bb_temp")) v_DN.push_back(d_vars[scan2]["bb_temp"][thermistor]); - int mDN = most_common(v_DN.begin(), v_DN.end(), 0); + int mDN = satdump::most_common(v_DN.begin(), v_DN.end(), 0); if (abs(DN - mDN) > 200) DN = mDN; #endif @@ -97,7 +97,7 @@ namespace eos if (d_vars[scan2].contains("mir_temp")) v_MIR.push_back(d_vars[scan2]["mir_temp"][i]); - int mMIR = most_common(v_MIR.begin(), v_MIR.end(), 0); + int mMIR = satdump::most_common(v_MIR.begin(), v_MIR.end(), 0); if (abs(MIR - mMIR) > 200) MIR = mMIR; #endif @@ -188,7 +188,7 @@ namespace eos if (d_vars[scan2].contains("inst_temp") && d_vars[scan2]["inst_temp"][i] != 0) v_INS.push_back(d_vars[scan2]["inst_temp"][i]); - int mINS = v_INS.size() == 0 ? 0 : most_common(v_INS.begin(), v_INS.end(), 0); + int mINS = v_INS.size() == 0 ? 0 : satdump::most_common(v_INS.begin(), v_INS.end(), 0); if (mINS != 0 && abs(INS - mINS) > 200) INS = mINS; #endif @@ -243,10 +243,10 @@ namespace eos v_LWHTR_ON.push_back(d_vars[scan2]["fp_temp_info"][2]); v_SMHTR_ON.push_back(d_vars[scan2]["fp_temp_info"][3]); } - bool FP_T1SET = most_common(v_FP_T1SET.begin(), v_FP_T1SET.end(), 0); - bool FP_T3SET = most_common(v_FP_T3SET.begin(), v_FP_T3SET.end(), 0); - bool LWHTR_ON = most_common(v_LWHTR_ON.begin(), v_LWHTR_ON.end(), 0); - bool SMHTR_ON = most_common(v_SMHTR_ON.begin(), v_SMHTR_ON.end(), 0); + bool FP_T1SET = satdump::most_common(v_FP_T1SET.begin(), v_FP_T1SET.end(), 0); + bool FP_T3SET = satdump::most_common(v_FP_T3SET.begin(), v_FP_T3SET.end(), 0); + bool LWHTR_ON = satdump::most_common(v_LWHTR_ON.begin(), v_LWHTR_ON.end(), 0); + bool SMHTR_ON = satdump::most_common(v_SMHTR_ON.begin(), v_SMHTR_ON.end(), 0); #else bool FP_T1SET = d_vars[scan]["fp_temp_info"][0]; bool FP_T3SET = d_vars[scan]["fp_temp_info"][1]; @@ -270,10 +270,10 @@ namespace eos v_FP4.push_back(d_vars[scan2]["fp_temp"][3]); } - int mFP1 = most_common(v_FP1.begin(), v_FP1.end(), 0); - int mFP2 = most_common(v_FP2.begin(), v_FP2.end(), 0); - int mFP3 = most_common(v_FP3.begin(), v_FP3.end(), 0); - int mFP4 = most_common(v_FP4.begin(), v_FP4.end(), 0); + int mFP1 = satdump::most_common(v_FP1.begin(), v_FP1.end(), 0); + int mFP2 = satdump::most_common(v_FP2.begin(), v_FP2.end(), 0); + int mFP3 = satdump::most_common(v_FP3.begin(), v_FP3.end(), 0); + int mFP4 = satdump::most_common(v_FP4.begin(), v_FP4.end(), 0); if (FP1 == 0 || FP1 == 4095 || abs(FP1 - mFP1) > 200) FP1 = mFP1; diff --git a/plugins/eos_support/eos/module_eos_instruments.cpp b/plugins/eos_support/eos/module_eos_instruments.cpp index eebbcd0c8..21288fb93 100644 --- a/plugins/eos_support/eos/module_eos_instruments.cpp +++ b/plugins/eos_support/eos/module_eos_instruments.cpp @@ -167,7 +167,7 @@ namespace eos dataset.satellite_name = "Aura"; if (d_satellite == AQUA || d_satellite == TERRA) // MODIS - dataset.timestamp = get_median(modis_reader.timestamps_1000); + dataset.timestamp = satdump::get_median(modis_reader.timestamps_1000); else dataset.timestamp = time(0); diff --git a/plugins/fengyun2_support/fengyun2/svissr/module_svissr_image_decoder.cpp b/plugins/fengyun2_support/fengyun2/svissr/module_svissr_image_decoder.cpp index bd67e40cd..7ef69d673 100644 --- a/plugins/fengyun2_support/fengyun2/svissr/module_svissr_image_decoder.cpp +++ b/plugins/fengyun2_support/fengyun2/svissr/module_svissr_image_decoder.cpp @@ -7,6 +7,7 @@ #include "logger.h" #include "core/resources.h" #include +#include "utils/stats.h" #define FRAME_SIZE 44356 @@ -236,7 +237,7 @@ namespace fengyun_svissr // std::cout << counter << std::endl; // Try to detect a new scan - uint8_t is_back = most_common(&last_status[0], &last_status[20], 0); + uint8_t is_back = satdump::most_common(&last_status[0], &last_status[20], 0); // Ensures the counter doesn't lock during rollback // Situation: @@ -263,7 +264,7 @@ namespace fengyun_svissr buffer->image4 = vissrImageReader.getImageIR4(); buffer->image5 = vissrImageReader.getImageVIS(); - buffer->scid = most_common(scid_stats.begin(), scid_stats.end(), 0); + buffer->scid = satdump::most_common(scid_stats.begin(), scid_stats.end(), 0); scid_stats.clear(); buffer->timestamp = time(0); @@ -326,7 +327,7 @@ namespace fengyun_svissr buffer->image4 = vissrImageReader.getImageIR4(); buffer->image5 = vissrImageReader.getImageVIS(); - buffer->scid = most_common(scid_stats.begin(), scid_stats.end(), 0); + buffer->scid = satdump::most_common(scid_stats.begin(), scid_stats.end(), 0); scid_stats.clear(); buffer->timestamp = time(0); @@ -353,7 +354,7 @@ namespace fengyun_svissr buffer->image4 = vissrImageReader.getImageIR4(); buffer->image5 = vissrImageReader.getImageVIS(); - buffer->scid = most_common(scid_stats.begin(), scid_stats.end(), 0); + buffer->scid = satdump::most_common(scid_stats.begin(), scid_stats.end(), 0); scid_stats.clear(); buffer->timestamp = time(0); diff --git a/plugins/fengyun3_support/fengyun3/module_fy3_instruments.cpp b/plugins/fengyun3_support/fengyun3/module_fy3_instruments.cpp index af8de0a54..e5189b33d 100644 --- a/plugins/fengyun3_support/fengyun3/module_fy3_instruments.cpp +++ b/plugins/fengyun3_support/fengyun3/module_fy3_instruments.cpp @@ -18,6 +18,7 @@ #include "core/exception.h" #include "image/io.h" #include "common/tracking/tle.h" +#include "utils/stats.h" namespace fengyun3 { @@ -435,7 +436,7 @@ namespace fengyun3 if (d_dump_mersi) mersi_bin.close(); - int scid = most_common(fy_scids.begin(), fy_scids.end(), 0); + int scid = satdump::most_common(fy_scids.begin(), fy_scids.end(), 0); fy_scids.clear(); std::string sat_name = "Unknown FengYun-3"; @@ -474,17 +475,17 @@ namespace fengyun3 satdump::products::DataSet dataset; dataset.satellite_name = sat_name; if ((d_satellite == FY_AB || d_satellite == FY_3C) && d_downlink == AHRPT) - dataset.timestamp = get_median(virr_reader.timestamps); + dataset.timestamp = satdump::get_median(virr_reader.timestamps); else if (d_satellite == FY_AB && d_downlink == MPT) - dataset.timestamp = get_median(mersi1_reader.timestamps); + dataset.timestamp = satdump::get_median(mersi1_reader.timestamps); else if (d_satellite == FY_3D) - dataset.timestamp = get_median(mersi2_reader.timestamps); + dataset.timestamp = satdump::get_median(mersi2_reader.timestamps); else if (d_satellite == FY_3E) - dataset.timestamp = get_median(mersill_reader.timestamps); + dataset.timestamp = satdump::get_median(mersill_reader.timestamps); else if (d_satellite == FY_3F) - dataset.timestamp = get_median(mersi3_reader.timestamps); + dataset.timestamp = satdump::get_median(mersi3_reader.timestamps); else if (d_satellite == FY_3G) - dataset.timestamp = get_median(mersirm_reader.timestamps); + dataset.timestamp = satdump::get_median(mersirm_reader.timestamps); std::optional satellite_tle = satdump::general_tle_registry->get_from_norad_time(norad, dataset.timestamp); @@ -599,12 +600,12 @@ namespace fengyun3 if (d_write_c10) { - virr_to_c10->close(get_median(virr_reader.timestamps), scid); + virr_to_c10->close(satdump::get_median(virr_reader.timestamps), scid); delete virr_to_c10; } if (d_downlink == AHRPT) - dataset.timestamp = get_median(virr_reader.timestamps); // Re-set dataset timestamp since we just adjusted it + dataset.timestamp = satdump::get_median(virr_reader.timestamps); // Re-set dataset timestamp since we just adjusted it virr_products.save(directory); dataset.products_list.push_back("VIRR"); diff --git a/plugins/fengyun4_support/fy4/module_fy4_lrit_data_decoder_proc.cpp b/plugins/fengyun4_support/fy4/module_fy4_lrit_data_decoder_proc.cpp index 6ad7370fd..402fd9c6a 100644 --- a/plugins/fengyun4_support/fy4/module_fy4_lrit_data_decoder_proc.cpp +++ b/plugins/fengyun4_support/fy4/module_fy4_lrit_data_decoder_proc.cpp @@ -7,6 +7,7 @@ #include "image/j2k_utils.h" #include #include "image/io.h" +#include "utils/string.h" namespace fy4 { @@ -46,7 +47,7 @@ namespace fy4 { if (primary_header.file_type_code == 0 && file.hasHeader()) { - std::vector header_parts = splitString(current_filename, '_'); + std::vector header_parts = satdump::splitString(current_filename, '_'); // for (std::string part : header_parts) // logger->trace(part); diff --git a/plugins/geonetcast_support/geonetcast/module_geonetcast_decoder.cpp b/plugins/geonetcast_support/geonetcast/module_geonetcast_decoder.cpp index 59fa0384f..b19988e40 100644 --- a/plugins/geonetcast_support/geonetcast/module_geonetcast_decoder.cpp +++ b/plugins/geonetcast_support/geonetcast/module_geonetcast_decoder.cpp @@ -14,7 +14,7 @@ #include "goes_abi.h" -#include "common/thread_priority.h" +#include "utils/thread_priority.h" namespace geonetcast { diff --git a/plugins/gk2a_support/gk2a/module_gk2a_lrit_data_decoder.cpp b/plugins/gk2a_support/gk2a/module_gk2a_lrit_data_decoder.cpp index 66397c6da..f27bd2d3a 100644 --- a/plugins/gk2a_support/gk2a/module_gk2a_lrit_data_decoder.cpp +++ b/plugins/gk2a_support/gk2a/module_gk2a_lrit_data_decoder.cpp @@ -12,6 +12,7 @@ #include "libs/miniz/miniz.h" #include "libs/miniz/miniz_zip.h" #include "init.h" +#include "utils/http.h" namespace gk2a { @@ -90,7 +91,7 @@ namespace gk2a // Try to download std::string download_url = "http://web.archive.org/web/20210502102522if_/http://nmsc.kma.go.kr/resources/enhome/resources/satellites/coms/COMS_Decryption_Sample_Cpp.zip"; std::string file_data; - if (!perform_http_request(download_url, file_data)) + if (!satdump::perform_http_request(download_url, file_data)) { logger->info("Downloaded COMS Decryption sample! Decompressing..."); diff --git a/plugins/gk2a_support/gk2a/module_gk2a_lrit_data_decoder_proc.cpp b/plugins/gk2a_support/gk2a/module_gk2a_lrit_data_decoder_proc.cpp index bb763ca32..5a5c6583f 100644 --- a/plugins/gk2a_support/gk2a/module_gk2a_lrit_data_decoder_proc.cpp +++ b/plugins/gk2a_support/gk2a/module_gk2a_lrit_data_decoder_proc.cpp @@ -7,6 +7,7 @@ #include "image/io.h" #include "imgui/imgui_image.h" #include +#include "utils/string.h" extern "C" { @@ -117,7 +118,7 @@ namespace gk2a file.lrit_data.insert(file.lrit_data.end(), (uint8_t *)img.raw_data(), (uint8_t *)img.raw_data() + img.size() * img.typesize()); } - std::vector header_parts = splitString(current_filename, '_'); // Is this a FD? + std::vector header_parts = satdump::splitString(current_filename, '_'); // Is this a FD? if (header_parts.size() < 2) header_parts = {"", ""}; @@ -186,7 +187,7 @@ namespace gk2a segmentedDecoder.meta = lmeta; } - std::vector header_parts = splitString(orig_filename, '_'); + std::vector header_parts = satdump::splitString(orig_filename, '_'); int seg_number = 0; if (header_parts.size() >= 7) @@ -233,7 +234,7 @@ namespace gk2a int offset = primary_header.total_header_length; - std::vector header_parts = splitString(current_filename, '_'); + std::vector header_parts = satdump::splitString(current_filename, '_'); // Get type name std::string name = ""; diff --git a/plugins/goes_support/goes/gvar/module_gvar_image_decoder.cpp b/plugins/goes_support/goes/gvar/module_gvar_image_decoder.cpp index 872e023de..0218bfd4e 100644 --- a/plugins/goes_support/goes/gvar/module_gvar_image_decoder.cpp +++ b/plugins/goes_support/goes/gvar/module_gvar_image_decoder.cpp @@ -1,11 +1,11 @@ #include "module_gvar_image_decoder.h" -#include "image/io.h" #include "common/physics_constants.h" -#include "common/thread_priority.h" #include "common/utils.h" #include "core/config.h" +#include "core/resources.h" #include "crc_table.h" #include "gvar_headers.h" +#include "image/io.h" #include "imgui/imgui.h" #include "imgui/imgui_image.h" #include "logger.h" @@ -14,9 +14,9 @@ #include "products2/image_product.h" #include "products2/product.h" #include "products2/product_process.h" -#include "core/resources.h" +#include "utils/thread_priority.h" #include -#include +#include "utils/stats.h" #define FRAME_SIZE 32786 @@ -197,7 +197,7 @@ namespace goes if (block_zero_timestamps.size() > 0) { logger->debug("Using time from satellite info block"); - image_time = most_common(block_zero_timestamps.begin(), block_zero_timestamps.end(), 0); + image_time = satdump::most_common(block_zero_timestamps.begin(), block_zero_timestamps.end(), 0); } // There were no valid Block 0s received, use fallback else @@ -211,13 +211,13 @@ namespace goes { logger->debug("Using image size from satellite info block"); - img_size_x = most_common(block_zero_x_size.begin(), block_zero_x_size.end(), 0); - img_size_y = most_common(block_zero_y_size.begin(), block_zero_y_size.end(), 0); + img_size_x = satdump::most_common(block_zero_x_size.begin(), block_zero_x_size.end(), 0); + img_size_y = satdump::most_common(block_zero_y_size.begin(), block_zero_y_size.end(), 0); - img_off_x = most_common(block_zero_x_offset.begin(), block_zero_x_offset.end(), -1); - img_off_y = most_common(block_zero_y_offset.begin(), block_zero_y_offset.end(), -1); + img_off_x = satdump::most_common(block_zero_x_offset.begin(), block_zero_x_offset.end(), -1); + img_off_y = satdump::most_common(block_zero_y_offset.begin(), block_zero_y_offset.end(), -1); - subsat_lon = most_common(block_zero_subsat_lon.begin(), block_zero_subsat_lon.end(), 0) / 1000.0; + subsat_lon = satdump::most_common(block_zero_subsat_lon.begin(), block_zero_subsat_lon.end(), 0) / 1000.0; } else { @@ -234,7 +234,7 @@ namespace goes isSavingInProgress = true; imageVectorMutex.lock(); imagesVector.push_back({infraredImageReader1.getImage1(), infraredImageReader1.getImage2(), infraredImageReader2.getImage1(), infraredImageReader2.getImage2(), - visibleImageReader.getImage(), most_common(scid_stats.begin(), scid_stats.end(), 0), img_size_x, img_size_y, image_time, img_off_x, img_off_y, subsat_lon}); + visibleImageReader.getImage(), satdump::most_common(scid_stats.begin(), scid_stats.end(), 0), img_size_x, img_size_y, image_time, img_off_x, img_off_y, subsat_lon}); imageVectorMutex.unlock(); isSavingInProgress = false; } @@ -248,7 +248,7 @@ namespace goes infraredImageReader2.getImage1(), infraredImageReader2.getImage2(), visibleImageReader.getImage(), - most_common(scid_stats.begin(), scid_stats.end(), 0), + satdump::most_common(scid_stats.begin(), scid_stats.end(), 0), img_size_x, // most_common(vis_width_stats.begin(), vis_width_stats.end(), 0), img_size_y, image_time, @@ -370,7 +370,7 @@ namespace goes ir_width_stats.push_back(line_header.word_count &= 0x1fff); // Get current stats - int current_words = most_common(ir_width_stats.begin(), ir_width_stats.end(), 0); + int current_words = satdump::most_common(ir_width_stats.begin(), ir_width_stats.end(), 0); // Safeguard if (current_words > 6565) @@ -619,7 +619,6 @@ namespace goes void GVARImageDecoderModule::writeImagesThread() { logger->info("Started saving thread..."); - setLowestThreadPriority(); while (writeImagesAync) { imageVectorMutex.lock(); @@ -650,7 +649,8 @@ namespace goes if (writeImagesAync) { imageSavingThread = std::thread(&GVARImageDecoderModule::writeImagesThread, this); - setLowestThreadPriority(imageSavingThread); // Low priority to avoid sampledrop + satdump::setLowestThreadPriority(imageSavingThread); // Low priority to avoid sampledrop + // TODOREWORK namespace remove } directory = d_output_file_hint.substr(0, d_output_file_hint.rfind('/')) + "/IMAGE"; diff --git a/plugins/goes_support/goes/hrit/dcs/dcs_decoder.cpp b/plugins/goes_support/goes/hrit/dcs/dcs_decoder.cpp index d61de52c9..b365e6021 100644 --- a/plugins/goes_support/goes/hrit/dcs/dcs_decoder.cpp +++ b/plugins/goes_support/goes/hrit/dcs/dcs_decoder.cpp @@ -3,6 +3,7 @@ #include "dcs_decoder.h" #include "core/config.h" #include "common/utils.h" +#include "utils/http.h" #include "common/lrit/crc_table.h" #include "nlohmann/json_utils.h" #include "logger.h" @@ -42,7 +43,7 @@ namespace goes std::vector pdt_urls = satdump::config::main_cfg["plugin_settings"]["goes_support"]["pdt_urls"]; for (std::string& pdt_url : pdt_urls) { - if (perform_http_request(pdt_url, file_data) == 0) + if (satdump::perform_http_request(pdt_url, file_data) == 0) { std::ofstream save_pdts(satdump::user_path + "/PDTS_COMPRESSED.txt"); save_pdts << file_data; @@ -63,7 +64,7 @@ namespace goes std::vector hads_urls = satdump::config::main_cfg["plugin_settings"]["goes_support"]["hads_urls"]; for (std::string& hads_url : hads_urls) { - if (perform_http_request(hads_url, file_data) == 0) + if (satdump::perform_http_request(hads_url, file_data) == 0) { std::ofstream save_hads(satdump::user_path + "/all_dcp_defs.txt"); save_hads << file_data; diff --git a/plugins/goes_support/goes/hrit/lrit_header.h b/plugins/goes_support/goes/hrit/lrit_header.h index 8c18130fd..fe9c57c9e 100644 --- a/plugins/goes_support/goes/hrit/lrit_header.h +++ b/plugins/goes_support/goes/hrit/lrit_header.h @@ -4,6 +4,7 @@ #include #include #include "common/utils.h" +#include "utils/string.h" namespace goes { @@ -71,11 +72,11 @@ namespace goes // I will admit I needed to peek in goestools to figure that one out // A bit hard without having live data... - std::vector fields = splitString(ancillary_text, ';'); + std::vector fields = satdump::splitString(ancillary_text, ';'); for (std::string &field : fields) { - std::vector values = splitString(field, '='); + std::vector values = satdump::splitString(field, '='); if (values.size() == 2) { values[0] = values[0].substr(0, values[0].find_last_not_of(' ') + 1); diff --git a/plugins/goes_support/goes/hrit/module_goes_lrit_data_decoder_proc.cpp b/plugins/goes_support/goes/hrit/module_goes_lrit_data_decoder_proc.cpp index 7b533f414..509f8735b 100644 --- a/plugins/goes_support/goes/hrit/module_goes_lrit_data_decoder_proc.cpp +++ b/plugins/goes_support/goes/hrit/module_goes_lrit_data_decoder_proc.cpp @@ -7,6 +7,7 @@ #include #include "image/io.h" #include "image/processing.h" +#include "utils/string.h" namespace goes { @@ -147,7 +148,7 @@ namespace goes { lmeta.satellite_name = "GOES-" + std::to_string(noaa_header.product_id); lmeta.satellite_short_name = "G" + std::to_string(noaa_header.product_id); - std::vector cutFilename = splitString(current_filename, '-'); + std::vector cutFilename = satdump::splitString(current_filename, '-'); if (cutFilename.size() >= 4) { @@ -292,7 +293,7 @@ namespace goes // Apparently the timestamp is in there for Himawari-8 data AnnotationRecord annotation_record = file.getHeader(); - std::vector strParts = splitString(annotation_record.annotation_text, '_'); + std::vector strParts = satdump::splitString(annotation_record.annotation_text, '_'); if (strParts.size() > 3) { strptime(strParts[2].c_str(), "%Y%m%d%H%M", timeReadable); diff --git a/plugins/goes_support/goes/sd/sd_imager_reader.cpp b/plugins/goes_support/goes/sd/sd_imager_reader.cpp index aeafeaae7..4f9d9ef78 100644 --- a/plugins/goes_support/goes/sd/sd_imager_reader.cpp +++ b/plugins/goes_support/goes/sd/sd_imager_reader.cpp @@ -6,6 +6,7 @@ #include "image/io.h" #include "image/processing.h" #include +#include "utils/stats.h" #define IMG_WIDTH 40000 @@ -25,7 +26,7 @@ namespace goes memmove(last_status, &last_status[1], (FULL_BUF_SZ - 1) * sizeof(uint16_t)); last_status[FULL_BUF_SZ - 1] = type; - uint16_t last_types = most_common(&last_status[0], &last_status[FULL_BUF_SZ], 0); + uint16_t last_types = satdump::most_common(&last_status[0], &last_status[FULL_BUF_SZ], 0); //std::cout< 10) diff --git a/plugins/jason3_support/jason3/module_jason3_instruments.cpp b/plugins/jason3_support/jason3/module_jason3_instruments.cpp index 08fe2e923..fbd6f8a51 100644 --- a/plugins/jason3_support/jason3/module_jason3_instruments.cpp +++ b/plugins/jason3_support/jason3/module_jason3_instruments.cpp @@ -7,6 +7,7 @@ #include "common/utils.h" #include "common/ccsds/ccsds_tm/demuxer.h" #include "image/io.h" +#include "utils/stats.h" #include @@ -90,7 +91,7 @@ namespace jason3 // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = "Jason-3"; - dataset.timestamp = get_median(amr2_reader.timestamps); + dataset.timestamp = satdump::get_median(amr2_reader.timestamps); std::optional satellite_tle = satdump::general_tle_registry->get_from_norad_time(41240, dataset.timestamp); diff --git a/plugins/jpss_support/jpss/module_jpss_instruments.cpp b/plugins/jpss_support/jpss/module_jpss_instruments.cpp index 8d27ff81c..3bcd6ea45 100644 --- a/plugins/jpss_support/jpss/module_jpss_instruments.cpp +++ b/plugins/jpss_support/jpss/module_jpss_instruments.cpp @@ -17,6 +17,7 @@ #include "products2/image_product.h" #include "products2/dataset.h" #include "common/tracking/tle.h" +#include "utils/stats.h" namespace jpss { @@ -140,7 +141,7 @@ namespace jpss data_in.close(); - int scid = most_common(jpss_scids.begin(), jpss_scids.end(), 0); + int scid = satdump::most_common(jpss_scids.begin(), jpss_scids.end(), 0); jpss_scids.clear(); std::string sat_name = "Unknown JPSS"; @@ -166,7 +167,7 @@ namespace jpss // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = sat_name; - dataset.timestamp = get_median(atms_reader.timestamps); + dataset.timestamp = satdump::get_median(atms_reader.timestamps); std::optional satellite_tle = satdump::general_tle_registry->get_from_norad_time(norad, dataset.timestamp); diff --git a/plugins/meteor_support/meteor/instruments/msumr/lrpt_msumr_reader.cpp b/plugins/meteor_support/meteor/instruments/msumr/lrpt_msumr_reader.cpp index d219447be..e8b1ed936 100644 --- a/plugins/meteor_support/meteor/instruments/msumr/lrpt_msumr_reader.cpp +++ b/plugins/meteor_support/meteor/instruments/msumr/lrpt_msumr_reader.cpp @@ -1,6 +1,6 @@ #include "lrpt_msumr_reader.h" #include "logger.h" -#include "common/utils.h" +#include "utils/stats.h" #include #include @@ -240,7 +240,7 @@ namespace meteor } } - timestamps.push_back(most_common(line_timestamps.begin(), line_timestamps.end(), -1.0)); + timestamps.push_back(satdump::most_common(line_timestamps.begin(), line_timestamps.end(), -1.0)); } // Fill missing data, if requested diff --git a/plugins/meteor_support/meteor/instruments/msumr/module_meteor_msumr_lrpt.cpp b/plugins/meteor_support/meteor/instruments/msumr/module_meteor_msumr_lrpt.cpp index 508a7a925..661299711 100644 --- a/plugins/meteor_support/meteor/instruments/msumr/module_meteor_msumr_lrpt.cpp +++ b/plugins/meteor_support/meteor/instruments/msumr/module_meteor_msumr_lrpt.cpp @@ -17,6 +17,7 @@ #include #include #include +#include "utils/stats.h" #define BUFFER_SIZE 8192 @@ -200,7 +201,7 @@ namespace meteor logger->info("Writing images.... (Can take a while)"); // Identify satellite, and apply per-sat settings... - int msumr_serial_number = most_common(msumr_ids.begin(), msumr_ids.end(), -1); + int msumr_serial_number = satdump::most_common(msumr_ids.begin(), msumr_ids.end(), -1); msumr_ids.clear(); logger->trace("MSU-MR ID %d", msumr_serial_number); @@ -310,14 +311,14 @@ namespace meteor } msumr_products.images.swap(msumr_images); - createMSUMRProduct(msumr_products, get_median(msureader.timestamps), norad, msumr_serial_number, calib_cfg, lrpt_channels, msureader.timestamps, sat_name); + createMSUMRProduct(msumr_products, satdump::get_median(msureader.timestamps), norad, msumr_serial_number, calib_cfg, lrpt_channels, msureader.timestamps, sat_name); msumr_products.save(directory); msumr_products.images.clear(); // Free up memory // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = sat_name; - dataset.timestamp = get_median(msureader.timestamps); + dataset.timestamp = satdump::get_median(msureader.timestamps); dataset.products_list.push_back("MSU-MR"); if (d_parameters.contains("fill_missing") && d_parameters["fill_missing"]) @@ -373,7 +374,7 @@ namespace meteor if (img.size() > 0) filled_products.images.push_back({i, "MSU-MR-" + std::to_string(i + 1), std::to_string(i + 1), img, 10}); } - createMSUMRProduct(filled_products, get_median(msureader.timestamps), norad, msumr_serial_number, calib_cfg, lrpt_channels, msureader.timestamps, sat_name); + createMSUMRProduct(filled_products, satdump::get_median(msureader.timestamps), norad, msumr_serial_number, calib_cfg, lrpt_channels, msureader.timestamps, sat_name); filled_products.save(fill_directory); dataset.products_list.push_back("MSU-MR (Filled)"); } diff --git a/plugins/meteor_support/meteor/instruments/msumr/msumr_calibrator.h b/plugins/meteor_support/meteor/instruments/msumr/msumr_calibrator.h index 6789f44db..0da47dbf0 100644 --- a/plugins/meteor_support/meteor/instruments/msumr/msumr_calibrator.h +++ b/plugins/meteor_support/meteor/instruments/msumr/msumr_calibrator.h @@ -1,7 +1,7 @@ #pragma once #include "common/calibration.h" -#include "common/utils.h" +#include "utils/stats.h" #include "nlohmann/json.hpp" #include "nlohmann/json_utils.h" #include "products2/image/image_calibrator.h" @@ -99,8 +99,8 @@ namespace meteor hot_temps.push_back(hott); } - auto coldm = most_common(cold_temps.begin(), cold_temps.end(), 0); - auto hotm = most_common(hot_temps.begin(), hot_temps.end(), 0); + auto coldm = satdump::most_common(cold_temps.begin(), cold_temps.end(), 0); + auto hotm = satdump::most_common(hot_temps.begin(), hot_temps.end(), 0); for (int i = 0; i < max_lcnt; i++) { if (abs(coldm - cold_temps[i]) > 5) diff --git a/plugins/meteor_support/meteor/module_meteor_instruments.cpp b/plugins/meteor_support/meteor/module_meteor_instruments.cpp index fbeada86a..d06dd00c4 100644 --- a/plugins/meteor_support/meteor/module_meteor_instruments.cpp +++ b/plugins/meteor_support/meteor/module_meteor_instruments.cpp @@ -12,6 +12,7 @@ #include "core/resources.h" #include "nlohmann/json_utils.h" #include "instruments/msumr/msumr_tlm.h" +#include "utils/stats.h" namespace meteor { @@ -131,7 +132,7 @@ namespace meteor data_in.close(); // Identify satellite, and apply per-sat settings... - int msumr_serial_number = most_common(msumr_ids.begin(), msumr_ids.end(), -1); + int msumr_serial_number = satdump::most_common(msumr_ids.begin(), msumr_ids.end(), -1); msumr_ids.clear(); std::string sat_name = "Unknown Meteor"; @@ -161,7 +162,7 @@ namespace meteor // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = sat_name; - dataset.timestamp = get_median(msumr_timestamps); + dataset.timestamp = satdump::get_median(msumr_timestamps); // Satellite ID { diff --git a/plugins/meteor_support/meteor/module_meteor_xband_instruments.cpp b/plugins/meteor_support/meteor/module_meteor_xband_instruments.cpp index b2dbf178a..6a5caad14 100644 --- a/plugins/meteor_support/meteor/module_meteor_xband_instruments.cpp +++ b/plugins/meteor_support/meteor/module_meteor_xband_instruments.cpp @@ -11,6 +11,8 @@ #include "core/resources.h" #include #include +#include "utils/time.h" +#include "utils/stats.h" namespace meteor { @@ -215,7 +217,7 @@ namespace meteor else if (norad == 59051) offset = 1704067200 - 3600 * 24 - 3600 * 3 - 3600 * 24 * 3107; double timestamp = offset + double(idk_value) * 65536 + double(seconds_value) + double(last_subsecond_cnt) / 16777216.0; - logger->trace("%s - %d", timestamp_to_string(timestamp).c_str(), idk_value); + logger->trace("%s - %d", satdump::timestamp_to_string(timestamp).c_str(), idk_value); timestamps.push_back(timestamp); } else @@ -282,7 +284,7 @@ namespace meteor // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = sat_name; - dataset.timestamp = get_median(timestamps); + dataset.timestamp = satdump::get_median(timestamps); // KMSS1 { diff --git a/plugins/meteosat_support/msg/instruments/seviri/seviri_reader.cpp b/plugins/meteosat_support/msg/instruments/seviri/seviri_reader.cpp index fd7ea35c3..f7ab2eb41 100644 --- a/plugins/meteosat_support/msg/instruments/seviri/seviri_reader.cpp +++ b/plugins/meteosat_support/msg/instruments/seviri/seviri_reader.cpp @@ -1,16 +1,16 @@ #include "seviri_reader.h" -#include "common/repack.h" -#include "common/ccsds/ccsds_time.h" -#include -#include "logger.h" -#include -#include "products2/image_product.h" #include "../../msg.h" -#include "common/utils.h" +#include "common/ccsds/ccsds_time.h" +#include "common/repack.h" +#include "utils/stats.h" +#include "logger.h" +#include "products2/image_product.h" +#include +#include -#include "core/config.h" -#include "common/thread_priority.h" #include "common/tracking/tle.h" +#include "core/config.h" +#include "utils/thread_priority.h" // TODOREWORK BRING BACK #include "products/processor/image_processor.h" namespace lrit @@ -31,8 +31,7 @@ namespace meteosat return double(offset) * 86400.0 + (days * 18.204444444 * 3600.0) + double(milliseconds_of_day) / double(ms_scale) + double(microseconds_of_millisecond) / us_of_ms_scale; } - SEVIRIReader::SEVIRIReader(bool d_mode_is_rss) - : d_mode_is_rss(d_mode_is_rss) + SEVIRIReader::SEVIRIReader(bool d_mode_is_rss) : d_mode_is_rss(d_mode_is_rss) { // Standard resolution channels for (int i = 0; i < 11; i++) @@ -52,8 +51,7 @@ namespace meteosat not_channels_lines = 0; // Automatic composite generation - if (satdump::config::main_cfg["viewer"]["instruments"].contains("seviri") && - satdump::config::main_cfg["satdump_general"]["auto_process_products"]["value"].get()) + if (satdump::config::main_cfg["viewer"]["instruments"].contains("seviri") && satdump::config::main_cfg["satdump_general"]["auto_process_products"]["value"].get()) can_make_composites = true; if (can_make_composites) @@ -95,7 +93,7 @@ namespace meteosat seviri_products->set_product_timestamp(last_timestamp); - int scid = most_common(all_scids.begin(), all_scids.end(), 0); + int scid = satdump::most_common(all_scids.begin(), all_scids.end(), 0); if (scid == METEOSAT_8_SCID) seviri_products->set_product_source("MSG-1"); @@ -124,9 +122,7 @@ namespace meteosat // seviri_products->set_tle(satellite_tle); TODOREWORK? Projection! int ch_offsets[12] = { - 0, - -18, - 18, + 0, -18, 18, 0, // TODO 0, // TODO 0, // TODO @@ -141,11 +137,8 @@ namespace meteosat for (int i = 0; i < 11; i++) { images_nrm[i].mirror(true, true); - seviri_products->images.push_back({i, "SEVIRI-" + std::to_string(i + 1), - std::to_string(i + 1), - images_nrm[i], - 10, - satdump::ChannelTransform().init_affine(3, 3, ch_offsets[i] * 3, 0)}); + seviri_products->images.push_back( + {i, "SEVIRI-" + std::to_string(i + 1), std::to_string(i + 1), images_nrm[i], 10, satdump::ChannelTransform().init_affine(3, 3, ch_offsets[i] * 3, 0)}); images_nrm[i].fill(0); } @@ -185,7 +178,7 @@ namespace meteosat void SEVIRIReader::compositeThreadFunc() { - setLowestThreadPriority(); + satdump::setLowestThreadPriority(); // TODOREWORK namespace remove while (composite_th_should_run) { compo_queue_mtx.lock(); @@ -246,18 +239,9 @@ namespace meteosat if (d_mode_is_rss) { - if (lines_since_last_end++ > 500 && (timeReadable.tm_min == 0 || - timeReadable.tm_min == 5 || - timeReadable.tm_min == 10 || - timeReadable.tm_min == 15 || - timeReadable.tm_min == 20 || - timeReadable.tm_min == 25 || - timeReadable.tm_min == 30 || - timeReadable.tm_min == 35 || - timeReadable.tm_min == 40 || - timeReadable.tm_min == 45 || - timeReadable.tm_min == 50 || - timeReadable.tm_min == 55)) + if (lines_since_last_end++ > 500 && (timeReadable.tm_min == 0 || timeReadable.tm_min == 5 || timeReadable.tm_min == 10 || timeReadable.tm_min == 15 || + timeReadable.tm_min == 20 || timeReadable.tm_min == 25 || timeReadable.tm_min == 30 || timeReadable.tm_min == 35 || + timeReadable.tm_min == 40 || timeReadable.tm_min == 45 || timeReadable.tm_min == 50 || timeReadable.tm_min == 55)) { lines_since_last_end = 0; saveImages(); @@ -273,8 +257,7 @@ namespace meteosat } } - size_t lines = d_mode_is_rss ? (fmod(scan_timestamp, 5 * 60) / (300 / 1494.0)) - : (fmod(scan_timestamp, 15 * 60) / (300 / 1494.0)); + size_t lines = d_mode_is_rss ? (fmod(scan_timestamp, 5 * 60) / (300 / 1494.0)) : (fmod(scan_timestamp, 15 * 60) / (300 / 1494.0)); // Timestamp, somewhat interpolated to have one on all lines, // assuming the scan rate to be right @@ -289,11 +272,7 @@ namespace meteosat for (int c = 0; c < 3; c++) { // Some channels are swapped on the focal plane - bool swap = scan_chunk_number == 3 || - scan_chunk_number == 4 || - scan_chunk_number == 8 || - scan_chunk_number == 9 || - scan_chunk_number == 10; + bool swap = scan_chunk_number == 3 || scan_chunk_number == 4 || scan_chunk_number == 8 || scan_chunk_number == 9 || scan_chunk_number == 10; for (int v = 0; v < 3834; v++) if (lines < images_nrm[scan_chunk_number].height()) images_nrm[scan_chunk_number].set(lines * images_nrm[scan_chunk_number].width() + v, tmp_linebuf_nrm[(swap ? (2 - c) : c) * 3834 + v] << 6); @@ -319,8 +298,7 @@ namespace meteosat uint16_t *tmp_buf = new uint16_t[15000]; repackBytesTo10bits(&pkt.payload[8], pkt.payload.size() - 8, tmp_buf); - size_t lines = d_mode_is_rss ? (fmod(scan_timestamp, 5 * 60) / (100 / 1494.0)) - : fmod(scan_timestamp, 15 * 60) / (100 / 1494.0); + size_t lines = d_mode_is_rss ? (fmod(scan_timestamp, 5 * 60) / (100 / 1494.0)) : fmod(scan_timestamp, 15 * 60) / (100 / 1494.0); lines += (scan_chunk_number - 11) * 2; if (not_channels_lines != lines) @@ -344,8 +322,7 @@ namespace meteosat uint16_t *tmp_buf = new uint16_t[15000]; repackBytesTo10bits(&pkt.payload[8], pkt.payload.size() - 8, tmp_buf); - size_t lines = d_mode_is_rss ? (fmod(scan_timestamp, 5 * 60) / (100 / 1494.0)) - : fmod(scan_timestamp, 15 * 60) / (100 / 1494.0); + size_t lines = d_mode_is_rss ? (fmod(scan_timestamp, 5 * 60) / (100 / 1494.0)) : fmod(scan_timestamp, 15 * 60) / (100 / 1494.0); lines += (scan_chunk_number - 11) * 2; for (int v = 0; v < 5751; v++) @@ -357,5 +334,5 @@ namespace meteosat delete[] tmp_buf; } } - } -} \ No newline at end of file + } // namespace msg +} // namespace meteosat \ No newline at end of file diff --git a/plugins/noaa_metop_support/instruments/mhs/mhs_reader.cpp b/plugins/noaa_metop_support/instruments/mhs/mhs_reader.cpp index 8a720812d..21b56d25a 100644 --- a/plugins/noaa_metop_support/instruments/mhs/mhs_reader.cpp +++ b/plugins/noaa_metop_support/instruments/mhs/mhs_reader.cpp @@ -10,7 +10,7 @@ This decoder takes in raw AIP data and processes it to MHS. It perfprms calibrat #include #include "core/resources.h" #include "nlohmann/json_utils.h" -#include "common/utils.h" +#include "utils/stats.h" #include "common/calibration.h" #include "logger.h" @@ -152,7 +152,7 @@ namespace noaa_metop // calib_out["lua"] = loadFileToString(resources::getResourcePath("calibration/MHS.lua")); calib_out["calibrator"] = "noaa_mhs"; - uint8_t PIE = most_common(PIE_buff.begin(), PIE_buff.end(), 0); + uint8_t PIE = satdump::most_common(PIE_buff.begin(), PIE_buff.end(), 0); PIE_buff.clear(); double a, b; diff --git a/plugins/noaa_metop_support/metop/module_metop_instruments.cpp b/plugins/noaa_metop_support/metop/module_metop_instruments.cpp index a454f88ac..2cec613c1 100644 --- a/plugins/noaa_metop_support/metop/module_metop_instruments.cpp +++ b/plugins/noaa_metop_support/metop/module_metop_instruments.cpp @@ -16,6 +16,7 @@ #include "image/io.h" #include "image/processing.h" #include "common/calibration.h" +#include "utils/stats.h" #include "products2/punctiform_product.h" #include "products2/image_product.h" @@ -153,7 +154,7 @@ namespace metop data_in.close(); - int scid = most_common(metop_scids.begin(), metop_scids.end(), 0); + int scid = satdump::most_common(metop_scids.begin(), metop_scids.end(), 0); metop_scids.clear(); std::string sat_name = "Unknown MetOp"; @@ -175,7 +176,7 @@ namespace metop // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = sat_name; - dataset.timestamp = get_median(avhrr_reader.timestamps); + dataset.timestamp = satdump::get_median(avhrr_reader.timestamps); std::optional satellite_tle = admin_msg_reader.tles.get_from_norad(norad); if (!satellite_tle.has_value() || ignore_integrated_tle) diff --git a/plugins/noaa_metop_support/noaa/module_noaa_instruments.cpp b/plugins/noaa_metop_support/noaa/module_noaa_instruments.cpp index 13b697c75..0ee4c8672 100644 --- a/plugins/noaa_metop_support/noaa/module_noaa_instruments.cpp +++ b/plugins/noaa_metop_support/noaa/module_noaa_instruments.cpp @@ -10,6 +10,7 @@ #include "core/resources.h" #include "common/projection/timestamp_filtering.h" #include "common/tracking/tle.h" +#include "utils/stats.h" namespace noaa { @@ -119,7 +120,7 @@ namespace noaa } // done with the frames data_in.close(); - int scid = most_common(spacecraft_ids.begin(), spacecraft_ids.end(), 0); + int scid = satdump::most_common(spacecraft_ids.begin(), spacecraft_ids.end(), 0); spacecraft_ids.clear(); int norad = 0; std::string sat_name = "Unknown NOAA"; @@ -142,7 +143,7 @@ namespace noaa // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = sat_name; - dataset.timestamp = get_median(avhrr_reader.timestamps); + dataset.timestamp = satdump::get_median(avhrr_reader.timestamps); std::optional satellite_tle = satdump::general_tle_registry->get_from_norad_time(norad, dataset.timestamp); @@ -423,7 +424,7 @@ namespace noaa } // ID - uint8_t scid = most_common(scid_list.begin(), scid_list.end(), 0); + uint8_t scid = satdump::most_common(scid_list.begin(), scid_list.end(), 0); scid_list.clear(); int norad = 0; std::string sat_name = "Unknown NOAA"; @@ -446,7 +447,7 @@ namespace noaa // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = sat_name; - dataset.timestamp = get_median(hirs_reader.timestamps); + dataset.timestamp = satdump::get_median(hirs_reader.timestamps); std::optional satellite_tle = satdump::general_tle_registry->get_from_norad_time(norad, dataset.timestamp); diff --git a/plugins/official_products_support/hsd2pro/himawari_ahi.cpp b/plugins/official_products_support/hsd2pro/himawari_ahi.cpp index aa142d4a5..ebfbe2b3c 100644 --- a/plugins/official_products_support/hsd2pro/himawari_ahi.cpp +++ b/plugins/official_products_support/hsd2pro/himawari_ahi.cpp @@ -6,6 +6,7 @@ #include "libs/bzlib_utils.h" #include "logger.h" #include "products2/image_product.h" +#include "utils/string.h" #include #include @@ -169,7 +170,7 @@ namespace hsd2pro std::vector all_images; std::map> files_to_parse; // Channel, paths { - auto ori_splt = splitString(std::filesystem::path(hsd_file).stem().string(), '_'); + auto ori_splt = satdump::splitString(std::filesystem::path(hsd_file).stem().string(), '_'); if (ori_splt.size() != 8) throw satdump_exception("Invalid Himawari filename!"); @@ -184,7 +185,7 @@ namespace hsd2pro { std::string cleanname = std::filesystem::path(path).stem().string(); - auto splt = splitString(cleanname, '_'); + auto splt = satdump::splitString(cleanname, '_'); if (splt.size() == 8 && ori_splt[0] == splt[0] && ori_splt[1] == splt[1] && ori_splt[2] == splt[2] && ori_splt[3] == splt[3] && ori_splt[5] == splt[5]) { diff --git a/plugins/official_products_support/loader/aws.cpp b/plugins/official_products_support/loader/aws.cpp index 813f697d7..2365358b8 100644 --- a/plugins/official_products_support/loader/aws.cpp +++ b/plugins/official_products_support/loader/aws.cpp @@ -1,10 +1,11 @@ #include "archive_loader.h" -#include "common/utils.h" +#include "utils/http.h" #include "logger.h" #include "nlohmann/json.hpp" #include "processing.h" #include "main_ui.h" +#include "utils/time.h" #include "libs/rapidxml.hpp" @@ -14,7 +15,7 @@ namespace satdump { std::string url_req = url_host + url_path; std::string result; - while (perform_http_request(url_req, result) != 1) + while (satdump::perform_http_request(url_req, result) != 1) { // logger->trace("\nURL WAS : %s\n", url_req.c_str()); @@ -36,7 +37,7 @@ namespace satdump time_t timestamp = 0; std::string channel; (this->*parseTimestamp)(stem, timestamp, channel); - aws_list[timestamp_to_string(timestamp)].insert(url_host + path); + aws_list[satdump::timestamp_to_string(timestamp)].insert(url_host + path); } // Continuation diff --git a/plugins/official_products_support/loader/eumetsat.cpp b/plugins/official_products_support/loader/eumetsat.cpp index 05dc69a03..8ba619b22 100644 --- a/plugins/official_products_support/loader/eumetsat.cpp +++ b/plugins/official_products_support/loader/eumetsat.cpp @@ -6,6 +6,8 @@ #include "processing.h" #include "main_ui.h" #include "libs/base64/base64.h" +#include "utils/time.h" +#include "utils/http.h" namespace satdump { @@ -79,7 +81,7 @@ namespace satdump std::string final_token = macaron::Base64::Encode(eumetsat_user_consumer_credential + ":" + eumetsat_user_consumer_secret); std::string resp = ""; - if (perform_http_request_post("https://api.eumetsat.int/token", resp, "grant_type=client_credentials", "Authorization: Basic " + final_token) != 1) + if (satdump::perform_http_request_post("https://api.eumetsat.int/token", resp, "grant_type=client_credentials", "Authorization: Basic " + final_token) != 1) resp = nlohmann::json::parse(resp)["access_token"]; logger->trace("Token " + resp); return resp; @@ -105,7 +107,7 @@ namespace satdump "/products?format=json"; std::string resp; logger->info(url); - if (perform_http_request(url, resp, "") != 1) + if (satdump::perform_http_request(url, resp, "") != 1) { eumetsat_list.clear(); @@ -131,7 +133,7 @@ namespace satdump time_t timestamp = timegm(&timeS); std::string prod_d = prod["links"][0]["href"]; - eumetsat_list.push_back({timestamp_to_string(timestamp), prod_d}); + eumetsat_list.push_back({satdump::timestamp_to_string(timestamp), prod_d}); } } } @@ -188,7 +190,7 @@ namespace satdump if (ImGui::Button(std::string("Load##archiveloadertablebutton_" + str.timestamp).c_str())) { std::string resp; - if (perform_http_request(str.href, resp, "") != 1) + if (satdump::perform_http_request(str.href, resp, "") != 1) { nlohmann::json respj = nlohmann::json::parse(resp); // printf("\n%s\n", respj.dump(4).c_str()); diff --git a/plugins/official_products_support/nat2pro/formats/amsu_nat.cpp b/plugins/official_products_support/nat2pro/formats/amsu_nat.cpp index 37cf84aad..6961357a9 100644 --- a/plugins/official_products_support/nat2pro/formats/amsu_nat.cpp +++ b/plugins/official_products_support/nat2pro/formats/amsu_nat.cpp @@ -5,7 +5,7 @@ #include "core/resources.h" #include "metop_nat.h" -#include "common/utils.h" +#include "utils/stats.h" #include "metop_helper.h" namespace nat2pro @@ -99,7 +99,7 @@ namespace nat2pro } { - auto ptime = get_median(timestamps); + auto ptime = satdump::get_median(timestamps); auto info = getMetOpSatInfoFromID(sat_id, ptime); satdump::products::ImageProduct amsu_products; diff --git a/plugins/official_products_support/nat2pro/formats/avhrr_nat.cpp b/plugins/official_products_support/nat2pro/formats/avhrr_nat.cpp index 278824f2f..0444ca04e 100644 --- a/plugins/official_products_support/nat2pro/formats/avhrr_nat.cpp +++ b/plugins/official_products_support/nat2pro/formats/avhrr_nat.cpp @@ -4,8 +4,9 @@ #include "nlohmann/json_utils.h" #include "core/resources.h" #include "metop_nat.h" +#include "utils/time.h" -#include "common/utils.h" +#include "utils/stats.h" #include "common/tracking/tle.h" #include "metop_helper.h" @@ -125,7 +126,7 @@ namespace nat2pro } logger->info("%d %d %d %f %f %f %f %d - %s", (int)main_header.record_class, (int)main_header.record_size, (int)main_header.record_subclass_version, - lon_first, lat_first, lon_last, lat_last, ch3a, timestamp_to_string(main_header.record_start_time).c_str()); + lon_first, lat_first, lon_last, lat_last, ch3a, satdump::timestamp_to_string(main_header.record_start_time).c_str()); } } @@ -133,7 +134,7 @@ namespace nat2pro } { - auto ptime = get_median(timestamps); + auto ptime = satdump::get_median(timestamps); auto info = getMetOpSatInfoFromID(sat_id, ptime); satdump::products::ImageProduct avhrr_products; diff --git a/plugins/official_products_support/nat2pro/formats/gome_nat.cpp b/plugins/official_products_support/nat2pro/formats/gome_nat.cpp index 898dfdfc2..3731c4c14 100644 --- a/plugins/official_products_support/nat2pro/formats/gome_nat.cpp +++ b/plugins/official_products_support/nat2pro/formats/gome_nat.cpp @@ -5,7 +5,7 @@ #include "core/resources.h" #include "metop_nat.h" -#include "common/utils.h" +#include "utils/stats.h" #include "metop_helper.h" namespace nat2pro @@ -108,7 +108,7 @@ namespace nat2pro } { - auto ptime = get_median(timestamps); + auto ptime = satdump::get_median(timestamps); auto info = getMetOpSatInfoFromID(sat_id, ptime); satdump::products::ImageProduct gome_products; diff --git a/plugins/official_products_support/nat2pro/formats/hirs_nat.cpp b/plugins/official_products_support/nat2pro/formats/hirs_nat.cpp index 091b0c3f1..04f8869b9 100644 --- a/plugins/official_products_support/nat2pro/formats/hirs_nat.cpp +++ b/plugins/official_products_support/nat2pro/formats/hirs_nat.cpp @@ -5,7 +5,7 @@ #include "core/resources.h" #include "metop_nat.h" -#include "common/utils.h" +#include "utils/stats.h" #include "metop_helper.h" namespace nat2pro @@ -101,7 +101,7 @@ namespace nat2pro } { - auto ptime = get_median(timestamps); + auto ptime = satdump::get_median(timestamps); auto info = getMetOpSatInfoFromID(sat_id, ptime); satdump::products::ImageProduct hirs_products; diff --git a/plugins/official_products_support/nat2pro/formats/iasi_nat.cpp b/plugins/official_products_support/nat2pro/formats/iasi_nat.cpp index df3017ba1..d331562f5 100644 --- a/plugins/official_products_support/nat2pro/formats/iasi_nat.cpp +++ b/plugins/official_products_support/nat2pro/formats/iasi_nat.cpp @@ -7,7 +7,7 @@ #include "image/processing.h" -#include "common/utils.h" +#include "utils/stats.h" #include "metop_helper.h" namespace nat2pro @@ -120,7 +120,7 @@ namespace nat2pro } { - auto ptime = get_median(timestamps); + auto ptime = satdump::get_median(timestamps); auto info = getMetOpSatInfoFromID(sat_id, ptime); satdump::products::ImageProduct iasi_products; diff --git a/plugins/official_products_support/nat2pro/formats/mhs_nat.cpp b/plugins/official_products_support/nat2pro/formats/mhs_nat.cpp index 699643a8d..cc41a53d9 100644 --- a/plugins/official_products_support/nat2pro/formats/mhs_nat.cpp +++ b/plugins/official_products_support/nat2pro/formats/mhs_nat.cpp @@ -5,7 +5,7 @@ #include "core/resources.h" #include "metop_nat.h" -#include "common/utils.h" +#include "utils/stats.h" #include "metop_helper.h" namespace nat2pro @@ -119,7 +119,7 @@ namespace nat2pro } { - auto ptime = get_median(timestamps); + auto ptime = satdump::get_median(timestamps); auto info = getMetOpSatInfoFromID(sat_id, ptime); satdump::products::ImageProduct mhs_products; diff --git a/plugins/official_products_support/nc2pro/gk2a_ami.cpp b/plugins/official_products_support/nc2pro/gk2a_ami.cpp index c7007c871..647a4b1c6 100644 --- a/plugins/official_products_support/nc2pro/gk2a_ami.cpp +++ b/plugins/official_products_support/nc2pro/gk2a_ami.cpp @@ -3,7 +3,7 @@ #include #include "image/image.h" -#include "common/utils.h" +#include "utils/string.h" #include "core/exception.h" #include "gk2a_ami.h" #include "hdf5_utils.h" @@ -37,7 +37,7 @@ namespace nc2pro if (file < 0) return image_out; - std::vector name_parts = splitString(hdf5_get_string_attr_FILE_fixed(file, "file_name"), '_'); + std::vector name_parts = satdump::splitString(hdf5_get_string_attr_FILE_fixed(file, "file_name"), '_'); image_out.channel = name_parts[3]; std::transform(image_out.channel.begin(), image_out.channel.end(), image_out.channel.begin(), ::toupper); @@ -96,7 +96,7 @@ namespace nc2pro std::vector all_images; std::vector files_to_parse; //= {nc_file}; { - auto ori_splt = splitString(std::filesystem::path(nc_file).stem().string(), '_'); + auto ori_splt = satdump::splitString(std::filesystem::path(nc_file).stem().string(), '_'); if (ori_splt.size() != 6) throw satdump_exception("Invalid GK-2A filename!"); @@ -110,7 +110,7 @@ namespace nc2pro { std::string cleanname = std::filesystem::path(path).stem().string(); - auto splt = splitString(cleanname, '_'); + auto splt = satdump::splitString(cleanname, '_'); if (splt.size() == 6 && ori_splt[0] == splt[0] && ori_splt[1] == splt[1] && ori_splt[2] == splt[2] && ori_splt[5] == splt[5]) { diff --git a/plugins/official_products_support/nc2pro/goesr_abi.cpp b/plugins/official_products_support/nc2pro/goesr_abi.cpp index 933e0bcbf..cf9d379ea 100644 --- a/plugins/official_products_support/nc2pro/goesr_abi.cpp +++ b/plugins/official_products_support/nc2pro/goesr_abi.cpp @@ -8,6 +8,7 @@ #include #include #include +#include "utils/string.h" #include "nlohmann/json_utils.h" #include "core/resources.h" @@ -141,10 +142,10 @@ namespace nc2pro std::vector files_to_parse; { - auto ori_splt = splitString(std::filesystem::path(nc_file).stem().string(), '_'); + auto ori_splt = satdump::splitString(std::filesystem::path(nc_file).stem().string(), '_'); if (ori_splt.size() != 6) throw satdump_exception("Invalid GOES-R filename!"); - auto ori_splt2 = splitString(ori_splt[1], '-'); + auto ori_splt2 = satdump::splitString(ori_splt[1], '-'); if (ori_splt2.size() != 4 || ori_splt2[3].size() != 5) throw satdump_exception("Invalid GOES-R filename!"); @@ -158,11 +159,11 @@ namespace nc2pro { std::string cleanname = std::filesystem::path(path).stem().string(); - auto splt = splitString(cleanname, '_'); + auto splt = satdump::splitString(cleanname, '_'); if (splt.size() == 6 && ori_splt[0] == splt[0] && ori_splt[2] == splt[2] && ori_splt[3] == splt[3]) { - auto splt2 = splitString(splt[1], '-'); + auto splt2 = satdump::splitString(splt[1], '-'); if (splt2.size() == 4 && ori_splt2[0] == splt2[0] && ori_splt2[1] == splt2[1] && ori_splt2[2] == splt2[2] && ori_splt2[3].size() == 5 && ori_splt2[3][0] == splt2[3][0] && ori_splt2[3][1] == splt2[3][1] && ori_splt2[3][2] == splt2[3][2]) diff --git a/plugins/orbcomm_support/orbcomm/module_orbcomm_plotter.cpp b/plugins/orbcomm_support/orbcomm/module_orbcomm_plotter.cpp index b9e192e55..4ccd6fd34 100644 --- a/plugins/orbcomm_support/orbcomm/module_orbcomm_plotter.cpp +++ b/plugins/orbcomm_support/orbcomm/module_orbcomm_plotter.cpp @@ -8,6 +8,7 @@ #include "common/geodetic/ecef_to_eci.h" #include "common/geodetic/lla_xyz.h" #include "core/config.h" +#include "utils/time.h" // We need access to libpredict internals! #include "libs/predict/predict.h" @@ -213,7 +214,7 @@ namespace orbcomm time_t ephem_time = gps_time_to_unix(week_number, time_of_week); logger->info("SCID %d, Week Number %d, Time Of Week %d, Time %s - X %.3d Y %.3d Z %.3d - X %.3f Y %.3f Z %.3f - Lon %.1f, Lat %.1f, Alt %.1f - Az %.1f El %.1f Range %.1f", - scid + 70, week_number, time_of_week, timestamp_to_string(ephem_time).c_str(), + scid + 70, week_number, time_of_week, satdump::timestamp_to_string(ephem_time).c_str(), x_raw, y_raw, z_raw, X_DOT, Y_DOT, Z_DOT, lla.lon, lla.lat, lla.alt, diff --git a/plugins/others_support/orb/image_parser.h b/plugins/others_support/orb/image_parser.h index 35bd154aa..7c7d5ab10 100644 --- a/plugins/others_support/orb/image_parser.h +++ b/plugins/others_support/orb/image_parser.h @@ -10,6 +10,7 @@ #include "common/utils.h" #include "imgui/imgui_image.h" #include +#include "utils/time.h" namespace orb { @@ -107,7 +108,7 @@ namespace orb void saveAll(int channel = -1) { std::string dirpath = directory + "/" + - timestamp_to_string(last_timestamp); //+std::to_string(last_timestamp); + satdump::timestamp_to_string(last_timestamp); //+std::to_string(last_timestamp); if (!std::filesystem::exists(dirpath)) std::filesystem::create_directories(dirpath); diff --git a/plugins/proba_support/proba/instruments/chris/chris_reader.cpp b/plugins/proba_support/proba/instruments/chris/chris_reader.cpp index fc5b1e162..9f35daa1c 100644 --- a/plugins/proba_support/proba/instruments/chris/chris_reader.cpp +++ b/plugins/proba_support/proba/instruments/chris/chris_reader.cpp @@ -9,6 +9,7 @@ #include "common/repack.h" #include "../crc.h" #include "image/io.h" +#include "utils/stats.h" #define ALL_MODE 2 #define WATER_MODE 3 @@ -90,7 +91,7 @@ namespace proba if ((count_marker > 50 && count_marker < 70) || (count_marker > 500 && count_marker < 520) || (count_marker > 700 && count_marker < 720)) { - mode = most_common(modeMarkers.begin(), modeMarkers.end(), 0); + mode = satdump::most_common(modeMarkers.begin(), modeMarkers.end(), 0); if (mode == WATER_MODE || mode == CHLOROPHYL_MODE || mode == LAND_MODE) { diff --git a/plugins/stereo_support/stereo/instruments/secchi/secchi_reader.cpp b/plugins/stereo_support/stereo/instruments/secchi/secchi_reader.cpp index 90e98b61f..5e369b10c 100644 --- a/plugins/stereo_support/stereo/instruments/secchi/secchi_reader.cpp +++ b/plugins/stereo_support/stereo/instruments/secchi/secchi_reader.cpp @@ -2,6 +2,7 @@ #include #include "common/utils.h" #include "core/resources.h" +#include "utils/time.h" #include "rice_decomp.h" @@ -79,7 +80,7 @@ namespace stereo std::string channel_name = "COR2"; - text_drawer.draw_text(img, 150 / 2, 460 / 2, text_color, 30 / 2, timestamp_to_string(last_timestamp_0)); + text_drawer.draw_text(img, 150 / 2, 460 / 2, text_color, 30 / 2, satdump::timestamp_to_string(last_timestamp_0)); std::filesystem::create_directories(output_directory + "/" + channel_name); @@ -91,7 +92,7 @@ namespace stereo image::save_img(img, output_directory + "/" + channel_name + "/" + std::to_string(unknown_cnt++)); if (last_filename_0.size() > 0) - decompression_status_out << channel_name << " " << last_filename_0 << " " << timestamp_to_string(last_timestamp_0) << " " << ((img.size() > 0) ? "PASS" : "FAIL") << "\n"; + decompression_status_out << channel_name << " " << last_filename_0 << " " << satdump::timestamp_to_string(last_timestamp_0) << " " << ((img.size() > 0) ? "PASS" : "FAIL") << "\n"; last_filename_0 = ""; last_timestamp_0 = 0; } @@ -124,7 +125,7 @@ namespace stereo std::string channel_name = "HI1"; - text_drawer.draw_text(img, 150 / 2, 460 / 2, text_color, 30 / 2, timestamp_to_string(last_timestamp_1)); + text_drawer.draw_text(img, 150 / 2, 460 / 2, text_color, 30 / 2, satdump::timestamp_to_string(last_timestamp_1)); std::filesystem::create_directories(output_directory + "/" + channel_name); @@ -136,7 +137,7 @@ namespace stereo image::save_img(img, output_directory + "/" + channel_name + "/" + std::to_string(unknown_cnt++)); if (last_filename_1.size() > 0) - decompression_status_out << channel_name << " " << last_filename_1 << " " << timestamp_to_string(last_timestamp_1) << " " << ((img.size() > 0) ? "PASS" : "FAIL") << "\n"; + decompression_status_out << channel_name << " " << last_filename_1 << " " << satdump::timestamp_to_string(last_timestamp_1) << " " << ((img.size() > 0) ? "PASS" : "FAIL") << "\n"; last_filename_1 = ""; last_timestamp_1 = 0; } @@ -166,7 +167,7 @@ namespace stereo std::string channel_name = "HI2"; - text_drawer.draw_text(img, 150 / 2, 460 / 2, text_color, 30 / 2, timestamp_to_string(last_timestamp_2)); + text_drawer.draw_text(img, 150 / 2, 460 / 2, text_color, 30 / 2, satdump::timestamp_to_string(last_timestamp_2)); std::filesystem::create_directories(output_directory + "/" + channel_name); @@ -178,7 +179,7 @@ namespace stereo image::save_img(img, output_directory + "/" + channel_name + "/" + std::to_string(unknown_cnt++)); if (last_filename_2.size() > 0) - decompression_status_out << channel_name << " " << last_filename_2 << " " << timestamp_to_string(last_timestamp_2) << " " << ((img.size() > 0) ? "PASS" : "FAIL") << "\n"; + decompression_status_out << channel_name << " " << last_filename_2 << " " << satdump::timestamp_to_string(last_timestamp_2) << " " << ((img.size() > 0) ? "PASS" : "FAIL") << "\n"; last_filename_2 = ""; last_timestamp_2 = 0; } @@ -222,7 +223,7 @@ namespace stereo else channel_name = "Corrupted"; - text_drawer.draw_text(img, 150, 460, text_color, 30, timestamp_to_string(last_timestamp_3)); + text_drawer.draw_text(img, 150, 460, text_color, 30, satdump::timestamp_to_string(last_timestamp_3)); std::filesystem::create_directories(output_directory + "/" + channel_name); @@ -234,7 +235,7 @@ namespace stereo image::save_img(img, output_directory + "/" + channel_name + "/" + std::to_string(unknown_cnt++)); if (last_filename_3.size() > 0) - decompression_status_out << channel_name << " " << last_filename_3 << " " << timestamp_to_string(last_timestamp_3) << " " << ((img.size() > 0) ? "PASS" : "FAIL") << "\n"; + decompression_status_out << channel_name << " " << last_filename_3 << " " << satdump::timestamp_to_string(last_timestamp_3) << " " << ((img.size() > 0) ? "PASS" : "FAIL") << "\n"; last_filename_3 = ""; last_timestamp_3 = 0; last_polarization_3 = 0; diff --git a/plugins/wsf_support/wsfm/module_wsfm_instruments.cpp b/plugins/wsf_support/wsfm/module_wsfm_instruments.cpp index b44452976..05e66aae6 100644 --- a/plugins/wsf_support/wsfm/module_wsfm_instruments.cpp +++ b/plugins/wsf_support/wsfm/module_wsfm_instruments.cpp @@ -11,6 +11,7 @@ #include "core/resources.h" #include "nlohmann/json_utils.h" #include "common/tracking/tle.h" +#include "utils/stats.h" namespace wsfm { @@ -65,7 +66,7 @@ namespace wsfm data_in.close(); - int scid = most_common(wsfm_scids.begin(), wsfm_scids.end(), 0); + int scid = satdump::most_common(wsfm_scids.begin(), wsfm_scids.end(), 0); wsfm_scids.clear(); #define WSFM_1_SCID 120 @@ -82,7 +83,7 @@ namespace wsfm // Products dataset satdump::products::DataSet dataset; dataset.satellite_name = sat_name; - dataset.timestamp = get_median(mwi_reader.timestamps); + dataset.timestamp = satdump::get_median(mwi_reader.timestamps); std::optional satellite_tle = satdump::general_tle_registry->get_from_norad_time(norad, dataset.timestamp); diff --git a/src-cli/autotrack/autotrack.cpp b/src-cli/autotrack/autotrack.cpp index 00c1be029..f64a9d993 100644 --- a/src-cli/autotrack/autotrack.cpp +++ b/src-cli/autotrack/autotrack.cpp @@ -1,6 +1,7 @@ #include "autotrack.h" #include "logger.h" #include "common/utils.h" +#include "utils/time.h" AutoTrackApp::AutoTrackApp(nlohmann::json settings, nlohmann::json parameters, std::string output_folder) : d_settings(settings), d_parameters(parameters), d_output_folder(output_folder) @@ -178,7 +179,7 @@ AutoTrackApp::AutoTrackApp(nlohmann::json settings, nlohmann::json parameters, s // Finally, start auto_scheduler.start(); - auto_scheduler.setEngaged(true, getTime()); + auto_scheduler.setEngaged(true, satdump::getTime()); /////////////////////////////////////////////////////////////////////////////////// ///////////////// WebServer diff --git a/src-cli/autotrack/autotrack_proc.cpp b/src-cli/autotrack/autotrack_proc.cpp index 054bf06ab..653a07e93 100644 --- a/src-cli/autotrack/autotrack_proc.cpp +++ b/src-cli/autotrack/autotrack_proc.cpp @@ -1,7 +1,8 @@ #include "autotrack.h" -#include "logger.h" +#include "utils/thread_priority.h" #include "common/utils.h" -#include "common/thread_priority.h" +#include "logger.h" +#include "utils/time.h" void AutoTrackApp::start_processing() { @@ -51,7 +52,7 @@ void AutoTrackApp::stop_processing() nlohmann::json pipeline_params_ = pipeline_params; auto fun = [selected_pipeline_, pipeline_output_dir_, input_file, pipeline_params_](int) { - setLowestThreadPriority(); + satdump::setLowestThreadPriority(); // TODOREWORK namespace remove satdump::Pipeline pipeline = selected_pipeline_; int start_level = pipeline.live_cfg.normal_live[pipeline.live_cfg.normal_live.size() - 1].first; std::string input_level = pipeline.steps[start_level].level_name; @@ -70,7 +71,7 @@ void AutoTrackApp::start_recording() { splitter->set_enabled("record", true); - std::string filename = d_output_folder + "/" + prepareBasebandFileName(getTime(), get_samplerate(), frequency_hz); + std::string filename = d_output_folder + "/" + prepareBasebandFileName(satdump::getTime(), get_samplerate(), frequency_hz); std::string recorder_filename = file_sink->start_recording(filename, get_samplerate()); logger->info("Recording to " + recorder_filename); is_recording = true; diff --git a/src-cli/autotrack/autotrack_vfo.cpp b/src-cli/autotrack/autotrack_vfo.cpp index cad0945fa..394e5c037 100644 --- a/src-cli/autotrack/autotrack_vfo.cpp +++ b/src-cli/autotrack/autotrack_vfo.cpp @@ -1,6 +1,7 @@ #include "autotrack.h" #include "logger.h" #include "common/utils.h" +#include "utils/time.h" void AutoTrackApp::add_vfo_live(std::string id, std::string name, double freq, satdump::Pipeline vpipeline, nlohmann::json vpipeline_params) { @@ -65,7 +66,7 @@ void AutoTrackApp::add_vfo_reco(std::string id, std::string name, double freq, d wipInfo.decim_ptr->start(); wipInfo.file_sink->start(); - wipInfo.file_sink->start_recording(d_output_folder + "/" + prepareBasebandFileName(getTime(), get_samplerate() / decimation, freq), get_samplerate() / decimation); + wipInfo.file_sink->start_recording(d_output_folder + "/" + prepareBasebandFileName(satdump::getTime(), get_samplerate() / decimation, freq), get_samplerate() / decimation); splitter->set_vfo_enabled(id, true); diff --git a/src-cli/autotrack/autotrack_web.cpp b/src-cli/autotrack/autotrack_web.cpp index d333a2a50..44a8a4fe3 100644 --- a/src-cli/autotrack/autotrack_web.cpp +++ b/src-cli/autotrack/autotrack_web.cpp @@ -1,8 +1,9 @@ #include "autotrack.h" #include "../webserver.h" #include "logger.h" -#include "common/utils.h" +#include "utils/format.h" #include "image/jpeg_utils.h" +#include "utils/time.h" void AutoTrackApp::setup_webserver() { @@ -82,7 +83,7 @@ void AutoTrackApp::setup_webserver() webserver::handle_callback_schedule = [this]() -> std::vector { - auto img = auto_scheduler.getScheduleImage(512, getTime()); + auto img = auto_scheduler.getScheduleImage(512, satdump::getTime()); std::vector vec = image::save_jpeg_mem(img); return vec; }; @@ -145,12 +146,12 @@ void AutoTrackApp::setup_webserver() "

Object Tracker

" + "
" + "

Next AOS time: " + - timestamp_to_string(status["next_aos_time"].get(), auto_scheduler.getAutoTrackCfg().use_localtime) + + satdump::timestamp_to_string(status["next_aos_time"].get(), auto_scheduler.getAutoTrackCfg().use_localtime) + "" + aos_in + "

" + "

Next LOS time: " + - timestamp_to_string(status["next_los_time"].get(), auto_scheduler.getAutoTrackCfg().use_localtime) + + satdump::timestamp_to_string(status["next_los_time"].get(), auto_scheduler.getAutoTrackCfg().use_localtime) + "" + los_in + "

" + @@ -159,25 +160,25 @@ void AutoTrackApp::setup_webserver() "

" + "

Current position:
" + "Azimuth " + - svformat("%.2f", (status["sat_current_pos"]["az"].get())) + + satdump::svformat("%.2f", (status["sat_current_pos"]["az"].get())) + " °
Elevation " + - svformat("%.2f", (status["sat_current_pos"]["el"].get())) + + satdump::svformat("%.2f", (status["sat_current_pos"]["el"].get())) + " °
Range " + - svformat("%.2f", (status["sat_current_range"].get())) + + satdump::svformat("%.2f", (status["sat_current_range"].get())) + " km

" + "

Rotator Control

" + "

Status:" + rot_engaged + ", " + rot_tracking + "

" + "

Azimuth: requested " + - svformat("%.2f", (status["rot_current_req_pos"]["az"].get())) + + satdump::svformat("%.2f", (status["rot_current_req_pos"]["az"].get())) + " °, actual " + - svformat("%.2f", (status["rot_current_pos"]["az"].get())) + + satdump::svformat("%.2f", (status["rot_current_pos"]["az"].get())) + " °

" + "

Elevation: requested " + - svformat("%.2f", (status["rot_current_req_pos"]["el"].get())) + + satdump::svformat("%.2f", (status["rot_current_req_pos"]["el"].get())) + " °, actual " + - svformat("%.2f", (status["rot_current_pos"]["el"].get())) + + satdump::svformat("%.2f", (status["rot_current_pos"]["el"].get())) + " °

" + schedule + fft; diff --git a/src-core/common/lrit/lrit_productizer.cpp b/src-core/common/lrit/lrit_productizer.cpp index 7cc0d8e7a..a7b5dafca 100644 --- a/src-core/common/lrit/lrit_productizer.cpp +++ b/src-core/common/lrit/lrit_productizer.cpp @@ -3,11 +3,12 @@ #include "logger.h" #include "products2/image_product.h" #include +#include "utils/string.h" // TODOREWORK #include "products/processor/image_processor.h" -#include "common/thread_priority.h" #include "core/config.h" #include "nlohmann/json_utils.h" +#include "utils/thread_priority.h" #include "image/io.h" @@ -109,10 +110,10 @@ namespace lrit // if (instrument_id == "ahi") // printf("Channel %s\n%s\n", channel.c_str(), image_data_function_record->datas.c_str()); - auto lines = splitString(image_data_function_record->datas, '\n'); + auto lines = satdump::splitString(image_data_function_record->datas, '\n'); if (lines.size() < 4) { - lines = splitString(image_data_function_record->datas, '\r'); + lines = satdump::splitString(image_data_function_record->datas, '\r'); if (lines.size() < 4) { logger->error("Error parsing calibration info into lines!"); @@ -334,7 +335,7 @@ namespace lrit void LRITProductizer::compositeThreadFunc() { - setLowestThreadPriority(); + satdump::setLowestThreadPriority(); // TODOREWORK namespace remove std::string file_for_cache = compo_cache_path + "/.composite_cache_do_not_delete.json"; diff --git a/src-core/common/projection/timestamp_filtering.cpp b/src-core/common/projection/timestamp_filtering.cpp index 389b22e04..b4afefcda 100644 --- a/src-core/common/projection/timestamp_filtering.cpp +++ b/src-core/common/projection/timestamp_filtering.cpp @@ -1,5 +1,5 @@ #include "timestamp_filtering.h" -#include "common/utils.h" +#include "utils/stats.h" #include "logger.h" namespace timestamp_filtering @@ -7,7 +7,7 @@ namespace timestamp_filtering std::vector filter_timestamps_simple(std::vector timestamps, double max_tolerate, double max_diff) { std::vector filter_timestamps = timestamps; - double avg = get_median(filter_timestamps); + double avg = satdump::get_median(filter_timestamps); double last = -1; for (double &v : filter_timestamps) { diff --git a/src-core/common/rimgui.h b/src-core/common/rimgui.h index b8d56bda9..302a8bb87 100644 --- a/src-core/common/rimgui.h +++ b/src-core/common/rimgui.h @@ -2,7 +2,7 @@ #include "imgui/imgui.h" #include "imgui/imgui_stdlib.h" -#include "common/utils.h" +#include "utils/format.h" #include #include #include @@ -298,7 +298,7 @@ namespace RImGui else current_instance->ui_elements.push_back({UI_ELEMENT_TEXT, current_instance->current_id++, - 0, 0, svformat(fmt, args...)}); + 0, 0, satdump::svformat(fmt, args...)}); } inline bool Button(const char *label, ImVec2 size = ImVec2(0, 0)) diff --git a/src-core/common/thread_priority.cpp b/src-core/common/thread_priority.cpp deleted file mode 100644 index e267f5daa..000000000 --- a/src-core/common/thread_priority.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include "thread_priority.h" - -#include "logger.h" -#ifdef _WIN32 -#include -#endif - -void setThreadPriority(std::thread &th, thread_priority_t priority) -{ -#ifdef _WIN32 - if (SetThreadPriority(th.native_handle(), priority) == 0) - logger->error("Could not set thread priority!"); -#else - sched_param sch_params; - int policy = 0; - pthread_getschedparam(th.native_handle(), &policy, &sch_params); - sch_params.sched_priority = priority; - if (pthread_setschedparam(th.native_handle(), SCHED_RR, &sch_params)) - logger->error("Could not set thread priority!"); -#endif -} - -void setLowestThreadPriority(std::thread &th) -{ -#ifdef _WIN32 - if (SetThreadPriority(th.native_handle(), -2) == 0) - logger->error("Could not set thread priority!"); -#elif defined(__APPLE__) - sched_param sch_params; - int policy = 0; - pthread_getschedparam(th.native_handle(), &policy, &sch_params); - sch_params.sched_priority = PRIORITY_LOWEST; - if (pthread_setschedparam(th.native_handle(), SCHED_RR, &sch_params)) - logger->error("Could not set thread priority!"); -#else - sched_param sch_params; - int policy = 0; - pthread_getschedparam(th.native_handle(), &policy, &sch_params); - if (pthread_setschedparam(th.native_handle(), SCHED_IDLE, &sch_params)) - logger->error("Could not set thread priority!"); -#endif -} - -void setLowestThreadPriority() -{ -#ifdef _WIN32 - if (SetThreadPriority(GetCurrentThread(), -2) == 0) - logger->error("Could not set thread priority!"); -#elif defined(__APPLE__) - sched_param sch_params; - int policy = 0; - pthread_getschedparam(pthread_self(), &policy, &sch_params); - sch_params.sched_priority = PRIORITY_LOWEST; - if (pthread_setschedparam(pthread_self(), SCHED_RR, &sch_params)) - logger->error("Could not set thread priority!"); -#else - sched_param sch_params; - int policy = 0; - pthread_getschedparam(pthread_self(), &policy, &sch_params); - if (pthread_setschedparam(pthread_self(), SCHED_IDLE, &sch_params)) - logger->error("Could not set thread priority!"); -#endif -} \ No newline at end of file diff --git a/src-core/common/thread_priority.h b/src-core/common/thread_priority.h deleted file mode 100644 index 27e326c84..000000000 --- a/src-core/common/thread_priority.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include - -enum thread_priority_t -{ -#ifdef _WIN32 - PRIORITY_LOWEST = -2, - PRIORITY_LOW = -1, - PRIORITY_NORMAL = 0, - PRIORITY_HIGH = 1, - PRIORITY_HIGHEST = 2, -#else - PRIORITY_LOWEST = 1, - PRIORITY_LOW = 24, - PRIORITY_NORMAL = 50, - PRIORITY_HIGH = 74, - PRIORITY_HIGHEST = 99, -#endif -}; - -void setThreadPriority(std::thread &th, thread_priority_t priority); -void setLowestThreadPriority(std::thread &th); -void setLowestThreadPriority(); \ No newline at end of file diff --git a/src-core/common/tile_map/map.cpp b/src-core/common/tile_map/map.cpp index a5fdfe484..e58b9408b 100644 --- a/src-core/common/tile_map/map.cpp +++ b/src-core/common/tile_map/map.cpp @@ -2,6 +2,7 @@ #include #include "common/geodetic/geodetic_coordinates.h" #include "common/utils.h" +#include "utils/http.h" #include "logger.h" #include "image/io.h" #include "image/meta.h" @@ -71,7 +72,7 @@ image::Image downloadTileMap(std::string url_source, double lat0, double lon0, d { logger->debug("Downloading tile from: " + url); - perform_http_request(url, res); + satdump::perform_http_request(url, res); image::Image tile; image::load_img(tile, (uint8_t *)res.data(), res.size()); diff --git a/src-core/common/tracking/obj_tracker/object_tracker_backend.cpp b/src-core/common/tracking/obj_tracker/object_tracker_backend.cpp index a099c3bea..58bf23cae 100644 --- a/src-core/common/tracking/obj_tracker/object_tracker_backend.cpp +++ b/src-core/common/tracking/obj_tracker/object_tracker_backend.cpp @@ -3,6 +3,7 @@ #include "common/utils.h" #include "logger.h" #include "common/tracking/tle.h" +#include "utils/time.h" #include namespace satdump diff --git a/src-core/common/tracking/obj_tracker/object_tracker_horizons.cpp b/src-core/common/tracking/obj_tracker/object_tracker_horizons.cpp index 24b87737b..dc067b1e5 100644 --- a/src-core/common/tracking/obj_tracker/object_tracker_horizons.cpp +++ b/src-core/common/tracking/obj_tracker/object_tracker_horizons.cpp @@ -1,6 +1,7 @@ #include "object_tracker.h" #include "logger.h" #include "common/utils.h" +#include "utils/http.h" namespace satdump { @@ -110,7 +111,7 @@ namespace satdump std::string url = "https://ssd.jpl.nasa.gov/api/horizons.api?format=text&COMMAND='*'"; std::string req_result; - perform_http_request(url, req_result); + satdump::perform_http_request(url, req_result); std::istringstream req_results(req_result); std::string line; diff --git a/src-core/common/tracking/obj_tracker/object_tracker_info.cpp b/src-core/common/tracking/obj_tracker/object_tracker_info.cpp index 9cb5498ea..ab51bc674 100644 --- a/src-core/common/tracking/obj_tracker/object_tracker_info.cpp +++ b/src-core/common/tracking/obj_tracker/object_tracker_info.cpp @@ -1,5 +1,6 @@ -#include "object_tracker.h" #include "common/utils.h" +#include "object_tracker.h" +#include "utils/time.h" namespace satdump { @@ -60,19 +61,12 @@ namespace satdump std::vector color_orange = {1, 165.0 / 255.0, 0}; std::vector color_cyan = {0, 237.0 / 255.0, 1}; - img.draw_circle(plot_size / 2, plot_size / 2, - radius1, color_green, false); - img.draw_circle(plot_size / 2, plot_size / 2, - radius2, color_green, false); - img.draw_circle(plot_size / 2, plot_size / 2, - radius3, color_green, false); + img.draw_circle(plot_size / 2, plot_size / 2, radius1, color_green, false); + img.draw_circle(plot_size / 2, plot_size / 2, radius2, color_green, false); + img.draw_circle(plot_size / 2, plot_size / 2, radius3, color_green, false); - img.draw_line(plot_size / 2, 0, - plot_size / 2, plot_size - 1, - color_green); - img.draw_line(0, plot_size / 2, - plot_size - 1, plot_size / 2, - color_green); + img.draw_line(plot_size / 2, 0, plot_size / 2, plot_size - 1, color_green); + img.draw_line(0, plot_size / 2, plot_size - 1, plot_size / 2, color_green); // Draw the satellite's trace if (upcoming_pass_points.size() > 1) @@ -93,9 +87,7 @@ namespace satdump point_x2 += az_el_to_plot_x(plot_size, radius, p2.az, p2.el); point_y2 -= az_el_to_plot_y(plot_size, radius, p2.az, p2.el); - img.draw_line(point_x1, point_y1, - point_x2, point_y2, - color_orange); + img.draw_line(point_x1, point_y1, point_x2, point_y2, color_orange); } upcoming_passes_mtx.unlock(); } @@ -141,4 +133,4 @@ namespace satdump return img; } -} +} // namespace satdump diff --git a/src-core/common/tracking/obj_tracker/object_tracker_render.cpp b/src-core/common/tracking/obj_tracker/object_tracker_render.cpp index 7827131f3..e1767301b 100644 --- a/src-core/common/tracking/obj_tracker/object_tracker_render.cpp +++ b/src-core/common/tracking/obj_tracker/object_tracker_render.cpp @@ -2,9 +2,10 @@ #include "common/geodetic/geodetic_coordinates.h" #include "imgui/imgui.h" #include "imgui/imgui_stdlib.h" -#include "common/utils.h" +#include "utils/string.h" #include "core/style.h" #include "common/tracking/tle.h" +#include "utils/time.h" namespace satdump { @@ -234,7 +235,7 @@ namespace satdump { bool show = true; if (horizons_searchstr.size() != 0) - show = isStringPresent(horizonsoptions[i].second, horizons_searchstr); + show = satdump::isStringPresent(horizonsoptions[i].second, horizons_searchstr); if (show) { if (ImGui::Selectable(horizonsoptions[i].second.c_str(), i == current_horizons_id)) diff --git a/src-core/common/tracking/obj_tracker/object_tracker_rotator.cpp b/src-core/common/tracking/obj_tracker/object_tracker_rotator.cpp index eb8d3c2e8..59258b266 100644 --- a/src-core/common/tracking/obj_tracker/object_tracker_rotator.cpp +++ b/src-core/common/tracking/obj_tracker/object_tracker_rotator.cpp @@ -6,6 +6,7 @@ #include #include "imgui/imgui.h" #include "core/style.h" +#include "utils/time.h" #include "common/widgets/azel_input.h" diff --git a/src-core/common/tracking/scheduler/scheduler.cpp b/src-core/common/tracking/scheduler/scheduler.cpp index 4f936648c..578e40c97 100644 --- a/src-core/common/tracking/scheduler/scheduler.cpp +++ b/src-core/common/tracking/scheduler/scheduler.cpp @@ -2,6 +2,7 @@ #include "logger.h" #include "core/plugin.h" #include "common/utils.h" +#include "utils/time.h" namespace satdump { diff --git a/src-core/common/tracking/scheduler/scheduler_ui.cpp b/src-core/common/tracking/scheduler/scheduler_ui.cpp index fa6d71a5a..e4237fabf 100644 --- a/src-core/common/tracking/scheduler/scheduler_ui.cpp +++ b/src-core/common/tracking/scheduler/scheduler_ui.cpp @@ -12,6 +12,9 @@ #include "common/widgets/frequency_input.h" #include "core/resources.h" #include "image/text.h" +#include "utils/time.h" +#include "utils/string.h" +#include "utils/format.h" namespace satdump { @@ -39,7 +42,7 @@ namespace satdump for (int i = 0; i < num_objects; i++) if (std::find_if(enabled_satellites.begin(), enabled_satellites.end(), [i, &tle_registry](TrackedObject &c) { return c.norad == (*tle_registry)[i].norad; }) == enabled_satellites.end()) - if (availablesatssearch.size() == 0 || isStringPresent(satoptions[i], availablesatssearch)) + if (availablesatssearch.size() == 0 || satdump::isStringPresent(satoptions[i], availablesatssearch)) { if (ImGui::Selectable(satoptions[i].c_str(), i == tracking_sats_menu_selected_1)) tracking_sats_menu_selected_1 = i; @@ -84,7 +87,7 @@ namespace satdump for (int i = 0; i < num_objects; i++) if (std::find_if(enabled_satellites.begin(), enabled_satellites.end(), [i, &tle_registry](TrackedObject &c) { return c.norad == (*tle_registry)[i].norad; }) != enabled_satellites.end()) - if (selectedsatssearch.size() == 0 || isStringPresent(satoptions[i], selectedsatssearch)) + if (selectedsatssearch.size() == 0 || satdump::isStringPresent(satoptions[i], selectedsatssearch)) { if (ImGui::Selectable(satoptions[i].c_str(), i == tracking_sats_menu_selected_2)) tracking_sats_menu_selected_2 = i; @@ -420,7 +423,7 @@ namespace satdump // ImGui::Dummy(ImVec2(0, 0)); for (int i = (timeReadable->tm_min < 30 ? 1 : 0); i < (timeReadable->tm_min < 30 ? 12 : 13); i++) { - text_drawer.draw_text(img, i * d_pplot_size / 12 - offset, 0, color_gray, 10, svformat("%s%s%s", (curr_hour + i) % 24 < 10 ? "0" : "", std::to_string((curr_hour + i) % 24).c_str(), ":00")); + text_drawer.draw_text(img, i * d_pplot_size / 12 - offset, 0, color_gray, 10, satdump::svformat("%s%s%s", (curr_hour + i) % 24 < 10 ? "0" : "", std::to_string((curr_hour + i) % 24).c_str(), ":00")); } float sat_blk_height = ((float)d_pplot_height / (float)enabled_satellites.size()); for (int i = 0; i < (int)enabled_satellites.size(); i++) diff --git a/src-core/common/tracking/tle.cpp b/src-core/common/tracking/tle.cpp index f156dd947..99a36ac01 100644 --- a/src-core/common/tracking/tle.cpp +++ b/src-core/common/tracking/tle.cpp @@ -10,6 +10,7 @@ #include #include #include "satdump_vars.h" +#include "utils/http.h" namespace satdump { @@ -111,7 +112,7 @@ namespace satdump int http_res = 1, trials = 0; while (http_res == 1 && trials < 10) { - if ((http_res = perform_http_request(url_str, result)) != 1) + if ((http_res = satdump::perform_http_request(url_str, result)) != 1) { std::istringstream tle_stream(result); success = parseTLEStream(tle_stream, new_registry) > 0; @@ -350,7 +351,7 @@ namespace satdump std::string result; curl_easy_setopt(curl, CURLOPT_POSTFIELDS, NULL); curl_easy_setopt(curl, CURLOPT_POST, 0); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_std_string); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, satdump::curl_write_std_string); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result); curl_easy_setopt(curl, CURLOPT_URL, final_url.c_str()); diff --git a/src-core/common/utils.cpp b/src-core/common/utils.cpp index a48838b09..23a64311d 100644 --- a/src-core/common/utils.cpp +++ b/src-core/common/utils.cpp @@ -4,11 +4,12 @@ #include "core/resources.h" #include #include +#include "logger.h" #include "core/config.h" #include "common/dsp_source_sink/format_notated.h" -#include + #include "satdump_vars.h" @@ -23,17 +24,7 @@ void signed_soft_to_unsigned(int8_t *in, uint8_t *out, int nsamples) } } -std::vector splitString(std::string input, char del) -{ - std::stringstream stcStream(input); - std::string seg; - std::vector segs; - while (std::getline(stcStream, seg, del)) - segs.push_back(seg); - - return segs; -} // Return filesize uint64_t getFilesize(std::string filepath) @@ -44,231 +35,11 @@ uint64_t getFilesize(std::string filepath) return fileSize; } -bool isStringPresent(std::string searched, std::string keyword) -{ - std::transform(searched.begin(), searched.end(), searched.begin(), tolower); - std::transform(keyword.begin(), keyword.end(), keyword.begin(), tolower); - auto found_it = searched.find(keyword, 0); - return found_it != std::string::npos; -} -#include "logger.h" -#include "satdump_vars.h" -size_t curl_write_std_string(void *contents, size_t size, size_t nmemb, std::string *s) -{ - size_t newLength = size * nmemb; - try - { - s->append((char *)contents, newLength); - } - catch (std::bad_alloc &) - { - return 0; - } - return newLength; -} -int curl_float_progress_func(void *ptr, curl_off_t TotalToDownload, curl_off_t NowDownloaded, curl_off_t TotalToUpload, curl_off_t NowUploaded) -{ - float *pptr = (float *)ptr; - if (TotalToDownload != 0) - *pptr = (float)NowDownloaded / (float)TotalToDownload; - else if (TotalToUpload != 0) - *pptr = (float)NowUploaded / (float)TotalToUpload; - return 0; -} -int perform_http_request(std::string url_str, std::string &result, std::string added_header, float *progress) -{ - CURL *curl; - CURLcode res; - bool ret = 1; - char error_buffer[CURL_ERROR_SIZE] = {0}; - - curl_global_init(CURL_GLOBAL_ALL); - - curl = curl_easy_init(); - if (curl) - { - curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buffer); - curl_easy_setopt(curl, CURLOPT_USERAGENT, std::string((std::string) "SatDump/v" + satdump::SATDUMP_VERSION).c_str()); - curl_easy_setopt(curl, CURLOPT_URL, url_str.c_str()); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_std_string); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result); - curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 100); - -#ifdef CURLSSLOPT_NATIVE_CA - curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA); -#endif - - struct curl_slist *chunk = NULL; - if (added_header != "") - { - /* Remove a header curl would otherwise add by itself */ - chunk = curl_slist_append(chunk, added_header.c_str()); - curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); - } - - if (progress != nullptr) - { - curl_easy_setopt(curl, CURLOPT_XFERINFODATA, progress); - curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, curl_float_progress_func); - curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false); - } - - res = curl_easy_perform(curl); - - if (res != CURLE_OK) - { - if (strlen(error_buffer)) - logger->error("curl_easy_perform() failed: %s", error_buffer); - else - logger->error("curl_easy_perform() failed: %s", curl_easy_strerror(res)); - } - else - ret = 0; - - curl_easy_cleanup(curl); - - if (chunk != NULL) - curl_slist_free_all(chunk); - } - curl_global_cleanup(); - return ret; -} - -int perform_http_request_post(std::string url_str, std::string &result, std::string post_req, std::string added_header) -{ - CURL *curl; - CURLcode res; - bool ret = 1; - char error_buffer[CURL_ERROR_SIZE] = {0}; - - curl_global_init(CURL_GLOBAL_ALL); - - curl = curl_easy_init(); - if (curl) - { - curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buffer); - curl_easy_setopt(curl, CURLOPT_USERAGENT, std::string((std::string) "SatDump/v" + satdump::SATDUMP_VERSION).c_str()); - curl_easy_setopt(curl, CURLOPT_URL, url_str.c_str()); - curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_req.c_str()); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_std_string); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result); - -#ifdef CURLSSLOPT_NATIVE_CA - curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA); -#endif - - struct curl_slist *chunk = NULL; - if (added_header != "") - { - /* Remove a header curl would otherwise add by itself */ - chunk = curl_slist_append(chunk, added_header.c_str()); - curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); - } - - res = curl_easy_perform(curl); - - if (res != CURLE_OK) - { - if (strlen(error_buffer)) - logger->error("curl_easy_perform() failed: %s", error_buffer); - else - logger->error("curl_easy_perform() failed: %s", curl_easy_strerror(res)); - } - else - ret = 0; - - curl_easy_cleanup(curl); - - if (chunk != NULL) - curl_slist_free_all(chunk); - } - curl_global_cleanup(); - return ret; -} - -std::string timestamp_to_string(double timestamp, bool local) -{ - if (timestamp < 0) - timestamp = 0; - - time_t tttime = timestamp; - std::tm *timeReadable = (local ? localtime(&tttime) : gmtime(&tttime)); - std::stringstream timestamp_string; - std::string timezone_string = ""; - - if (local) - { -#ifdef _WIN32 - size_t tznameSize = 0; - char *tznameBuffer = NULL; - timezone_string = " "; - _get_tzname(&tznameSize, NULL, 0, timeReadable->tm_isdst); - if (tznameSize > 0) - { - if (nullptr != (tznameBuffer = (char *)(malloc(tznameSize)))) - { - if (_get_tzname(&tznameSize, tznameBuffer, tznameSize, timeReadable->tm_isdst) == 0) - for (size_t i = 0; i < tznameSize; i++) - if (std::isupper(tznameBuffer[i])) - timezone_string += tznameBuffer[i]; - - free(tznameBuffer); - } - } - if (timezone_string == " ") - timezone_string = " Local"; -#else - timezone_string = " " + std::string(timeReadable->tm_zone); -#endif - } - - timestamp_string << std::setfill('0') - << timeReadable->tm_year + 1900 << "/" - << std::setw(2) << timeReadable->tm_mon + 1 << "/" - << std::setw(2) << timeReadable->tm_mday << " " - << std::setw(2) << timeReadable->tm_hour << ":" - << std::setw(2) << timeReadable->tm_min << ":" - << std::setw(2) << timeReadable->tm_sec - << timezone_string; - - return timestamp_string.str(); -} - -double get_median(std::vector values) -{ - if (values.size() == 0) - return 0; - std::sort(values.begin(), values.end()); - size_t middle = values.size() / 2; - return values[middle]; -} - -std::string loadFileToString(std::string path) -{ - std::ifstream f(path); - std::string str = std::string(std::istreambuf_iterator{f}, {}); - f.close(); - return str; -} - -std::string ws2s(const std::wstring &wstr) -{ - using convert_typeX = std::codecvt_utf8; - std::wstring_convert converterX; - return converterX.to_bytes(wstr); -} - -std::wstring s2ws(const std::string &str) -{ - using convert_typeX = std::codecvt_utf8; - std::wstring_convert converterX; - return converterX.from_bytes(str); -} std::string prepareAutomatedPipelineFolder(time_t timevalue, double frequency, std::string pipeline_name, std::string folder) { diff --git a/src-core/common/utils.h b/src-core/common/utils.h index 536066eea..c1b3831fb 100644 --- a/src-core/common/utils.h +++ b/src-core/common/utils.h @@ -18,46 +18,9 @@ void char_array_to_uchar(int8_t *in, uint8_t *out, int nsamples); void signed_soft_to_unsigned(int8_t *in, uint8_t *out, int nsamples); -template ::value_type> -T most_common(InputIt begin, InputIt end, T def) -{ - if (begin == end) - return def; - std::map counts; - for (InputIt it = begin; it != end; ++it) - { - if (counts.find(*it) != counts.end()) - ++counts[*it]; - else - counts[*it] = 1; - } - return std::max_element(counts.begin(), counts.end(), [](const std::pair &pair1, const std::pair &pair2) - { return pair1.second < pair2.second; }) - ->first; -} -template ::value_type> -T average_common(InputIt begin, InputIt end) -{ - T avg = 0; - size_t count = 0; - for (InputIt it = begin; it != end; ++it) - { - avg += *it; - count++; - } - return avg / T(count); -} -template -std::string to_string_with_precision(const T a_value, const int n = 6) -{ - std::ostringstream out; - out.precision(n); - out << std::fixed << a_value; - return out.str(); -} template T swap_endian(T u) @@ -76,44 +39,7 @@ T swap_endian(T u) return dest.u; } -template -int percentile(T *array, int size, float percentile) -{ - float number_percent = (size + 1) * percentile / 100.0f; - if (number_percent == 1) - return array[0]; - else if (number_percent == size) - return array[size - 1]; - else - return array[(int)number_percent - 1] + (number_percent - (int)number_percent) * (array[(int)number_percent] - array[(int)number_percent - 1]); -} -template -double avg_overflowless(std::vector const &v) -{ - T n = 0; - double mean = 0.0; - for (auto x : v) - { - double delta = x - mean; - mean += delta / ++n; - } - return mean; -} - -std::vector splitString(std::string input, char del); - -inline void replaceAllStr(std::string &str, const std::string &from, const std::string &to) -{ - if (from.empty()) - return; - size_t start_pos = 0; - while ((start_pos = str.find(from, start_pos)) != std::string::npos) - { - str.replace(start_pos, from.length(), to); - start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx' - } -} template inline bool getBit(T &data, int &bit) @@ -121,22 +47,9 @@ inline bool getBit(T &data, int &bit) return (data >> bit) & 1; } -bool isStringPresent(std::string searched, std::string keyword); - // Return filesize uint64_t getFilesize(std::string filepath); -// cURL helper function -size_t curl_write_std_string(void *contents, size_t size, size_t nmemb, std::string *s); - -// Perform a HTTP Request on the provided URL and return the result as a string -int perform_http_request(std::string url, std::string &result, std::string added_header = "", float *progress = nullptr); - -// Perform a HTTP Request on the provided URL and return the result as a string, with POST data -int perform_http_request_post(std::string url_str, std::string &result, std::string post_req, std::string added_header = ""); - -std::string timestamp_to_string(double timestamp, bool local = false); - inline std::vector double_buffer_to_float(double *ptr, int size) { std::vector ret; @@ -145,7 +58,7 @@ inline std::vector double_buffer_to_float(double *ptr, int size) return ret; } -double get_median(std::vector values); + template std::vector unsigned_to_bitvec(T v) @@ -166,49 +79,12 @@ std::vector oversample_vector(std::vector data, int oversampling) return r; } -template -std::string svformat(const char *fmt, T &&...args) -{ - // Allocate a buffer on the stack that's big enough for us almost - // all the time. - size_t size = 1024; - std::vector buf; - buf.resize(size); - // Try to vsnprintf into our buffer. - size_t needed = snprintf((char *)&buf[0], size, fmt, args...); - // NB. On Windows, vsnprintf returns -1 if the string didn't fit the - // buffer. On Linux & OSX, it returns the length it would have needed. - if (needed <= size) - { - // It fit fine the first time, we're done. - return std::string(&buf[0]); - } - else - { - // vsnprintf reported that it wanted to write more characters - // than we allotted. So do a malloc of the right size and try again. - // This doesn't happen very often if we chose our initial size - // well. - size = needed; - buf.resize(size); - needed = snprintf((char *)&buf[0], size, fmt, args...); - return std::string(&buf[0]); - } -} -inline double getTime() -{ - auto time = std::chrono::system_clock::now(); - auto since_epoch = time.time_since_epoch(); - auto millis = std::chrono::duration_cast(since_epoch); - return millis.count() / 1e3; -} -std::string loadFileToString(std::string path); -std::string ws2s(const std::wstring &wstr); -std::wstring s2ws(const std::string &str); + + std::string prepareAutomatedPipelineFolder(time_t timevalue, double frequency, std::string pipeline_name, std::string folder = ""); std::string prepareBasebandFileName(double timeValue_precise, uint64_t samplerate, uint64_t frequency); diff --git a/src-core/common/widgets/pipeline_selector.cpp b/src-core/common/widgets/pipeline_selector.cpp index e52a551ef..077a05f2d 100644 --- a/src-core/common/widgets/pipeline_selector.cpp +++ b/src-core/common/widgets/pipeline_selector.cpp @@ -7,6 +7,7 @@ #include "common/detect_header.h" #include "common/widgets/json_editor.h" #include "logger.h" +#include "utils/string.h" #include @@ -168,7 +169,7 @@ namespace satdump int n = favourite[k]; bool show = true; if (pipeline_search_in.size() != 0) - show = isStringPresent(pipelines[n].readable_name, pipeline_search_in); + show = satdump::isStringPresent(pipelines[n].readable_name, pipeline_search_in); if (show && (!live_mode || pipelines[n].live)) { @@ -216,7 +217,7 @@ namespace satdump { bool show = true; if (pipeline_search_in.size() != 0) - show = isStringPresent(pipelines[n].readable_name, pipeline_search_in); + show = satdump::isStringPresent(pipelines[n].readable_name, pipeline_search_in); if (show && (!live_mode || pipelines[n].live)) { diff --git a/src-core/core/plugin.h b/src-core/core/plugin.h index 2813b1da9..fb2155b26 100644 --- a/src-core/core/plugin.h +++ b/src-core/core/plugin.h @@ -5,7 +5,7 @@ #include #include "common/event_bus.h" -#include "common/task_scheduler.h" +#include "utils/task_scheduler.h" #define PLUGIN_LOADER(constructor) \ extern "C" \ diff --git a/src-core/dsp/flowgraph/flowgraph.cpp b/src-core/dsp/flowgraph/flowgraph.cpp index a74aa8ea1..9cbf59733 100644 --- a/src-core/dsp/flowgraph/flowgraph.cpp +++ b/src-core/dsp/flowgraph/flowgraph.cpp @@ -7,7 +7,7 @@ #include "imgui/imnodes/imnodes_internal.h" #include "logger.h" -#include "common/utils.h" +#include "utils/string.h" #include "dsp/path/splitter.h" diff --git a/src-core/handlers/dataset/dataset_handler.cpp b/src-core/handlers/dataset/dataset_handler.cpp index 4c8ad7b25..b5bf5d498 100644 --- a/src-core/handlers/dataset/dataset_handler.cpp +++ b/src-core/handlers/dataset/dataset_handler.cpp @@ -6,7 +6,7 @@ #include "../product/image_product_handler.h" // TODOREWORK CLEAN #include "../product/punctiform_product_handler.h" // TODOREWORK CLEAN -#include "common/utils.h" +#include "utils/time.h" namespace satdump { diff --git a/src-core/handlers/image/image_handler.cpp b/src-core/handlers/image/image_handler.cpp index d5b650d1c..04c116c88 100644 --- a/src-core/handlers/image/image_handler.cpp +++ b/src-core/handlers/image/image_handler.cpp @@ -18,7 +18,7 @@ #include "../vector/shapefile_handler.h" -#include "common/utils.h" +#include "utils/string.h" #include "core/config.h" #include "imgui/dialogs/pfd_utils.h" // TODOREWORK diff --git a/src-core/handlers/product/product_handler.cpp b/src-core/handlers/product/product_handler.cpp index 79af4790b..715f53201 100644 --- a/src-core/handlers/product/product_handler.cpp +++ b/src-core/handlers/product/product_handler.cpp @@ -1,5 +1,6 @@ #include "product_handler.h" -#include "common/utils.h" +#include "utils/string.h" +#include "utils/time.h" #include "core/config.h" #include "core/exception.h" #include "imgui/imgui_stdlib.h" diff --git a/src-core/image/expression.cpp b/src-core/image/expression.cpp index 9cc42c241..2e7ceaa7c 100644 --- a/src-core/image/expression.cpp +++ b/src-core/image/expression.cpp @@ -1,5 +1,5 @@ #include "expression.h" -#include "common/utils.h" +#include "utils/string.h" #include "core/exception.h" #include "image/meta.h" #include "libs/muparser/muParser.h" diff --git a/src-core/products2/dataset.cpp b/src-core/products2/dataset.cpp index 06d8be041..6aa1fdded 100644 --- a/src-core/products2/dataset.cpp +++ b/src-core/products2/dataset.cpp @@ -1,6 +1,6 @@ #include "dataset.h" #include "nlohmann/json_utils.h" -#include "common/utils.h" +#include "utils/http.h" #include "core/exception.h" namespace satdump diff --git a/src-core/products2/image/product_expression.cpp b/src-core/products2/image/product_expression.cpp index 3f96747ea..bd3c1342d 100644 --- a/src-core/products2/image/product_expression.cpp +++ b/src-core/products2/image/product_expression.cpp @@ -4,7 +4,7 @@ #include "libs/muparser/muParser.h" #include "logger.h" -#include "common/utils.h" +#include "utils/string.h" #include "products2/image/image_calibrator.h" #include "image/io.h" diff --git a/src-core/products2/image_product.cpp b/src-core/products2/image_product.cpp index 1fd8ef3e1..b4feddc9d 100644 --- a/src-core/products2/image_product.cpp +++ b/src-core/products2/image_product.cpp @@ -1,7 +1,7 @@ #include "image_product.h" #include "logger.h" #include "core/config.h" -#include "common/utils.h" +#include "utils/http.h" #include "image/io.h" #include "image/image_utils.h" diff --git a/src-core/products2/image_product.h b/src-core/products2/image_product.h index 39a9e5e4d..b6cdefc0f 100644 --- a/src-core/products2/image_product.h +++ b/src-core/products2/image_product.h @@ -5,7 +5,7 @@ */ #include "image/image.h" -#include "common/utils.h" +#include "utils/stats.h" #include "image/channel_transform.h" #include "product.h" diff --git a/src-core/products2/product.cpp b/src-core/products2/product.cpp index c311f6f4a..9b7536641 100644 --- a/src-core/products2/product.cpp +++ b/src-core/products2/product.cpp @@ -1,5 +1,5 @@ #include "product.h" -#include "common/utils.h" +#include "utils/http.h" #include "core/exception.h" #include "core/plugin.h" #include "logger.h" diff --git a/src-core/projection/warp/warp.cpp b/src-core/projection/warp/warp.cpp index 32fc4e8e0..24e0af0c7 100644 --- a/src-core/projection/warp/warp.cpp +++ b/src-core/projection/warp/warp.cpp @@ -7,6 +7,7 @@ #include "core/opencl.h" #include #include +#include "utils/stats.h" #include "common/geodetic/geodetic_coordinates.h" diff --git a/src-core/utils/format.h b/src-core/utils/format.h new file mode 100644 index 000000000..64bfc6467 --- /dev/null +++ b/src-core/utils/format.h @@ -0,0 +1,68 @@ +#pragma once + +/** + * @file format.h + */ + +#include +#include + +namespace satdump +{ + /** + * @brief Format a number to string with a specific + * float precision + * + * @param a_value the number to format + * @param n precision to use + * @return formatted string + */ + template + std::string to_string_with_precision(const T a_value, const int n = 6) + { + std::ostringstream out; + out.precision(n); + out << std::fixed << a_value; + return out.str(); + } + + /** + * @brief Format a std::string with a standard printf + * formatting pattern. + * + * @param fmt formatting string + * @param args arguments + * @return formatted string + */ + template + std::string svformat(const char *fmt, T &&...args) + { + // Allocate a buffer on the stack that's big enough for us almost + // all the time. + size_t size = 1024; + std::vector buf; + buf.resize(size); + + // Try to vsnprintf into our buffer. + size_t needed = snprintf((char *)&buf[0], size, fmt, args...); + // NB. On Windows, vsnprintf returns -1 if the string didn't fit the + // buffer. On Linux & OSX, it returns the length it would have needed. + + if (needed <= size) + { + // It fit fine the first time, we're done. + return std::string(&buf[0]); + } + else + { + // vsnprintf reported that it wanted to write more characters + // than we allotted. So do a malloc of the right size and try again. + // This doesn't happen very often if we chose our initial size + // well. + size = needed; + buf.resize(size); + needed = snprintf((char *)&buf[0], size, fmt, args...); + return std::string(&buf[0]); + } + } +} // namespace satdump \ No newline at end of file diff --git a/src-core/utils/http.cpp b/src-core/utils/http.cpp new file mode 100644 index 000000000..420cef23d --- /dev/null +++ b/src-core/utils/http.cpp @@ -0,0 +1,143 @@ +#include "http.h" +#include "logger.h" +#include "satdump_vars.h" +#include +#include + +namespace satdump +{ + size_t curl_write_std_string(void *contents, size_t size, size_t nmemb, std::string *s) + { + size_t newLength = size * nmemb; + try + { + s->append((char *)contents, newLength); + } + catch (std::bad_alloc &) + { + return 0; + } + return newLength; + } + + int curl_float_progress_func(void *ptr, curl_off_t TotalToDownload, curl_off_t NowDownloaded, curl_off_t TotalToUpload, curl_off_t NowUploaded) + { + float *pptr = (float *)ptr; + if (TotalToDownload != 0) + *pptr = (float)NowDownloaded / (float)TotalToDownload; + else if (TotalToUpload != 0) + *pptr = (float)NowUploaded / (float)TotalToUpload; + return 0; + } + + int perform_http_request(std::string url_str, std::string &result, std::string added_header, float *progress) + { + CURL *curl; + CURLcode res; + bool ret = 1; + char error_buffer[CURL_ERROR_SIZE] = {0}; + + curl_global_init(CURL_GLOBAL_ALL); + + curl = curl_easy_init(); + if (curl) + { + curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buffer); + curl_easy_setopt(curl, CURLOPT_USERAGENT, std::string((std::string) "SatDump/v" + satdump::SATDUMP_VERSION).c_str()); + curl_easy_setopt(curl, CURLOPT_URL, url_str.c_str()); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_std_string); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result); + curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 100); + +#ifdef CURLSSLOPT_NATIVE_CA + curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA); +#endif + + struct curl_slist *chunk = NULL; + if (added_header != "") + { + /* Remove a header curl would otherwise add by itself */ + chunk = curl_slist_append(chunk, added_header.c_str()); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); + } + + if (progress != nullptr) + { + curl_easy_setopt(curl, CURLOPT_XFERINFODATA, progress); + curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, curl_float_progress_func); + curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false); + } + + res = curl_easy_perform(curl); + + if (res != CURLE_OK) + { + if (strlen(error_buffer)) + logger->error("curl_easy_perform() failed: %s", error_buffer); + else + logger->error("curl_easy_perform() failed: %s", curl_easy_strerror(res)); + } + else + ret = 0; + + curl_easy_cleanup(curl); + + if (chunk != NULL) + curl_slist_free_all(chunk); + } + curl_global_cleanup(); + return ret; + } + + int perform_http_request_post(std::string url_str, std::string &result, std::string post_req, std::string added_header) + { + CURL *curl; + CURLcode res; + bool ret = 1; + char error_buffer[CURL_ERROR_SIZE] = {0}; + + curl_global_init(CURL_GLOBAL_ALL); + + curl = curl_easy_init(); + if (curl) + { + curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buffer); + curl_easy_setopt(curl, CURLOPT_USERAGENT, std::string((std::string) "SatDump/v" + satdump::SATDUMP_VERSION).c_str()); + curl_easy_setopt(curl, CURLOPT_URL, url_str.c_str()); + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_req.c_str()); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_std_string); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result); + +#ifdef CURLSSLOPT_NATIVE_CA + curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA); +#endif + + struct curl_slist *chunk = NULL; + if (added_header != "") + { + /* Remove a header curl would otherwise add by itself */ + chunk = curl_slist_append(chunk, added_header.c_str()); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); + } + + res = curl_easy_perform(curl); + + if (res != CURLE_OK) + { + if (strlen(error_buffer)) + logger->error("curl_easy_perform() failed: %s", error_buffer); + else + logger->error("curl_easy_perform() failed: %s", curl_easy_strerror(res)); + } + else + ret = 0; + + curl_easy_cleanup(curl); + + if (chunk != NULL) + curl_slist_free_all(chunk); + } + curl_global_cleanup(); + return ret; + } +} // namespace satdump \ No newline at end of file diff --git a/src-core/utils/http.h b/src-core/utils/http.h new file mode 100644 index 000000000..b6a9973af --- /dev/null +++ b/src-core/utils/http.h @@ -0,0 +1,42 @@ +#pragma once + +/** + * @file http.h + */ + +#include + +namespace satdump +{ + /** + * @brief cURL helper function, writing + * the payload into a std::string + * + * TODOREWORK document + */ + size_t curl_write_std_string(void *contents, size_t size, size_t nmemb, std::string *s); + + /** + * @brief Perform a HTTP Request on the + * provided URL and return the result as + * a string. + * + * @param url_str URL to use + * @param result HTTP response, as a string + * @param added_header optional additional headers + * @param progress optional progress float pointer + */ + int perform_http_request(std::string url, std::string &result, std::string added_header = "", float *progress = nullptr); + + /** + * @brief Perform a HTTP Request on the + * provided URL and return the result as + * a string, with POST data. + * + * @param url_str URL to use + * @param result HTTP response, as a string + * @param post_req POST payload + * @param added_header optional additional headers + */ + int perform_http_request_post(std::string url_str, std::string &result, std::string post_req, std::string added_header = ""); +} // namespace satdump \ No newline at end of file diff --git a/src-core/utils/stats.cpp b/src-core/utils/stats.cpp new file mode 100644 index 000000000..21b8fc108 --- /dev/null +++ b/src-core/utils/stats.cpp @@ -0,0 +1,13 @@ +#include "stats.h" + +namespace satdump +{ + double get_median(std::vector values) + { + if (values.size() == 0) + return 0; + std::sort(values.begin(), values.end()); + size_t middle = values.size() / 2; + return values[middle]; + } +} // namespace satdump \ No newline at end of file diff --git a/src-core/utils/stats.h b/src-core/utils/stats.h new file mode 100644 index 000000000..dbe8226f6 --- /dev/null +++ b/src-core/utils/stats.h @@ -0,0 +1,109 @@ +#pragma once + +/** + * @file stats.h + */ + +#include +#include +#include + +namespace satdump +{ + /** + * @brief Return the most common element within the + * provided sequence. + * + * @param begin First iterator + * @param end last iterator + * @param def default if we don't have enough elements + * @return most common element OR default + */ + template ::value_type> + T most_common(InputIt begin, InputIt end, T def) + { + if (begin == end) + return def; + + std::map counts; + for (InputIt it = begin; it != end; ++it) + { + if (counts.find(*it) != counts.end()) + ++counts[*it]; + else + counts[*it] = 1; + } + return std::max_element(counts.begin(), counts.end(), [](const std::pair &pair1, const std::pair &pair2) { return pair1.second < pair2.second; })->first; + } + + /** + * @brief Returns the average of the provided + * elements. + * + * @param begin First iterator + * @param end last iterator + * @return average of elements + */ + template ::value_type> + T average_common(InputIt begin, InputIt end) + { + T avg = 0; + size_t count = 0; + for (InputIt it = begin; it != end; ++it) + { + avg += *it; + count++; + } + return avg / T(count); + } + + /** + * @brief Returns a percentile of the provided array + * + * @param array to work with + * @param size of the array, in elements + * @param percentile to return + * @return the percentile + */ + template + T percentile(T *array, int size, float percentile) + { + float number_percent = (size + 1) * percentile / 100.0f; + if (number_percent == 1) + return array[0]; + else if (number_percent == size) + return array[size - 1]; + else + return array[(int)number_percent - 1] + (number_percent - (int)number_percent) * (array[(int)number_percent] - array[(int)number_percent - 1]); + } + + /** + * @brief Returns the average of the provided + * elements. Version that won't overflow with + * very large numbers and amount of elements. + * + * @param v Vector to average + * @return average of elements + */ + template + double avg_overflowless(std::vector const &v) + { + T n = 0; + double mean = 0.0; + for (auto x : v) + { + double delta = x - mean; + mean += delta / ++n; + } + return mean; + } + + /** + * @brief Returns the median of the provided + * elements. + * + * @param values input vector + * @return median of the elements + */ + double get_median(std::vector values); +} // namespace satdump \ No newline at end of file diff --git a/src-core/utils/string.cpp b/src-core/utils/string.cpp new file mode 100644 index 000000000..8733a079f --- /dev/null +++ b/src-core/utils/string.cpp @@ -0,0 +1,64 @@ +#include "string.h" +#include +#include +#include +#include +#include + +namespace satdump +{ + std::vector splitString(std::string input, char del) + { + std::stringstream stcStream(input); + std::string seg; + std::vector segs; + + while (std::getline(stcStream, seg, del)) + segs.push_back(seg); + + return segs; + } + + void replaceAllStr(std::string &str, const std::string &from, const std::string &to) + { + if (from.empty()) + return; + size_t start_pos = 0; + while ((start_pos = str.find(from, start_pos)) != std::string::npos) + { + str.replace(start_pos, from.length(), to); + start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx' + } + } + + bool isStringPresent(std::string searched, std::string keyword) + { + std::transform(searched.begin(), searched.end(), searched.begin(), tolower); + std::transform(keyword.begin(), keyword.end(), keyword.begin(), tolower); + + auto found_it = searched.find(keyword, 0); + return found_it != std::string::npos; + } + + std::string loadFileToString(std::string path) + { + std::ifstream f(path); + std::string str = std::string(std::istreambuf_iterator{f}, {}); + f.close(); + return str; + } + + std::string ws2s(const std::wstring &wstr) + { + using convert_typeX = std::codecvt_utf8; + std::wstring_convert converterX; + return converterX.to_bytes(wstr); + } + + std::wstring s2ws(const std::string &str) + { + using convert_typeX = std::codecvt_utf8; + std::wstring_convert converterX; + return converterX.from_bytes(str); + } +} // namespace satdump \ No newline at end of file diff --git a/src-core/utils/string.h b/src-core/utils/string.h new file mode 100644 index 000000000..0bd09ad00 --- /dev/null +++ b/src-core/utils/string.h @@ -0,0 +1,65 @@ +#pragma once + +/** + * @file string.h + */ + +#include +#include + +namespace satdump +{ + /** + * @brief Split a string into multiples where + * a specific char is present. + * + * @param input the string to split + * @param del delimiter character + * @return string segments + */ + std::vector splitString(std::string input, char del); + + /** + * @brief Replaces all occurences of a string in + * a string with another string. (lots of strings!) + * + * @param str the string to replace in + * @param from pattern to replace + * @param to pattern to replace the old pattern with + */ + void replaceAllStr(std::string &str, const std::string &from, const std::string &to); + + /** + * @brief Check if a pattern is present in the + * provided string. Case-insensitive + * + * @param searched string to search in + * @param keyword pattern to search + * @return true if present + */ + bool isStringPresent(std::string searched, std::string keyword); + + /** + * @brief Load a text file into a std::string + * + * @param path file path + * @return loaded string + */ + std::string loadFileToString(std::string path); + + /** + * @brief Convert a std::wstring to std::string + * + * @param wstr input std::wstring + * @return output std::string + */ + std::string ws2s(const std::wstring &wstr); + + /** + * @brief Convert a std::string to std::wstring + * + * @param wstr input std::string + * @return output std::wstring + */ + std::wstring s2ws(const std::string &str); +} // namespace satdump \ No newline at end of file diff --git a/src-core/common/task_scheduler.cpp b/src-core/utils/task_scheduler.cpp similarity index 100% rename from src-core/common/task_scheduler.cpp rename to src-core/utils/task_scheduler.cpp diff --git a/src-core/common/task_scheduler.h b/src-core/utils/task_scheduler.h similarity index 100% rename from src-core/common/task_scheduler.h rename to src-core/utils/task_scheduler.h diff --git a/src-core/utils/thread_priority.cpp b/src-core/utils/thread_priority.cpp new file mode 100644 index 000000000..0839529ba --- /dev/null +++ b/src-core/utils/thread_priority.cpp @@ -0,0 +1,66 @@ +#include "thread_priority.h" + +#include "logger.h" +#ifdef _WIN32 +#include +#endif + +namespace satdump +{ + void setThreadPriority(std::thread &th, thread_priority_t priority) + { +#ifdef _WIN32 + if (SetThreadPriority(th.native_handle(), priority) == 0) + logger->error("Could not set thread priority!"); +#else + sched_param sch_params; + int policy = 0; + pthread_getschedparam(th.native_handle(), &policy, &sch_params); + sch_params.sched_priority = priority; + if (pthread_setschedparam(th.native_handle(), SCHED_RR, &sch_params)) + logger->error("Could not set thread priority!"); +#endif + } + + void setLowestThreadPriority(std::thread &th) + { +#ifdef _WIN32 + if (SetThreadPriority(th.native_handle(), -2) == 0) + logger->error("Could not set thread priority!"); +#elif defined(__APPLE__) + sched_param sch_params; + int policy = 0; + pthread_getschedparam(th.native_handle(), &policy, &sch_params); + sch_params.sched_priority = PRIORITY_LOWEST; + if (pthread_setschedparam(th.native_handle(), SCHED_RR, &sch_params)) + logger->error("Could not set thread priority!"); +#else + sched_param sch_params; + int policy = 0; + pthread_getschedparam(th.native_handle(), &policy, &sch_params); + if (pthread_setschedparam(th.native_handle(), SCHED_IDLE, &sch_params)) + logger->error("Could not set thread priority!"); +#endif + } + + void setLowestThreadPriority() + { +#ifdef _WIN32 + if (SetThreadPriority(GetCurrentThread(), -2) == 0) + logger->error("Could not set thread priority!"); +#elif defined(__APPLE__) + sched_param sch_params; + int policy = 0; + pthread_getschedparam(pthread_self(), &policy, &sch_params); + sch_params.sched_priority = PRIORITY_LOWEST; + if (pthread_setschedparam(pthread_self(), SCHED_RR, &sch_params)) + logger->error("Could not set thread priority!"); +#else + sched_param sch_params; + int policy = 0; + pthread_getschedparam(pthread_self(), &policy, &sch_params); + if (pthread_setschedparam(pthread_self(), SCHED_IDLE, &sch_params)) + logger->error("Could not set thread priority!"); +#endif + } +} // namespace satdump \ No newline at end of file diff --git a/src-core/utils/thread_priority.h b/src-core/utils/thread_priority.h new file mode 100644 index 000000000..35b779eee --- /dev/null +++ b/src-core/utils/thread_priority.h @@ -0,0 +1,50 @@ +#pragma once + +/** + * @file thread_priority.h + */ + +#include + +namespace satdump +{ + enum thread_priority_t + { +#ifdef _WIN32 + PRIORITY_LOWEST = -2, + PRIORITY_LOW = -1, + PRIORITY_NORMAL = 0, + PRIORITY_HIGH = 1, + PRIORITY_HIGHEST = 2, +#else + PRIORITY_LOWEST = 1, + PRIORITY_LOW = 24, + PRIORITY_NORMAL = 50, + PRIORITY_HIGH = 74, + PRIORITY_HIGHEST = 99, +#endif + }; + + /** + * @brief Set specified thread priority + * on the specified thread. + * + * @param th the thread to apply to + * @param priority priority to set + */ + void setThreadPriority(std::thread &th, thread_priority_t priority); + + /** + * @brief Set lowest possible thread priority + * on the specified thread. + * + * @param th the thread to apply to + */ + void setLowestThreadPriority(std::thread &th); + + /** + * @brief Set lowest possible thread priority + * on the current thread. + */ + void setLowestThreadPriority(); +} // namespace satdump \ No newline at end of file diff --git a/src-core/utils/time.cpp b/src-core/utils/time.cpp new file mode 100644 index 000000000..fefb3509a --- /dev/null +++ b/src-core/utils/time.cpp @@ -0,0 +1,61 @@ +#include "time.h" +#include + +namespace satdump +{ + double getTime() + { + auto time = std::chrono::system_clock::now(); + auto since_epoch = time.time_since_epoch(); + auto millis = std::chrono::duration_cast(since_epoch); + return millis.count() / 1e3; + } + + std::string timestamp_to_string(double timestamp, bool local) + { + if (timestamp < 0) + timestamp = 0; + + time_t tttime = timestamp; + std::tm *timeReadable = (local ? localtime(&tttime) : gmtime(&tttime)); + std::stringstream timestamp_string; + std::string timezone_string = ""; + + if (local) + { +#ifdef _WIN32 + size_t tznameSize = 0; + char *tznameBuffer = NULL; + timezone_string = " "; + _get_tzname(&tznameSize, NULL, 0, timeReadable->tm_isdst); + if (tznameSize > 0) + { + if (nullptr != (tznameBuffer = (char *)(malloc(tznameSize)))) + { + if (_get_tzname(&tznameSize, tznameBuffer, tznameSize, timeReadable->tm_isdst) == 0) + for (size_t i = 0; i < tznameSize; i++) + if (std::isupper(tznameBuffer[i])) + timezone_string += tznameBuffer[i]; + + free(tznameBuffer); + } + } + if (timezone_string == " ") + timezone_string = " Local"; +#else + timezone_string = " " + std::string(timeReadable->tm_zone); +#endif + } + + timestamp_string << std::setfill('0') // + << timeReadable->tm_year + 1900 << "/" // + << std::setw(2) << timeReadable->tm_mon + 1 << "/" // + << std::setw(2) << timeReadable->tm_mday << " " // + << std::setw(2) << timeReadable->tm_hour << ":" // + << std::setw(2) << timeReadable->tm_min << ":" // + << std::setw(2) << timeReadable->tm_sec // + << timezone_string; + + return timestamp_string.str(); + } +} // namespace satdump \ No newline at end of file diff --git a/src-core/utils/time.h b/src-core/utils/time.h new file mode 100644 index 000000000..a806e9a22 --- /dev/null +++ b/src-core/utils/time.h @@ -0,0 +1,30 @@ +#pragma once + +/** + * @file time.h + */ + +#include +#include + +namespace satdump +{ + /** + * @brief Get high-precision current UNIX + * time (milliseconds-level). + * + * @return UNIX timestamps in seconds + */ + double getTime(); + + /** + * @brief Format an unit timestamp to + * string. + * + * @param timestamp UNIX Timestamps in seconds + * @param local format to local time. UTC (false) + * by default + * @return String in YYYY/MM/DD HH:MM:SS format + */ + std::string timestamp_to_string(double timestamp, bool local = false); +} // namespace satdump \ No newline at end of file diff --git a/src-interface/recorder/recorder_proc.cpp b/src-interface/recorder/recorder_proc.cpp index c7b537eee..7d64be29b 100644 --- a/src-interface/recorder/recorder_proc.cpp +++ b/src-interface/recorder/recorder_proc.cpp @@ -3,6 +3,7 @@ #include "main_ui.h" #include "logger.h" #include "processing.h" +#include "utils/time.h" #ifndef _MSC_VER #include diff --git a/src-interface/recorder/recorder_vfo.cpp b/src-interface/recorder/recorder_vfo.cpp index f0d2a8cce..d2eb9fa7f 100644 --- a/src-interface/recorder/recorder_vfo.cpp +++ b/src-interface/recorder/recorder_vfo.cpp @@ -4,6 +4,7 @@ #include "logger.h" #include "processing.h" #include "common/utils.h" +#include "utils/time.h" namespace satdump { diff --git a/src-interface/recorder/tracking/tracking_widget.cpp b/src-interface/recorder/tracking/tracking_widget.cpp index ed9ce5b81..bc1824a7b 100644 --- a/src-interface/recorder/tracking/tracking_widget.cpp +++ b/src-interface/recorder/tracking/tracking_widget.cpp @@ -6,6 +6,7 @@ #include "core/style.h" #include "common/imgui_utils.h" #include "common/tracking/rotator/rotcl_handler.h" +#include "utils/time.h" namespace satdump { diff --git a/src-testing/main.cpp b/src-testing/main.cpp index d666c2b52..63a3543f7 100644 --- a/src-testing/main.cpp +++ b/src-testing/main.cpp @@ -10,52 +10,378 @@ * Don't judge the code you might see in there! :) **********************************************************************/ +#include "common/geodetic/calc_azel.h" +#include "common/geodetic/geodetic_coordinates.h" +#include "common/geodetic/wgs84.h" +#include "common/utils.h" #include "logger.h" - -#include "common/ccsds/ccsds_tm/demuxer.h" -#include "common/ccsds/ccsds_tm/vcdu.h" -#include "common/simple_deframer.h" -#include - -#include "image/image.h" -#include "image/io.h" -#include "image/processing.h" - +#include "nutation.h" +#include +#include #include +#include +#include -#include "common/repack.h" +#if 1 +extern "C" +{ +#include -#include "image/bayer/bayer.h" +#include +#include +} -#include "common/codings/reedsolomon/reedsolomon.h" +// Below are some Earth orientation values. Here we define them as constants, but they may +// of course be variables. They should be set to the appropriate values for the time +// of observation based on the IERS Bulletins... + +#define LEAP_SECONDS 37 ///< [s] current leap seconds from IERS Bulletin C +#define DUT1 0.114 ///< [s] current UT1 - UTC time difference from IERS Bulletin A +#define POLAR_DX (0.0863 / 1000.0) // 230.0 ///< [mas] Earth polar offset x, e.g. from IERS Bulletin A. +#define POLAR_DY (0.4178 / 1000.0) // -62.0 ///< [mas] Earth polar offset y, e.g. from IERS Bulletin A. +#endif + +#define ENABLE_CUSTOM_AZ_EL 1 + +#if ENABLE_CUSTOM_AZ_EL +namespace t +{ + struct vector + { + double x; + double y; + double z; + }; + + // Must already be in radians! + void lla2xyz(geodetic::geodetic_coords_t lla, vector &position) + { + // double asq = geodetic::WGS84::a * geodetic::WGS84::a; + double esq = geodetic::WGS84::e * geodetic::WGS84::e; + double N = geodetic::WGS84::a / sqrt(1 - esq * pow(sin(lla.lat), 2)); + position.x = (N + lla.alt) * cos(lla.lat) * cos(lla.lon); + position.y = (N + lla.alt) * cos(lla.lat) * sin(lla.lon); + position.z = ((1 - esq) * N + lla.alt) * sin(lla.lat); + } + + // Output in radians! + void xyz2lla(vector position, geodetic::geodetic_coords_t &lla) + { + double asq = geodetic::WGS84::a * geodetic::WGS84::a; + double esq = geodetic::WGS84::e * geodetic::WGS84::e; + + double b = sqrt(asq * (1 - esq)); + double bsq = b * b; + double ep = sqrt((asq - bsq) / bsq); + double p = sqrt(position.x * position.x + position.y * position.y); + double th = atan2(geodetic::WGS84::a * position.z, b * p); + double lon = atan2(position.y, position.x); + double lat = atan2((position.z + ep * ep * b * pow(sin(th), 3)), (p - esq * geodetic::WGS84::a * pow(cos(th), 3))); + // double N = geodetic::WGS84::a / (sqrt(1 - esq * pow(sin(lat), 2))); + + vector g; + lla2xyz(geodetic::geodetic_coords_t(lat, lon, 0, true), g); + + double gm = sqrt(g.x * g.x + g.y * g.y + g.z * g.z); + double am = sqrt(position.x * position.x + position.y * position.y + position.z * position.z); + double alt = am - gm; + + lla = geodetic::geodetic_coords_t(lat, lon, alt, true); + } +} // namespace t +#endif int main(int argc, char *argv[]) { initLogger(); - std::ifstream data_in(argv[1], std::ios::binary); + logger->trace("NOVAS_TEST\n"); - std::ofstream test_t(argv[2]); +#if 1 + // SuperNOVAS variables used for the calculations -------------------------> + novas_orbital orbit = NOVAS_ORBIT_INIT; // Orbital parameters + object source; // a celestial object: sidereal, planet, ephemeris or orbital source + observer obs; // observer location + novas_timespec obs_time; // astrometric time of observation + novas_frame obs_frame; // observing frame defined for observing time and location + enum novas_accuracy accuracy; // NOVAS_FULL_ACCURACY or NOVAS_REDUCED_ACCURACY + sky_pos apparent; // calculated precise observed (apparent) position of source - uint8_t frm[528]; + // Calculated quantities -------------------------------------------------> + double az, el; // calculated azimuth and elevation at observing site - const uint8_t pm_sequence[] = {0xad, 0x43, 0xc4, 0x7e, 0x31, 0x6c, 0x28, 0xae, // - 0xde, 0x63, 0xd0, 0x93, 0x2f, 0x10, 0xf0, 0x07, // - 0xc2, 0x0e, 0x8c, 0xdf, 0x6b, 0x12, 0xe1, 0x83, // - 0x27, 0x56, 0xe3, 0x92, 0xa3, 0xb3, 0xbb, 0xfd, // - 0x6e, 0x7b, 0x1a, 0xa7, 0x90, 0xb2, 0x37, 0x5e, // - 0xa5, 0x81, 0x36, 0xd2, 0x06, 0xca, 0xcc, 0x7e, // - 0x73, 0x5c, 0xb4, 0x05, 0xd3, 0x8a, 0x69, 0x87, // - 0x04, 0x5f, 0x29, 0x22}; + // Intermediate variables we'll use --------------------------------------> + struct timespec unix_time; // Standard precision UNIX time structure - while (!data_in.eof()) + // We'll print debugging messages and error traces... + novas_debug(NOVAS_DEBUG_ON); + +#if 1 + // ------------------------------------------------------------------------- + // We'll use the CALCEPH library to provide ephemeris data + + // First open one or more ephemeris files with CALCEPH to use + // E.g. the DE440 (short-term) ephemeris data from JPL. + const char *arrr[] = { + "/home/alan/Downloads/juice_orbc_000082_230414_310721_v01.bsp", // + "/home/alan/Downloads/de440s.bsp", // + "/home/alan/Downloads/jwst_pred.bsp" // + }; + t_calcephbin *de440 = calceph_open_array(2, arrr); //// calceph_open("/home/alan/Downloads/de440s.bsp"); + if (!de440) { - // Read buffer - data_in.read((char *)frm, 528); - - memset(frm, 0, 528); - memcpy(frm, pm_sequence, 60); - - test_t.write((char *)frm, 528); + fprintf(stderr, "ERROR! could not open ephemeris data\n"); + return 1; } + + // calceph_prefetch(de440); + +#if 1 + // Try to list + { + struct ObjEntry + { + }; + + int count = calceph_getpositionrecordcount(de440); + logger->info(count); + for (int i = 0; i < count; i++) + { + int target; + int center; + double firsttime; + double lasttime; + int frame; + calceph_getpositionrecordindex(de440, i + 1, &target, ¢er, &firsttime, &lasttime, &frame); + + // t_calcephcharvalue objname; + // calceph_getnamebyidss(de440, target, 1, objname); + // logger->trace(objname); + + char timestamp1[40], timestamp2[40]; + novas_timespec timespec1, timespec2; + novas_set_time(novas_timescale::NOVAS_TAI, firsttime, LEAP_SECONDS, DUT1, ×pec1); + novas_set_time(novas_timescale::NOVAS_TAI, lasttime, LEAP_SECONDS, DUT1, ×pec2); + + novas_iso_timestamp(×pec1, timestamp1, sizeof(timestamp1)); + novas_iso_timestamp(×pec2, timestamp2, sizeof(timestamp2)); + + logger->info("- Body ID %d || %s %s", /* std::string(objname).c_str(),*/ target, timestamp1, timestamp2); + } + } + + // return 1; +#endif + + // Make de440 provide ephemeris data for the major planets. + novas_use_calceph(de440); +#elif 1 + cspice_add_kernel("/home/alan/Downloads/de440s.bsp"); + cspice_add_kernel("/home/alan/Downloads/juice_orbc_000082_230414_310721_v01.bsp"); + cspice_add_kernel("/home/alan/Downloads/jwst_pred.bsp"); + + novas_use_cspice(); +#endif + + // Orbitals assume Keplerian motion, and are never going to be accurate much below the + // tens of arcsec level even for the most current MPC orbits. Orbitals for planetary + // satellites are even less precise. So, with orbitals, there is no point on pressing + // for ultra-high (sub-uas level) accuracy... + accuracy = NOVAS_FULL_ACCURACY; // NOVAS_REDUCED_ACCURACY; // mas-level precision, typically + + // ------------------------------------------------------------------------- + // Define a sidereal source + +#if 0 + // Orbital Parameters for the asteroid Ceres from the Minor Planet Center + // (MPC) at JD 2460600.5 + orbit.jd_tdb = 2460600.5; // [day] TDB date + orbit.a = 2.7666197; // [AU] + orbit.e = 0.079184; + orbit.i = 10.5879; // [deg] + orbit.omega = 73.28579; // [deg] + orbit.Omega = 80.25414; // [deg] + orbit.M0 = 145.84905; // [deg] + orbit.n = 0.21418047; // [deg/day] + + // Define Ceres as the observed object (we can use whatever ID numbering + // system here, since it's irrelevant to SuperNOVAS in this context). + make_orbital_object("Ceres", 2000001, &orbit, &source); +#elif 0 + // ... Or, you could define orbitals for a satellite instead: + + // E.g. Callisto's orbital parameters from JPL Horizons + // https://ssd.jpl.nasa.gov/sats/elem/sep.html + // 1882700. 0.007 43.8 87.4 0.3 309.1 16.690440 277.921 577.264 268.7 64.8 + orbit.system.center = NOVAS_JUPITER; + novas_set_orbsys_pole(NOVAS_GCRS, 268.7 / 15.0, 64.8, &orbit.system); + + orbit.jd_tdb = NOVAS_JD_J2000; + orbit.a = 1882700.0 * 1e3 / NOVAS_AU; + orbit.e = 0.007; + orbit.omega = 43.8; + orbit.M0 = 87.4; + orbit.i = 0.3; + orbit.Omega = 309.1; + orbit.n = TWOPI / 16.690440; + orbit.apsis_period = 277.921 * 365.25; + orbit.node_period = 577.264 * 365.25; + + // Set Callisto as the observed object + make_orbital_object("Callisto", 501, &orbit, &source); +#elif 1 + make_planet(NOVAS_MOON, &source); + // make_planet(NOVAS_SUN, &source); + // make_planet(NOVAS_MERCURY, &source); + // make_ephem_object("STEREO-A", -234, &source); + // make_ephem_object("Io", 501, &source); + // make_ephem_object("JWST", -170, &source); + // make_ephem_object("JUICE", -28, &source); +#endif + + // ------------------------------------------------------------------------- + // Define observer somewhere on Earth (we can also define observers in Earth + // or Sun orbit, at the geocenter or at the Solary-system barycenter...) + + // Specify the location we are observing from + // 50.7374 deg N, 7.0982 deg E, 60m elevation + // (We'll ignore the local weather parameters here, but you can set those too.) + if (make_observer_at_geocenter(&obs)) + // if (make_observer_on_surface(48.0, 1.8, 173.0, 0.0, 0.0, &obs) != 0) + { + fprintf(stderr, "ERROR! defining Earth-based observer location.\n"); + return 1; + } + + observer obs2; + make_observer_on_surface(48.0, 1.8, 173.0, 0.0, 0.0, &obs2); + + while (1) + { + sleep(1); + + // ------------------------------------------------------------------------- + // Set the astrometric time of observation... + + // Get the current system time, with up to nanosecond resolution... + clock_gettime(CLOCK_REALTIME, &unix_time); + + // Set the time of observation to the precise UTC-based UNIX time + // (We can set astromtric time using an other time measure also...) + if (novas_set_unix_time(unix_time.tv_sec, unix_time.tv_nsec, LEAP_SECONDS, DUT1, &obs_time) != 0) + { + fprintf(stderr, "ERROR! failed to set time of observation.\n"); + continue; + } + + // ... Or you could set a time explicily in any known timescale. + /* + // Let's set a TDB-based time for the start of the J2000 epoch exactly... + if(novas_set_time(NOVAS_TDB, NOVAS_JD_J2000, 32, 0.0, &obs_time) != 0) { + fprintf(stderr, "ERROR! failed to set time of observation.\n"); + return 1; + } + */ + + // ------------------------------------------------------------------------- + // You might want to set a provider for precise planet positions so we might + // calculate Earth, Sun and major planet positions accurately. It is needed + // if you have orbitals defined around a major planet. + // + // There are many ways to set a provider of planet positions. For example, + // you may use the CALCEPH library: + // + // t_calcephbin *planets = calceph_open("path/to/de440s.bsp"); + // novas_use_calceph(planets); + + // ------------------------------------------------------------------------- + // Initialize the observing frame with the given observing and Earth + // orientation patameters. + // + if (novas_make_frame(accuracy, &obs, &obs_time, POLAR_DX, POLAR_DY, &obs_frame) != 0) + { + fprintf(stderr, "ERROR! failed to define observing frame.\n"); + continue; + } + + // ------------------------------------------------------------------------- + // Calculate the precise apparent position (e.g. in CIRS). + if (novas_sky_pos(&source, &obs_frame, NOVAS_CIRS, &apparent) != 0) + { + fprintf(stderr, "ERROR! failed to calculate apparent position.\n"); + continue; + } + + // Let's print the apparent position + // (Note, CIRS R.A. is relative to CIO, not the true equinox of date.) + printf(" RA = %.9f deg, Dec = %.9f deg, rad_vel = %.6f km/s, distance = %.6f km", apparent.ra * 15., apparent.dec, apparent.rv, (apparent.dis * NOVAS_AU) / 1e3); + + // ------------------------------------------------------------------------- + // Convert the apparent position in CIRS on sky to horizontal coordinates + // We'll use a standard (fixed) atmospheric model to estimate an optical refraction + // (You might use other refraction models, or NULL to ignore refraction corrections) + // if (novas_app_to_hor(&obs_frame, NOVAS_CIRS, apparent.ra, apparent.dec, novas_standard_refraction, &az, &el) != 0) + // { + // fprintf(stderr, "ERROR! failed to calculate azimuth / elevation.\n"); + // return 1; + // } + + // double jd_tt = novas_get_time(&obs_time, novas_timescale::NOVAS_TT); + +#if ENABLE_CUSTOM_AZ_EL + double pos[3], vel[3]; + // if (novas_orbit_posvel((obs_time.ijd_tt + obs_time.fjd_tt) + obs_time.tt2tdb, &orbit, NOVAS_FULL_ACCURACY, pos,vel)) + if (novas_geom_posvel(&source, &obs_frame, novas_reference_system::NOVAS_CIRS, pos, vel)) + { + fprintf(stderr, "ERROR! failed to calculate pos / vel.\n"); + return 1; + } + + double pos2[3]; + if (cirs_to_itrs(/*double jd_tt_high*/ obs_time.ijd_tt, /*double jd_tt_low*/ obs_time.fjd_tt, obs_time.ut1_to_tt, NOVAS_FULL_ACCURACY, POLAR_DX * 1e3, POLAR_DY * 1e3, pos, pos2)) + { + fprintf(stderr, "ERROR! failed to calculate CIRS => ITRS.\n"); + return 1; + } + + geodetic::geodetic_coords_t c; + t::xyz2lla({pos2[0] * NOVAS_AU_KM, pos2[1] * NOVAS_AU_KM, pos2[2] * NOVAS_AU_KM}, c); + c.toDegs(); + + // printf(" X %.6f Y %.6f Z %.6f (%.6f, %.6f, %.6f Km)", (pos2[0] * NOVAS_AU) / 1e3, (pos2[1] * NOVAS_AU) / 1e3, (pos2[2] * NOVAS_AU) / 1e3, c.lat, c.lon, c.alt); + + // novas_track tr; + // novas_equ_track(&source, &obs_frame, 0.00001, &tr); + // printf(" Lat = %.2f deg, Lon = %.6f deg ", tr.pos.lat, tr.pos.lon); + + geodetic::geodetic_coords_t obs(48.0, 1.8, 173.0 / 1e3); + auto v = geodetic::calc_azel(obs, c); + printf(" Az2 = %.6f deg, El2 = %.6f deg ||| ", v.az - 180, v.el); +#endif + + /*double dx, dy; + // iau2000a(jd_tt, 0, &dx, &dy); + double jd_tt2 = novas_get_time(&obs_time, novas_timescale::NOVAS_TT); + nutation_angles((jd_tt2 - 2451545.0) / 36525.0, NOVAS_FULL_ACCURACY, &dx, &dy); + printf("JD %f DX %f %f, DY %f %f ", jd_tt, dx * NOVAS_ARCSEC, POLAR_DX, dy * NOVAS_ARCSEC, POLAR_DY); +*/ + +#if 0 + { + novas_track ttt; + novas_equ_track(&source, &obs_frame, 0.000001, &ttt); + printf(" Lat = %f Lon = %f Dist = %f Km", ttt.pos.lat, ttt.pos.lon, ttt.pos.dist * NOVAS_AU_KM); + } +#endif + + novas_frame obs_frame2; + novas_make_frame(accuracy, &obs2, &obs_time, POLAR_DX, POLAR_DY, &obs_frame2); + sky_pos apparent2; + novas_sky_pos(&source, &obs_frame2, NOVAS_CIRS, &apparent2); + novas_app_to_hor(&obs_frame2, NOVAS_CIRS, apparent2.ra, apparent2.dec, NULL, &az, &el); + // Let's print the calculated azimuth and elevation + printf(" Az = %.6f deg, El = %.6f deg\n", az, el); + } +#endif + return 0; } diff --git a/src-testing/main_novas.cpp b/src-testing/main_novas.cpp deleted file mode 100644 index 447c06dfd..000000000 --- a/src-testing/main_novas.cpp +++ /dev/null @@ -1,379 +0,0 @@ -/********************************************************************** - * This file is used for testing random stuff without running the - * whole of SatDump, which comes in handy for debugging individual - * elements before putting them all together in modules... - * - * If you are an user, ignore this file which will not be built by - * default, and if you're a developper in need of doing stuff here... - * Go ahead! - * - * Don't judge the code you might see in there! :) - **********************************************************************/ - -#include "common/geodetic/calc_azel.h" -#include "common/geodetic/geodetic_coordinates.h" -#include "common/geodetic/wgs84.h" -#include "common/utils.h" -#include "logger.h" -#include "nutation.h" -#include -#include -#include -#include -#include - -#if 1 -extern "C" -{ -#include - -#include -#include -} - -// Below are some Earth orientation values. Here we define them as constants, but they may -// of course be variables. They should be set to the appropriate values for the time -// of observation based on the IERS Bulletins... - -#define LEAP_SECONDS 37 ///< [s] current leap seconds from IERS Bulletin C -#define DUT1 0.114 ///< [s] current UT1 - UTC time difference from IERS Bulletin A -#define POLAR_DX (0.0863 / 1000.0) // 230.0 ///< [mas] Earth polar offset x, e.g. from IERS Bulletin A. -#define POLAR_DY (0.4178 / 1000.0) // -62.0 ///< [mas] Earth polar offset y, e.g. from IERS Bulletin A. -#endif - -#define ENABLE_CUSTOM_AZ_EL 0 - -#if ENABLE_CUSTOM_AZ_EL -namespace t -{ - struct vector - { - double x; - double y; - double z; - }; - - // Must already be in radians! - void lla2xyz(geodetic::geodetic_coords_t lla, vector &position) - { - // double asq = geodetic::WGS84::a * geodetic::WGS84::a; - double esq = geodetic::WGS84::e * geodetic::WGS84::e; - double N = geodetic::WGS84::a / sqrt(1 - esq * pow(sin(lla.lat), 2)); - position.x = (N + lla.alt) * cos(lla.lat) * cos(lla.lon); - position.y = (N + lla.alt) * cos(lla.lat) * sin(lla.lon); - position.z = ((1 - esq) * N + lla.alt) * sin(lla.lat); - } - - // Output in radians! - void xyz2lla(vector position, geodetic::geodetic_coords_t &lla) - { - double asq = geodetic::WGS84::a * geodetic::WGS84::a; - double esq = geodetic::WGS84::e * geodetic::WGS84::e; - - double b = sqrt(asq * (1 - esq)); - double bsq = b * b; - double ep = sqrt((asq - bsq) / bsq); - double p = sqrt(position.x * position.x + position.y * position.y); - double th = atan2(geodetic::WGS84::a * position.z, b * p); - double lon = atan2(position.y, position.x); - double lat = atan2((position.z + ep * ep * b * pow(sin(th), 3)), (p - esq * geodetic::WGS84::a * pow(cos(th), 3))); - // double N = geodetic::WGS84::a / (sqrt(1 - esq * pow(sin(lat), 2))); - - vector g; - lla2xyz(geodetic::geodetic_coords_t(lat, lon, 0, true), g); - - double gm = sqrt(g.x * g.x + g.y * g.y + g.z * g.z); - double am = sqrt(position.x * position.x + position.y * position.y + position.z * position.z); - double alt = am - gm; - - lla = geodetic::geodetic_coords_t(lat, lon, alt, true); - } -} // namespace t -#endif - -int main(int argc, char *argv[]) -{ - initLogger(); - - logger->trace("NOVAS_TEST\n"); - -#if 1 - // SuperNOVAS variables used for the calculations -------------------------> - novas_orbital orbit = NOVAS_ORBIT_INIT; // Orbital parameters - object source; // a celestial object: sidereal, planet, ephemeris or orbital source - observer obs; // observer location - novas_timespec obs_time; // astrometric time of observation - novas_frame obs_frame; // observing frame defined for observing time and location - enum novas_accuracy accuracy; // NOVAS_FULL_ACCURACY or NOVAS_REDUCED_ACCURACY - sky_pos apparent; // calculated precise observed (apparent) position of source - - // Calculated quantities -------------------------------------------------> - double az, el; // calculated azimuth and elevation at observing site - - // Intermediate variables we'll use --------------------------------------> - struct timespec unix_time; // Standard precision UNIX time structure - - // We'll print debugging messages and error traces... - novas_debug(NOVAS_DEBUG_ON); - -#if 1 - // ------------------------------------------------------------------------- - // We'll use the CALCEPH library to provide ephemeris data - - // First open one or more ephemeris files with CALCEPH to use - // E.g. the DE440 (short-term) ephemeris data from JPL. - const char *arrr[] = { - "/home/alan/Downloads/juice_orbc_000082_230414_310721_v01.bsp", // - "/home/alan/Downloads/de440s.bsp", // - "/home/alan/Downloads/jwst_pred.bsp" // - }; - t_calcephbin *de440 = calceph_open_array(3, arrr); //// calceph_open("/home/alan/Downloads/de440s.bsp"); - if (!de440) - { - fprintf(stderr, "ERROR! could not open ephemeris data\n"); - return 1; - } - - // calceph_prefetch(de440); - -#if 1 - // Try to list - { - struct ObjEntry - { - }; - - int count = calceph_getpositionrecordcount(de440); - logger->info(count); - for (int i = 0; i < count; i++) - { - int target; - int center; - double firsttime; - double lasttime; - int frame; - calceph_getpositionrecordindex(de440, i + 1, &target, ¢er, &firsttime, &lasttime, &frame); - - // t_calcephcharvalue objname; - // calceph_getnamebyidss(de440, target, 1, objname); - // logger->trace(objname); - - char timestamp1[40], timestamp2[40]; - novas_timespec timespec1, timespec2; - novas_set_time(novas_timescale::NOVAS_TAI, firsttime, LEAP_SECONDS, DUT1, ×pec1); - novas_set_time(novas_timescale::NOVAS_TAI, lasttime, LEAP_SECONDS, DUT1, ×pec2); - - novas_iso_timestamp(×pec1, timestamp1, sizeof(timestamp1)); - novas_iso_timestamp(×pec2, timestamp2, sizeof(timestamp2)); - - logger->info("- Body ID %d || %s %s", /* std::string(objname).c_str(),*/ target, timestamp1, timestamp2); - } - } - - // return 1; -#endif - - // Make de440 provide ephemeris data for the major planets. - novas_use_calceph(de440); -#elif 1 - cspice_add_kernel("/home/alan/Downloads/de440s.bsp"); - cspice_add_kernel("/home/alan/Downloads/juice_orbc_000082_230414_310721_v01.bsp"); - cspice_add_kernel("/home/alan/Downloads/jwst_pred.bsp"); - - novas_use_cspice(); -#endif - - // Orbitals assume Keplerian motion, and are never going to be accurate much below the - // tens of arcsec level even for the most current MPC orbits. Orbitals for planetary - // satellites are even less precise. So, with orbitals, there is no point on pressing - // for ultra-high (sub-uas level) accuracy... - accuracy = NOVAS_FULL_ACCURACY; // NOVAS_REDUCED_ACCURACY; // mas-level precision, typically - - // ------------------------------------------------------------------------- - // Define a sidereal source - -#if 0 - // Orbital Parameters for the asteroid Ceres from the Minor Planet Center - // (MPC) at JD 2460600.5 - orbit.jd_tdb = 2460600.5; // [day] TDB date - orbit.a = 2.7666197; // [AU] - orbit.e = 0.079184; - orbit.i = 10.5879; // [deg] - orbit.omega = 73.28579; // [deg] - orbit.Omega = 80.25414; // [deg] - orbit.M0 = 145.84905; // [deg] - orbit.n = 0.21418047; // [deg/day] - - // Define Ceres as the observed object (we can use whatever ID numbering - // system here, since it's irrelevant to SuperNOVAS in this context). - make_orbital_object("Ceres", 2000001, &orbit, &source); -#elif 0 - // ... Or, you could define orbitals for a satellite instead: - - // E.g. Callisto's orbital parameters from JPL Horizons - // https://ssd.jpl.nasa.gov/sats/elem/sep.html - // 1882700. 0.007 43.8 87.4 0.3 309.1 16.690440 277.921 577.264 268.7 64.8 - orbit.system.center = NOVAS_JUPITER; - novas_set_orbsys_pole(NOVAS_GCRS, 268.7 / 15.0, 64.8, &orbit.system); - - orbit.jd_tdb = NOVAS_JD_J2000; - orbit.a = 1882700.0 * 1e3 / NOVAS_AU; - orbit.e = 0.007; - orbit.omega = 43.8; - orbit.M0 = 87.4; - orbit.i = 0.3; - orbit.Omega = 309.1; - orbit.n = TWOPI / 16.690440; - orbit.apsis_period = 277.921 * 365.25; - orbit.node_period = 577.264 * 365.25; - - // Set Callisto as the observed object - make_orbital_object("Callisto", 501, &orbit, &source); -#elif 1 - // make_planet(NOVAS_MOON, &source); - // make_planet(NOVAS_SUN, &source); - make_planet(NOVAS_MERCURY, &source); - // make_ephem_object("STEREO-A", -234, &source); - // make_ephem_object("Io", 501, &source); - // make_ephem_object("JWST", -170, &source); - // make_ephem_object("JUICE_T", -28, &source); -#endif - - // ------------------------------------------------------------------------- - // Define observer somewhere on Earth (we can also define observers in Earth - // or Sun orbit, at the geocenter or at the Solary-system barycenter...) - - // Specify the location we are observing from - // 50.7374 deg N, 7.0982 deg E, 60m elevation - // (We'll ignore the local weather parameters here, but you can set those too.) - if (make_observer_at_geocenter(&obs)) - // if (make_observer_on_surface(48.0, 1.8, 173.0, 0.0, 0.0, &obs) != 0) - { - fprintf(stderr, "ERROR! defining Earth-based observer location.\n"); - return 1; - } - - observer obs2; - make_observer_on_surface(48.0, 1.8, 173.0, 0.0, 0.0, &obs2); - - while (1) - { - sleep(1); - - // ------------------------------------------------------------------------- - // Set the astrometric time of observation... - - // Get the current system time, with up to nanosecond resolution... - clock_gettime(CLOCK_REALTIME, &unix_time); - - // Set the time of observation to the precise UTC-based UNIX time - // (We can set astromtric time using an other time measure also...) - if (novas_set_unix_time(unix_time.tv_sec, unix_time.tv_nsec, LEAP_SECONDS, DUT1, &obs_time) != 0) - { - fprintf(stderr, "ERROR! failed to set time of observation.\n"); - continue; - } - - // ... Or you could set a time explicily in any known timescale. - /* - // Let's set a TDB-based time for the start of the J2000 epoch exactly... - if(novas_set_time(NOVAS_TDB, NOVAS_JD_J2000, 32, 0.0, &obs_time) != 0) { - fprintf(stderr, "ERROR! failed to set time of observation.\n"); - return 1; - } - */ - - // ------------------------------------------------------------------------- - // You might want to set a provider for precise planet positions so we might - // calculate Earth, Sun and major planet positions accurately. It is needed - // if you have orbitals defined around a major planet. - // - // There are many ways to set a provider of planet positions. For example, - // you may use the CALCEPH library: - // - // t_calcephbin *planets = calceph_open("path/to/de440s.bsp"); - // novas_use_calceph(planets); - - // ------------------------------------------------------------------------- - // Initialize the observing frame with the given observing and Earth - // orientation patameters. - // - if (novas_make_frame(accuracy, &obs, &obs_time, POLAR_DX, POLAR_DY, &obs_frame) != 0) - { - fprintf(stderr, "ERROR! failed to define observing frame.\n"); - continue; - } - - // ------------------------------------------------------------------------- - // Calculate the precise apparent position (e.g. in CIRS). - if (novas_sky_pos(&source, &obs_frame, NOVAS_CIRS, &apparent) != 0) - { - fprintf(stderr, "ERROR! failed to calculate apparent position.\n"); - continue; - } - - // Let's print the apparent position - // (Note, CIRS R.A. is relative to CIO, not the true equinox of date.) - printf(" RA = %.9f deg, Dec = %.9f deg, rad_vel = %.6f km/s, distance = %.6f km", apparent.ra * 15., apparent.dec, apparent.rv, (apparent.dis * NOVAS_AU) / 1e3); - - // ------------------------------------------------------------------------- - // Convert the apparent position in CIRS on sky to horizontal coordinates - // We'll use a standard (fixed) atmospheric model to estimate an optical refraction - // (You might use other refraction models, or NULL to ignore refraction corrections) - // if (novas_app_to_hor(&obs_frame, NOVAS_CIRS, apparent.ra, apparent.dec, novas_standard_refraction, &az, &el) != 0) - // { - // fprintf(stderr, "ERROR! failed to calculate azimuth / elevation.\n"); - // return 1; - // } - - // double jd_tt = novas_get_time(&obs_time, novas_timescale::NOVAS_TT); - -#if ENABLE_CUSTOM_AZ_EL - double pos[3], vel[3]; - // if (novas_orbit_posvel((obs_time.ijd_tt + obs_time.fjd_tt) + obs_time.tt2tdb, &orbit, NOVAS_FULL_ACCURACY, pos,vel)) - if (novas_geom_posvel(&source, &obs_frame, novas_reference_system::NOVAS_CIRS, pos, vel)) - { - fprintf(stderr, "ERROR! failed to calculate pos / vel.\n"); - return 1; - } - - double pos2[3]; - if (cirs_to_itrs(/*double jd_tt_high*/ jd_tt, /*double jd_tt_low*/ 0, obs_time.ut1_to_tt, NOVAS_FULL_ACCURACY, POLAR_DX * 1e3, POLAR_DY * 1e3, pos, pos2)) - { - fprintf(stderr, "ERROR! failed to calculate CIRS => ITRS.\n"); - return 1; - } - - geodetic::geodetic_coords_t c; - t::xyz2lla({(pos2[0] * NOVAS_AU) / 1e3, (pos2[1] * NOVAS_AU) / 1e3, (pos2[2] * NOVAS_AU) / 1e3}, c); - c.toDegs(); - - // printf(" X %.6f Y %.6f Z %.6f (%.6f, %.6f, %.6f Km)", (pos2[0] * NOVAS_AU) / 1e3, (pos2[1] * NOVAS_AU) / 1e3, (pos2[2] * NOVAS_AU) / 1e3, c.lat, c.lon, c.alt); - - // novas_track tr; - // novas_equ_track(&source, &obs_frame, 0.00001, &tr); - // printf(" Lat = %.2f deg, Lon = %.6f deg ", tr.pos.lat, tr.pos.lon); - - geodetic::geodetic_coords_t obs(48.0, 1.8, 173.0 / 1e3); - auto v = geodetic::calc_azel(obs, c); - printf(" Az2 = %.6f deg, El2 = %.6f deg ||| ", v.az, v.el); -#endif - - /*double dx, dy; - // iau2000a(jd_tt, 0, &dx, &dy); - double jd_tt2 = novas_get_time(&obs_time, novas_timescale::NOVAS_TT); - nutation_angles((jd_tt2 - 2451545.0) / 36525.0, NOVAS_FULL_ACCURACY, &dx, &dy); - printf("JD %f DX %f %f, DY %f %f ", jd_tt, dx * NOVAS_ARCSEC, POLAR_DX, dy * NOVAS_ARCSEC, POLAR_DY); -*/ - - novas_frame obs_frame2; - novas_make_frame(accuracy, &obs2, &obs_time, POLAR_DX, POLAR_DY, &obs_frame2); - sky_pos apparent2; - novas_sky_pos(&source, &obs_frame2, NOVAS_CIRS, &apparent2); - novas_app_to_hor(&obs_frame2, NOVAS_CIRS, apparent2.ra, apparent2.dec, NULL, &az, &el); - // Let's print the calculated azimuth and elevation - printf(" Az = %.6f deg, El = %.6f deg\n", az, el); - } -#endif - return 0; -} diff --git a/src-testing/main_sg.cpp b/src-testing/main_sg.cpp new file mode 100644 index 000000000..cd7a5c725 --- /dev/null +++ b/src-testing/main_sg.cpp @@ -0,0 +1,93 @@ +/********************************************************************** + * This file is used for testing random stuff without running the + * whole of SatDump, which comes in handy for debugging individual + * elements before putting them all together in modules... + * + * If you are an user, ignore this file which will not be built by + * default, and if you're a developper in need of doing stuff here... + * Go ahead! + * + * Don't judge the code you might see in there! :) + **********************************************************************/ + +#include "image/image.h" +#include "image/io.h" +#include "logger.h" +#include +#include +#include + +#include "common/ccsds/ccsds_aos/demuxer.h" +#include "common/ccsds/ccsds_aos/vcdu.h" + +int main(int argc, char *argv[]) +{ + initLogger(); + completeLoggerInit(); + + uint8_t cadu[1024]; + + std::ifstream data_in(argv[1]); + std::ofstream data_ou(argv[2]); + + ccsds::ccsds_aos::Demuxer demuxer_vcid(884, false); + + std::vector img_vec; + + while (!data_in.eof()) + { + data_in.read((char *)cadu, 1024); + + // Parse this transport frame + ccsds::ccsds_aos::VCDU vcdu = ccsds::ccsds_aos::parseVCDU(cadu); + + // printf("VCID %d\n", vcdu.vcid); + + std::vector ccsdsFrames = demuxer_vcid.work(cadu); + for (ccsds::CCSDSPacket &pkt : ccsdsFrames) + { + // printf("APID %d\n", pkt.header.apid); + +#if 1 // Img? + if (pkt.header.apid == 1443) // pkt.header.apid == 1440 || pkt.header.apid == 1443 || pkt.header.apid == 1444) + { + int mkr = pkt.payload[45]; + + printf("LEN %d %d MKR %d\n", pkt.header.sequence_flag, pkt.payload.size() + 6, mkr); + + // if (mkr == 23) + { + pkt.payload.resize(400 - 6); + + data_ou.write((char *)pkt.header.raw, 6); + data_ou.write((char *)pkt.payload.data(), pkt.payload.size()); + } + } + // else + // printf("APID %d\n", pkt.header.apid); +#endif + +#if 0 // "MHS" + if (pkt.header.apid == 1104) + { + printf("LEN %d %d\n", pkt.header.sequence_flag, pkt.payload.size() + 6); + + for (int i = 0; i < 1542; i++) + { + uint16_t v = pkt.payload[28 + 2 * i + 0] << 8 | pkt.payload[28 + 2 * i + 1]; + v += 32767; + img_vec.push_back(v); + } + + pkt.payload.resize(4000 - 6, 0); + + data_ou.write((char *)pkt.header.raw, 6); + data_ou.write((char *)pkt.payload.data(), pkt.payload.size()); + } +#endif + } + } + + image::Image img(img_vec.data(), 16, 1542, img_vec.size() / 1542, 1); + image::save_png(img, "/tmp/test.png"); +} \ No newline at end of file diff --git a/src-testing/main_snd.cpp b/src-testing/main_snd.cpp new file mode 100644 index 000000000..d666c2b52 --- /dev/null +++ b/src-testing/main_snd.cpp @@ -0,0 +1,61 @@ +/********************************************************************** + * This file is used for testing random stuff without running the + * whole of SatDump, which comes in handy for debugging individual + * elements before putting them all together in modules... + * + * If you are an user, ignore this file which will not be built by + * default, and if you're a developper in need of doing stuff here... + * Go ahead! + * + * Don't judge the code you might see in there! :) + **********************************************************************/ + +#include "logger.h" + +#include "common/ccsds/ccsds_tm/demuxer.h" +#include "common/ccsds/ccsds_tm/vcdu.h" +#include "common/simple_deframer.h" +#include + +#include "image/image.h" +#include "image/io.h" +#include "image/processing.h" + +#include + +#include "common/repack.h" + +#include "image/bayer/bayer.h" + +#include "common/codings/reedsolomon/reedsolomon.h" + +int main(int argc, char *argv[]) +{ + initLogger(); + + std::ifstream data_in(argv[1], std::ios::binary); + + std::ofstream test_t(argv[2]); + + uint8_t frm[528]; + + const uint8_t pm_sequence[] = {0xad, 0x43, 0xc4, 0x7e, 0x31, 0x6c, 0x28, 0xae, // + 0xde, 0x63, 0xd0, 0x93, 0x2f, 0x10, 0xf0, 0x07, // + 0xc2, 0x0e, 0x8c, 0xdf, 0x6b, 0x12, 0xe1, 0x83, // + 0x27, 0x56, 0xe3, 0x92, 0xa3, 0xb3, 0xbb, 0xfd, // + 0x6e, 0x7b, 0x1a, 0xa7, 0x90, 0xb2, 0x37, 0x5e, // + 0xa5, 0x81, 0x36, 0xd2, 0x06, 0xca, 0xcc, 0x7e, // + 0x73, 0x5c, 0xb4, 0x05, 0xd3, 0x8a, 0x69, 0x87, // + 0x04, 0x5f, 0x29, 0x22}; + + while (!data_in.eof()) + { + // Read buffer + data_in.read((char *)frm, 528); + + memset(frm, 0, 528); + memcpy(frm, pm_sequence, 60); + + test_t.write((char *)frm, 528); + } +} diff --git a/src-testing/mwr.h b/src-testing/mwr.h new file mode 100644 index 000000000..5d7a53d36 --- /dev/null +++ b/src-testing/mwr.h @@ -0,0 +1,17 @@ +#pragma once + +#include +namespace metopsg +{ + namespace instruments + { + namespace mwr + { + class MWRReader + { + private: + std::vector + }; + } // namespace mwr + } // namespace instruments +} // namespace metopsg \ No newline at end of file